import { useState } from 'react';
import type { AuditLogEntry, DeidentifyTask } from '../DeidentifyPanel';
import { MOCK_AUDIT_LOGS } from '../DeidentifyPanel';

function getAuditResultClass(type: AuditLogEntry['resultType']): string {
  switch (type) {
    case '성공':
      return 'text-emerald-400 bg-emerald-500/10';
    case '진행중':
      return 'text-cyan-400 bg-cyan-500/10';
    case '실패':
      return 'text-red-400 bg-red-500/10';
    case '거부':
      return 'text-yellow-400 bg-yellow-500/10';
  }
}

interface AuditLogModalProps {
  task: DeidentifyTask;
  onClose: () => void;
}

export function AuditLogModal({ task, onClose }: AuditLogModalProps) {
  const logs = MOCK_AUDIT_LOGS[task.id] ?? [];
  const [selectedLog, setSelectedLog] = useState<AuditLogEntry | null>(null);
  const [filterOperator, setFilterOperator] = useState('모두');
  const [startDate, setStartDate] = useState('2026-04-01');
  const [endDate, setEndDate] = useState('2026-04-11');

  const operators = ['모두', ...Array.from(new Set(logs.map((l) => l.operator)))];
  const filteredLogs = logs.filter((l) => {
    if (filterOperator !== '모두' && l.operator !== filterOperator) return false;
    return true;
  });

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
      <div className="bg-bg-card border border-stroke rounded-lg shadow-2xl w-full max-w-5xl max-h-[85vh] flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between px-5 py-3 border-b border-stroke shrink-0">
          <h3 className="text-body-2 font-semibold text-t1">감시 감독 (감사로그) — {task.name}</h3>
          <button
            onClick={onClose}
            className="text-t3 hover:text-t1 transition-colors text-lg leading-none"
          >
            ✕
          </button>
        </div>

        {/* 필터 바 */}
        <div className="flex items-center gap-3 px-5 py-2.5 border-b border-stroke shrink-0 bg-bg-base">
          <span className="text-caption text-t3">기간:</span>
          <input
            type="date"
            value={startDate}
            onChange={(e) => setStartDate(e.target.value)}
            className="px-2 py-1 text-caption rounded bg-bg-elevated border border-stroke text-t1 focus:outline-none focus:border-color-accent"
          />
          <span className="text-caption text-t3">~</span>
          <input
            type="date"
            value={endDate}
            onChange={(e) => setEndDate(e.target.value)}
            className="px-2 py-1 text-caption rounded bg-bg-elevated border border-stroke text-t1 focus:outline-none focus:border-color-accent"
          />
          <span className="text-caption text-t3 ml-2">작업자:</span>
          <select
            value={filterOperator}
            onChange={(e) => setFilterOperator(e.target.value)}
            className="px-2 py-1 text-caption rounded bg-bg-elevated border border-stroke text-t1 focus:outline-none focus:border-color-accent"
          >
            {operators.map((op) => (
              <option key={op} value={op}>
                {op}
              </option>
            ))}
          </select>
        </div>

        {/* 로그 테이블 */}
        <div className="flex-1 overflow-auto px-5 py-3">
          <table className="w-full text-caption border-collapse">
            <thead>
              <tr className="bg-bg-elevated text-t3 uppercase tracking-wide">
                {['시간', '작업자', '작업', '대상 데이터', '결과', '상세'].map((h) => (
                  <th
                    key={h}
                    className="px-3 py-2 text-left font-medium border-b border-stroke whitespace-nowrap"
                  >
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filteredLogs.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-3 py-8 text-center text-t3">
                    감사로그가 없습니다.
                  </td>
                </tr>
              ) : (
                filteredLogs.map((log) => (
                  <tr
                    key={log.id}
                    className={`border-b border-stroke hover:bg-bg-surface/50 cursor-pointer ${selectedLog?.id === log.id ? 'bg-bg-surface/70' : ''}`}
                    onClick={() => setSelectedLog(log)}
                  >
                    <td className="px-3 py-2 text-t2 whitespace-nowrap font-mono">
                      {log.time.split(' ')[1]}
                    </td>
                    <td className="px-3 py-2 text-t1 whitespace-nowrap">{log.operator}</td>
                    <td className="px-3 py-2 text-t2 whitespace-nowrap">{log.action}</td>
                    <td className="px-3 py-2 text-t2 whitespace-nowrap font-mono">
                      {log.targetData}
                    </td>
                    <td className="px-3 py-2">
                      <span
                        className={`inline-block px-2 py-0.5 rounded text-label-2 font-medium ${getAuditResultClass(log.resultType)}`}
                      >
                        {log.result}
                      </span>
                    </td>
                    <td className="px-3 py-2">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelectedLog(log);
                        }}
                        className="px-2 py-0.5 text-label-2 rounded bg-bg-elevated hover:bg-bg-card text-color-accent transition-colors whitespace-nowrap"
                      >
                        보기
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* 로그 상세 정보 */}
        {selectedLog && (
          <div className="px-5 py-3 border-t border-stroke shrink-0 bg-bg-base">
            <h4 className="text-caption font-semibold text-t1 mb-2">로그 상세 정보</h4>
            <div className="bg-bg-elevated border border-stroke rounded p-3 text-caption grid grid-cols-2 gap-x-6 gap-y-1.5">
              <div>
                <span className="text-t3">로그ID:</span>{' '}
                <span className="text-t1 font-mono">{selectedLog.id}</span>
              </div>
              <div>
                <span className="text-t3">타임스탬프:</span>{' '}
                <span className="text-t1 font-mono">{selectedLog.time}</span>
              </div>
              <div>
                <span className="text-t3">작업자:</span>{' '}
                <span className="text-t1">
                  {selectedLog.operator} ({selectedLog.operatorId})
                </span>
              </div>
              <div>
                <span className="text-t3">작업 유형:</span>{' '}
                <span className="text-t1">{selectedLog.action}</span>
              </div>
              <div>
                <span className="text-t3">대상:</span>{' '}
                <span className="text-t1">
                  {selectedLog.targetData} ({selectedLog.detail.dataCount.toLocaleString()}건)
                </span>
              </div>
              <div>
                <span className="text-t3">적용 규칙:</span>{' '}
                <span className="text-t1">{selectedLog.detail.rulesApplied}</span>
              </div>
              <div>
                <span className="text-t3">결과:</span>{' '}
                <span className="text-t1">
                  {selectedLog.result} (처리: {selectedLog.detail.processedCount.toLocaleString()},
                  오류: {selectedLog.detail.errorCount})
                </span>
              </div>
              <div>
                <span className="text-t3">IP 주소:</span>{' '}
                <span className="text-t1 font-mono">{selectedLog.ip}</span>
              </div>
              <div>
                <span className="text-t3">브라우저:</span>{' '}
                <span className="text-t1">{selectedLog.browser}</span>
              </div>
            </div>
          </div>
        )}

        {/* 하단 버튼 */}
        <div className="flex items-center justify-end gap-2 px-5 py-3 border-t border-stroke shrink-0">
          <button className="px-3 py-1.5 text-caption rounded bg-bg-elevated hover:bg-bg-card text-t2 transition-colors">
            상세내용 다운로드 (암호화됨)
          </button>
          <button className="px-3 py-1.5 text-caption rounded bg-bg-elevated hover:bg-bg-card text-t2 transition-colors">
            기간별 보고서 생성
          </button>
          <button
            onClick={onClose}
            className="px-3 py-1.5 text-caption rounded bg-bg-elevated hover:bg-bg-card text-t2 transition-colors"
          >
            닫기
          </button>
        </div>
      </div>
    </div>
  );
}
