import { useState, useEffect, useCallback } from 'react';
import { TaskTable } from './contents/TaskTable';
import { AuditLogModal } from './contents/AuditLogModal';
import { WizardModal } from './contents/WizardModal';
/* eslint-disable react-refresh/only-export-components */

// ─── 타입 ──────────────────────────────────────────────────

export type TaskStatus = '완료' | '진행중' | '대기' | '오류';

export interface AuditLogEntry {
  id: string;
  time: string;
  operator: string;
  operatorId: string;
  action: string;
  targetData: string;
  result: string;
  resultType: '성공' | '실패' | '거부' | '진행중';
  ip: string;
  browser: string;
  detail: {
    dataCount: number;
    rulesApplied: string;
    processedCount: number;
    errorCount: number;
  };
}

export interface DeidentifyTask {
  id: string;
  name: string;
  target: string;
  status: TaskStatus;
  startTime: string;
  progress: number;
  createdBy: string;
}

export type SourceType = 'db' | 'file' | 'api';
export type ProcessMode = 'immediate' | 'scheduled' | 'oneshot';
export type RepeatType = 'daily' | 'weekly' | 'monthly';
export type DeidentifyTechnique = '마스킹' | '삭제' | '범주화' | '암호화' | '샘플링' | '가명처리' | '유지';

export interface FieldConfig {
  name: string;
  dataType: string;
  technique: DeidentifyTechnique;
  configValue: string;
  selected: boolean;
}

export interface DbConfig {
  host: string;
  port: string;
  database: string;
  tableName: string;
}

export interface ApiConfig {
  url: string;
  method: 'GET' | 'POST';
}

export interface ScheduleConfig {
  hour: string;
  repeatType: RepeatType;
  weekday: string;
  startDate: string;
  notifyOnComplete: boolean;
  notifyOnError: boolean;
}

export interface OneshotConfig {
  date: string;
  hour: string;
}

export interface WizardState {
  step: number;
  taskName: string;
  sourceType: SourceType;
  dbConfig: DbConfig;
  apiConfig: ApiConfig;
  fields: FieldConfig[];
  processMode: ProcessMode;
  scheduleConfig: ScheduleConfig;
  oneshotConfig: OneshotConfig;
  saveAsTemplate: boolean;
  applyTemplate: string;
  confirmed: boolean;
}

// ─── Mock 데이터 ────────────────────────────────────────────

export const MOCK_TASKS: DeidentifyTask[] = [
  {
    id: '001',
    name: 'customer_2024',
    target: '선박/운항 - 선장·선원 성명',
    status: '완료',
    startTime: '2026-04-10 14:30',
    progress: 100,
    createdBy: '관리자',
  },
  {
    id: '002',
    name: 'transaction_04',
    target: '사고 현장 - 현장사진, 영상내 인물',
    status: '진행중',
    startTime: '2026-04-10 14:15',
    progress: 82,
    createdBy: '김담당',
  },
  {
    id: '003',
    name: 'employee_info',
    target: '인사정보 - 계정, 로그인 정보',
    status: '대기',
    startTime: '2026-04-10 22:00',
    progress: 0,
    createdBy: '이담당',
  },
  {
    id: '004',
    name: 'vendor_data',
    target: 'HNS 대응 - 화학물질 취급자, 방제업체 연락처',
    status: '오류',
    startTime: '2026-04-09 13:45',
    progress: 45,
    createdBy: '관리자',
  },
  {
    id: '005',
    name: 'partner_contacts',
    target: '시스템 운영 - 관리자, 운영자 접속로그',
    status: '완료',
    startTime: '2026-04-08 09:00',
    progress: 100,
    createdBy: '박담당',
  },
];

export const DEFAULT_FIELDS: FieldConfig[] = [
  { name: '고객ID', dataType: '문자열', technique: '삭제', configValue: '-', selected: true },
  {
    name: '이름',
    dataType: '문자열',
    technique: '마스킹',
    configValue: '*로 치환',
    selected: true,
  },
  {
    name: '휴대폰',
    dataType: '문자열',
    technique: '마스킹',
    configValue: '010-****-****',
    selected: true,
  },
  {
    name: '주소',
    dataType: '문자열',
    technique: '범주화',
    configValue: '시/도만 표시',
    selected: true,
  },
  {
    name: '이메일',
    dataType: '문자열',
    technique: '가명처리',
    configValue: '키: random_001',
    selected: true,
  },
  {
    name: '생년월일',
    dataType: '날짜',
    technique: '범주화',
    configValue: '연도만 표시',
    selected: true,
  },
  { name: '회사', dataType: '문자열', technique: '유지', configValue: '변경 없음', selected: true },
];

export const TECHNIQUES: DeidentifyTechnique[] = [
  '마스킹',
  '삭제',
  '범주화',
  '암호화',
  '샘플링',
  '가명처리',
  '유지',
];

export const HOURS = Array.from({ length: 24 }, (_, i) => `${String(i).padStart(2, '0')}:00`);

export const WEEKDAYS = ['월', '화', '수', '목', '금', '토', '일'];

export const TEMPLATES = ['기본 개인정보', '금융데이터', '의료데이터'];

export const MOCK_AUDIT_LOGS: Record<string, AuditLogEntry[]> = {
  '001': [
    {
      id: 'LOG_20260410_001',
      time: '2026-04-10 14:30:45',
      operator: '김철수',
      operatorId: 'user_12345',
      action: '처리완료',
      targetData: 'customer_2024',
      result: '성공 (100%)',
      resultType: '성공',
      ip: '192.168.1.100',
      browser: 'Chrome 123.0',
      detail: {
        dataCount: 15240,
        rulesApplied: '마스킹 3, 범주화 2, 삭제 2',
        processedCount: 15240,
        errorCount: 0,
      },
    },
    {
      id: 'LOG_20260410_002',
      time: '2026-04-10 14:15:10',
      operator: '김철수',
      operatorId: 'user_12345',
      action: '처리시작',
      targetData: 'customer_2024',
      result: '성공',
      resultType: '성공',
      ip: '192.168.1.100',
      browser: 'Chrome 123.0',
      detail: {
        dataCount: 15240,
        rulesApplied: '마스킹 3, 범주화 2, 삭제 2',
        processedCount: 0,
        errorCount: 0,
      },
    },
    {
      id: 'LOG_20260410_003',
      time: '2026-04-10 14:10:30',
      operator: '김철수',
      operatorId: 'user_12345',
      action: '규칙설정',
      targetData: 'customer_2024',
      result: '성공',
      resultType: '성공',
      ip: '192.168.1.100',
      browser: 'Chrome 123.0',
      detail: { dataCount: 15240, rulesApplied: '7개 규칙 적용', processedCount: 0, errorCount: 0 },
    },
  ],
  '002': [
    {
      id: 'LOG_20260410_004',
      time: '2026-04-10 14:15:22',
      operator: '이영희',
      operatorId: 'user_23456',
      action: '처리시작',
      targetData: 'transaction_04',
      result: '진행중 (82%)',
      resultType: '진행중',
      ip: '192.168.1.101',
      browser: 'Firefox 124.0',
      detail: {
        dataCount: 8920,
        rulesApplied: '마스킹 2, 암호화 1, 삭제 3',
        processedCount: 7314,
        errorCount: 0,
      },
    },
  ],
  '003': [
    {
      id: 'LOG_20260410_005',
      time: '2026-04-10 13:45:30',
      operator: '박민준',
      operatorId: 'user_34567',
      action: '규칙수정',
      targetData: 'employee_info',
      result: '성공',
      resultType: '성공',
      ip: '192.168.1.102',
      browser: 'Chrome 123.0',
      detail: {
        dataCount: 3200,
        rulesApplied: '마스킹 4, 가명처리 1',
        processedCount: 0,
        errorCount: 0,
      },
    },
  ],
  '004': [
    {
      id: 'LOG_20260409_001',
      time: '2026-04-09 13:45:30',
      operator: '관리자',
      operatorId: 'user_admin',
      action: '처리오류',
      targetData: 'vendor_data',
      result: '오류 (45%)',
      resultType: '실패',
      ip: '192.168.1.100',
      browser: 'Chrome 123.0',
      detail: {
        dataCount: 5100,
        rulesApplied: '마스킹 2, 범주화 1, 삭제 1',
        processedCount: 2295,
        errorCount: 12,
      },
    },
    {
      id: 'LOG_20260409_002',
      time: '2026-04-09 13:40:15',
      operator: '김철수',
      operatorId: 'user_12345',
      action: '규칙조회',
      targetData: 'vendor_data',
      result: '성공',
      resultType: '성공',
      ip: '192.168.1.100',
      browser: 'Chrome 123.0',
      detail: { dataCount: 5100, rulesApplied: '4개 규칙', processedCount: 0, errorCount: 0 },
    },
    {
      id: 'LOG_20260409_003',
      time: '2026-04-09 09:25:00',
      operator: '이영희',
      operatorId: 'user_23456',
      action: '삭제시도',
      targetData: 'vendor_data',
      result: '거부 (권한부족)',
      resultType: '거부',
      ip: '192.168.1.101',
      browser: 'Firefox 124.0',
      detail: { dataCount: 5100, rulesApplied: '-', processedCount: 0, errorCount: 0 },
    },
  ],
  '005': [
    {
      id: 'LOG_20260408_001',
      time: '2026-04-08 09:15:00',
      operator: '박담당',
      operatorId: 'user_45678',
      action: '처리완료',
      targetData: 'partner_contacts',
      result: '성공 (100%)',
      resultType: '성공',
      ip: '192.168.1.103',
      browser: 'Edge 122.0',
      detail: {
        dataCount: 1850,
        rulesApplied: '마스킹 2, 유지 3',
        processedCount: 1850,
        errorCount: 0,
      },
    },
  ],
};

function fetchTasks(): Promise<DeidentifyTask[]> {
  return new Promise((resolve) => {
    setTimeout(() => resolve(MOCK_TASKS), 300);
  });
}

// ─── 상태 뱃지 ─────────────────────────────────────────────

export function getStatusBadgeClass(status: TaskStatus): string {
  switch (status) {
    case '완료':
      return 'text-color-success bg-[rgba(34,197,94,0.1)]';
    case '진행중':
      return 'text-color-accent bg-[rgba(6,182,212,0.1)]';
    case '대기':
      return 'text-color-caution bg-[rgba(234,179,8,0.1)]';
    case '오류':
      return 'text-color-danger bg-[rgba(239,68,68,0.1)]';
  }
}

// ─── 진행률 바 ─────────────────────────────────────────────

export const TABLE_HEADERS = ['작업ID', '작업명', '대상', '상태', '시작시간', '진행률', '등록자', '액션'];

export const STEP_LABELS = ['소스선택', '데이터검증', '비식별화규칙', '처리방식', '최종확인'];

export const INITIAL_WIZARD: WizardState = {
  step: 1,
  taskName: '',
  sourceType: 'db',
  dbConfig: { host: '', port: '5432', database: '', tableName: '' },
  apiConfig: { url: '', method: 'GET' },
  fields: DEFAULT_FIELDS,
  processMode: 'immediate',
  scheduleConfig: {
    hour: '02:00',
    repeatType: 'daily',
    weekday: '월',
    startDate: '',
    notifyOnComplete: true,
    notifyOnError: true,
  },
  oneshotConfig: { date: '', hour: '02:00' },
  saveAsTemplate: false,
  applyTemplate: '',
  confirmed: false,
};

// ─── 메인 패널 ──────────────────────────────────────────────

type FilterStatus = '모두' | TaskStatus;

export default function DeidentifyPanel() {
  const [tasks, setTasks] = useState<DeidentifyTask[]>([]);
  const [loading, setLoading] = useState(false);
  const [showWizard, setShowWizard] = useState(false);
  const [auditTask, setAuditTask] = useState<DeidentifyTask | null>(null);
  const [searchName, setSearchName] = useState('');
  const [filterStatus, setFilterStatus] = useState<FilterStatus>('모두');
  const [filterPeriod, setFilterPeriod] = useState<'7' | '30' | '90'>('30');

  const loadTasks = useCallback(async () => {
    setLoading(true);
    const data = await fetchTasks();
    setTasks(data);
    setLoading(false);
  }, []);

  useEffect(() => {
    let isMounted = true;
    if (tasks.length === 0) {
      void Promise.resolve().then(() => {
        if (isMounted) void loadTasks();
      });
    }
    return () => {
      isMounted = false;
    };
  }, [tasks.length, loadTasks]);

  const handleAction = useCallback((action: string, task: DeidentifyTask) => {
    // TODO: 실제 API 연동 시 각 액션에 맞는 API 호출로 교체
    if (action === 'delete') {
      setTasks((prev) => prev.filter((t) => t.id !== task.id));
    } else if (action === 'audit') {
      setAuditTask(task);
    }
  }, []);

  const handleWizardSubmit = useCallback(
    (wizard: WizardState) => {
      const selectedFields = wizard.fields.filter((f) => f.selected).map((f) => f.name);
      const newTask: DeidentifyTask = {
        id: String(tasks.length + 1).padStart(3, '0'),
        name: wizard.taskName,
        target: selectedFields.join(', ') || '-',
        status: wizard.processMode === 'immediate' ? '진행중' : '대기',
        startTime: new Date()
          .toLocaleString('ko-KR', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false,
          })
          .replace(/\. /g, '-')
          .replace('.', ''),
        progress: 0,
        createdBy: '관리자',
      };
      setTasks((prev) => [newTask, ...prev]);
    },
    [tasks.length],
  );

  const filteredTasks = tasks.filter((t) => {
    if (searchName && !t.name.includes(searchName)) return false;
    if (filterStatus !== '모두' && t.status !== filterStatus) return false;
    return true;
  });

  const completedCount = tasks.filter((t) => t.status === '완료').length;
  const inProgressCount = tasks.filter((t) => t.status === '진행중').length;
  const errorCount = tasks.filter((t) => t.status === '오류').length;

  return (
    <div className="flex flex-col h-full overflow-hidden">
      {/* 헤더 */}
      <div className="flex items-center justify-between px-5 py-3 border-b border-stroke shrink-0">
        <h2 className="text-body-2 font-semibold text-t1">비식별화조치</h2>
        <button
          onClick={() => setShowWizard(true)}
          className="flex items-center gap-1.5 px-3 py-1.5 text-caption rounded bg-color-accent hover:bg-color-accent-muted text-white transition-colors"
        >
          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
          새 작업
        </button>
      </div>

      {/* 상태 요약 */}
      <div className="flex items-center gap-3 px-5 py-2 shrink-0 border-b border-stroke bg-bg-base">
        <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-caption bg-[rgba(34,197,94,0.1)] text-color-success">
          <span className="w-1.5 h-1.5 rounded-full bg-color-success" />
          완료 {completedCount}건
        </span>
        <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-caption bg-[rgba(6,182,212,0.1)] text-color-accent">
          <span className="w-1.5 h-1.5 rounded-full bg-color-accent" />
          진행중 {inProgressCount}건
        </span>
        {errorCount > 0 && (
          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-caption bg-[rgba(239,68,68,0.1)] text-color-danger">
            <span className="w-1.5 h-1.5 rounded-full bg-color-danger" />
            오류 {errorCount}건
          </span>
        )}
        <span className="text-caption text-t3">전체 {tasks.length}건</span>
      </div>

      {/* 검색/필터 */}
      <div className="flex items-center gap-2 px-5 py-2.5 shrink-0 border-b border-stroke">
        <input
          type="text"
          value={searchName}
          onChange={(e) => setSearchName(e.target.value)}
          placeholder="작업명 검색"
          className="px-2.5 py-1.5 text-caption rounded bg-bg-elevated border border-stroke text-t1 placeholder:text-t3 focus:outline-none focus:border-color-accent w-40"
        />
        <select
          value={filterStatus}
          onChange={(e) => setFilterStatus(e.target.value as FilterStatus)}
          className="px-2.5 py-1.5 text-caption rounded bg-bg-elevated border border-stroke text-t1 focus:outline-none focus:border-color-accent"
        >
          {(['모두', '완료', '진행중', '대기', '오류'] as FilterStatus[]).map((s) => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
        <select
          value={filterPeriod}
          onChange={(e) => setFilterPeriod(e.target.value as '7' | '30' | '90')}
          className="px-2.5 py-1.5 text-caption rounded bg-bg-elevated border border-stroke text-t1 focus:outline-none focus:border-color-accent"
        >
          <option value="7">최근 7일</option>
          <option value="30">최근 30일</option>
          <option value="90">최근 90일</option>
        </select>
      </div>

      {/* 테이블 */}
      <div className="flex-1 overflow-auto p-5">
        <TaskTable rows={filteredTasks} loading={loading} onAction={handleAction} />
      </div>

      {/* 감사로그 모달 */}
      {auditTask && <AuditLogModal task={auditTask} onClose={() => setAuditTask(null)} />}

      {/* 마법사 모달 */}
      {showWizard && (
        <WizardModal onClose={() => setShowWizard(false)} onSubmit={handleWizardSubmit} />
      )}
    </div>
  );
}
