import { useState, useEffect, useCallback } from 'react';
import { X, Search, RefreshCw, ChevronLeft, ChevronRight, Check, AlertTriangle } from 'lucide-react';
import { comms } from '@/communication';
import { KuntaeErrorCheckResult, KuntaeErrorCheckResponse } from '@/types';

interface KuntaeErrorCheckDialogProps {
  isOpen: boolean;
  onClose: () => void;
}

// 날짜를 2자리 연도로 포맷팅 (2025-01-15 -> 25-01-15)
const formatDateShort = (dateStr: string) => {
  if (!dateStr) return '';
  const parts = dateStr.split('-');
  if (parts.length === 3) {
    return `${parts[0].slice(-2)}-${parts[1]}-${parts[2]}`;
  }
  return dateStr;
};

export function KuntaeErrorCheckDialog({ isOpen, onClose }: KuntaeErrorCheckDialogProps) {
  // 날짜 상태
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  // 검사 결과
  const [okList, setOkList] = useState<KuntaeErrorCheckResult[]>([]);
  const [ngList, setNgList] = useState<KuntaeErrorCheckResult[]>([]);

  // 선택된 오류 항목
  const [selectedErrors, setSelectedErrors] = useState<Set<string>>(new Set());

  // 상태
  const [isChecking, setIsChecking] = useState(false);
  const [isFixing, setIsFixing] = useState(false);
  const [currentDate, setCurrentDate] = useState('');
  const [message, setMessage] = useState('');

  // 이번달로 초기화
  const setThisMonth = useCallback(() => {
    const now = new Date();
    const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
    const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
    setStartDate(firstDay.toISOString().split('T')[0]);
    setEndDate(lastDay.toISOString().split('T')[0]);
  }, []);

  // 이전달
  const setPrevMonth = useCallback(() => {
    const current = startDate ? new Date(startDate) : new Date();
    const firstDay = new Date(current.getFullYear(), current.getMonth() - 1, 1);
    const lastDay = new Date(current.getFullYear(), current.getMonth(), 0);
    setStartDate(firstDay.toISOString().split('T')[0]);
    setEndDate(lastDay.toISOString().split('T')[0]);
  }, [startDate]);

  // 다음달
  const setNextMonth = useCallback(() => {
    const current = startDate ? new Date(startDate) : new Date();
    const firstDay = new Date(current.getFullYear(), current.getMonth() + 1, 1);
    const lastDay = new Date(current.getFullYear(), current.getMonth() + 2, 0);
    setStartDate(firstDay.toISOString().split('T')[0]);
    setEndDate(lastDay.toISOString().split('T')[0]);
  }, [startDate]);

  // 다이얼로그 열릴 때 초기화
  useEffect(() => {
    if (isOpen) {
      setThisMonth();
      setOkList([]);
      setNgList([]);
      setSelectedErrors(new Set());
      setMessage('');
      setCurrentDate('');
    }
  }, [isOpen, setThisMonth]);

  // ESC 키 핸들러
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen && !isChecking && !isFixing) {
        onClose();
      }
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, isChecking, isFixing, onClose]);

  // 검사 실행
  const handleCheck = async () => {
    if (!startDate || !endDate) {
      setMessage('검사 기간을 설정해주세요.');
      return;
    }

    setIsChecking(true);
    setOkList([]);
    setNgList([]);
    setSelectedErrors(new Set());
    setMessage('검사 중...');

    try {
      const result = await comms.kuntaeErrorCheck(startDate, endDate) as KuntaeErrorCheckResponse;

      if (result.Success) {
        setOkList(result.OkList || []);
        setNgList(result.NgList || []);

        // 마감되지 않은 오류 항목 자동 선택
        const autoSelect = new Set<string>();
        (result.NgList || []).forEach(item => {
          if (!item.IsMagam) {
            autoSelect.add(item.Date);
          }
        });
        setSelectedErrors(autoSelect);

        setMessage(`검사 완료: 정상 ${result.OkList?.length || 0}건, 오류 ${result.NgList?.length || 0}건`);
      } else {
        setMessage(result.Message || '검사 중 오류가 발생했습니다.');
      }
    } catch (error) {
      setMessage('검사 중 오류가 발생했습니다.');
      console.error('Error checking:', error);
    } finally {
      setIsChecking(false);
      setCurrentDate('');
    }
  };

  // 오류 수정
  const handleFix = async () => {
    if (selectedErrors.size === 0) {
      setMessage('정정할 자료가 선택되지 않았습니다.');
      return;
    }

    if (!confirm('선택한 항목을 재생성 할까요?')) {
      return;
    }

    setIsFixing(true);
    setMessage('수정 중...');

    try {
      const dates = Array.from(selectedErrors);
      const result = await comms.kuntaeFixErrors(dates);

      if (result.Success) {
        setMessage('수정이 완료되었습니다. 다시 검사를 실행해주세요.');
        // 수정 후 자동으로 재검사
        setTimeout(() => handleCheck(), 500);
      } else {
        setMessage(result.Message || '수정 중 오류가 발생했습니다.');
      }
    } catch (error) {
      setMessage('수정 중 오류가 발생했습니다.');
      console.error('Error fixing:', error);
    } finally {
      setIsFixing(false);
    }
  };

  // 체크박스 토글
  const toggleError = (date: string, isMagam: boolean) => {
    if (isMagam) return; // 마감된 항목은 선택 불가

    const newSelected = new Set(selectedErrors);
    if (newSelected.has(date)) {
      newSelected.delete(date);
    } else {
      newSelected.add(date);
    }
    setSelectedErrors(newSelected);
  };

  // 전체 선택/해제
  const toggleAllErrors = () => {
    const selectableItems = ngList.filter(item => !item.IsMagam);
    if (selectedErrors.size === selectableItems.length) {
      setSelectedErrors(new Set());
    } else {
      setSelectedErrors(new Set(selectableItems.map(item => item.Date)));
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[10000]">
      <div className="glass-effect-solid rounded-xl w-[900px] max-h-[90vh] flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-white/10">
          <h2 className="text-xl font-bold text-white flex items-center gap-2">
            <AlertTriangle className="w-5 h-5 text-warning-400" />
            근태 자료 오류 확인
          </h2>
          <button
            onClick={onClose}
            disabled={isChecking || isFixing}
            className="text-white/60 hover:text-white transition-colors disabled:opacity-50"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* 검사 버튼 */}
        <div className="px-6 py-4">
          <button
            onClick={handleCheck}
            disabled={isChecking || isFixing}
            className="w-full py-4 bg-primary-500 hover:bg-primary-600 disabled:bg-gray-500
                       text-white font-bold text-xl rounded-lg transition-colors flex items-center justify-center gap-2"
          >
            {isChecking ? (
              <>
                <RefreshCw className="w-6 h-6 animate-spin" />
                검사 중...
              </>
            ) : (
              <>
                <Search className="w-6 h-6" />
                검사
              </>
            )}
          </button>
        </div>

        {/* 검사 기간 */}
        <div className="px-6 py-3 border-t border-white/10">
          <div className="flex items-center gap-4">
            <span className="text-white/70 text-sm font-medium">검사기간:</span>
            <input
              type="date"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
              className="px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white text-sm"
            />
            <span className="text-white/50">~</span>
            <input
              type="date"
              value={endDate}
              onChange={(e) => setEndDate(e.target.value)}
              className="px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white text-sm"
            />
            <div className="flex-1" />
            <button
              onClick={setPrevMonth}
              className="px-3 py-2 bg-white/10 hover:bg-white/20 rounded-lg text-white text-sm flex items-center gap-1"
            >
              <ChevronLeft className="w-4 h-4" />
              이전달
            </button>
            <button
              onClick={setThisMonth}
              className="px-3 py-2 bg-white/10 hover:bg-white/20 rounded-lg text-white text-sm"
            >
              이번달
            </button>
            <button
              onClick={setNextMonth}
              className="px-3 py-2 bg-white/10 hover:bg-white/20 rounded-lg text-white text-sm flex items-center gap-1"
            >
              다음달
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* 현재 검사 날짜 표시 */}
        {currentDate && (
          <div className="px-6 py-3 bg-black/30 text-center">
            <span className="text-4xl font-mono text-green-400">{currentDate}</span>
          </div>
        )}

        {/* 결과 테이블 영역 */}
        <div className="flex-1 overflow-auto px-6 py-4 space-y-4">
          {/* 정상 목록 */}
          {okList.length > 0 && (
            <div className="border border-white/10 rounded-lg overflow-hidden">
              <div className="bg-white/5 px-4 py-2 border-b border-white/10 flex items-center justify-between">
                <span className="text-white/70 font-medium">정상 ({okList.length}건)</span>
                {message && (
                  <span className="text-white/60 text-sm">{message}</span>
                )}
              </div>
              <div className="max-h-80 overflow-auto">
                <table className="w-full text-sm border-collapse">
                  <thead className="bg-white/5 sticky top-0">
                    <tr className="text-white/60">
                      <th className="px-2 py-2 text-left w-20 border-r border-white/10">일자</th>
                      <th className="px-3 py-2 text-left w-24 border-r border-white/10">구분</th>
                      <th className="px-2 py-2 text-center w-16 border-r border-white/10">발생(일)</th>
                      <th className="px-2 py-2 text-center w-16 border-r border-white/10">발생(시간)</th>
                      <th className="px-2 py-2 text-center w-16 border-r border-white/10">사용(일)</th>
                      <th className="px-2 py-2 text-center w-16 border-r border-white/10">사용(시간)</th>
                      <th className="px-3 py-2 text-left">비고</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/5">
                    {okList.map((item) => (
                      <tr key={item.Date} className="text-white/80 hover:bg-white/5">
                        <td className="px-2 py-2 w-20 border-r border-white/10">{formatDateShort(item.Date)}</td>
                        <td className="px-3 py-2 border-r border-white/10">{item.Gubun}</td>
                        <td className="px-2 py-2 text-center border-r border-white/10">{item.OccurDay}</td>
                        <td className="px-2 py-2 text-center border-r border-white/10">{item.OccurTime}</td>
                        <td className="px-2 py-2 text-center border-r border-white/10">{item.UseDay}</td>
                        <td className="px-2 py-2 text-center border-r border-white/10">{item.UseTime}</td>
                        <td className="px-3 py-2">{item.CateError}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* 오류 목록 */}
          {ngList.length > 0 && (
            <div className="border border-danger-500/50 rounded-lg overflow-hidden">
              <div className="bg-danger-500/10 px-4 py-2 border-b border-danger-500/30 flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <span className="text-danger-400 font-medium">
                    불량 - 불일치 데이터가 있는 날짜입니다 ({ngList.length}건)
                  </span>
                  {message && okList.length === 0 && (
                    <span className="text-white/60 text-sm">{message}</span>
                  )}
                </div>
                <button
                  onClick={toggleAllErrors}
                  className="text-xs text-white/60 hover:text-white"
                >
                  {selectedErrors.size === ngList.filter(i => !i.IsMagam).length ? '전체 해제' : '전체 선택'}
                </button>
              </div>
              <div className="max-h-80 overflow-auto">
                <table className="w-full text-sm border-collapse">
                  <thead className="bg-white/5 sticky top-0">
                    <tr className="text-white/60">
                      <th className="px-2 py-2 w-10 border-r border-white/10">
                        <Check className="w-4 h-4 mx-auto" />
                      </th>
                      <th className="px-2 py-2 text-left w-20 border-r border-white/10">일자</th>
                      <th className="px-3 py-2 text-left w-24 border-r border-white/10">구분</th>
                      <th className="px-2 py-2 text-center w-16 border-r border-white/10">발생(일)</th>
                      <th className="px-2 py-2 text-center w-16 border-r border-white/10">발생(시간)</th>
                      <th className="px-2 py-2 text-center w-16 border-r border-white/10">사용(일)</th>
                      <th className="px-2 py-2 text-center w-16 border-r border-white/10">사용(시간)</th>
                      <th className="px-3 py-2 text-left">비고</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/5">
                    {ngList.map((item) => (
                      <tr
                        key={item.Date}
                        className={`hover:bg-white/5 cursor-pointer ${
                          item.IsMagam ? 'text-blue-400' : 'text-danger-400'
                        }`}
                        onClick={() => toggleError(item.Date, item.IsMagam)}
                      >
                        <td className="px-2 py-2 text-center border-r border-white/10">
                          <input
                            type="checkbox"
                            checked={selectedErrors.has(item.Date)}
                            onChange={() => toggleError(item.Date, item.IsMagam)}
                            disabled={item.IsMagam}
                            className="w-4 h-4 rounded accent-primary-500"
                          />
                        </td>
                        <td className="px-2 py-2 w-20 border-r border-white/10">{formatDateShort(item.Date)}</td>
                        <td className="px-3 py-2 border-r border-white/10">{item.Gubun}</td>
                        <td className="px-2 py-2 text-center border-r border-white/10">{item.OccurDay}</td>
                        <td className="px-2 py-2 text-center border-r border-white/10">{item.OccurTime}</td>
                        <td className="px-2 py-2 text-center border-r border-white/10">{item.UseDay}</td>
                        <td className="px-2 py-2 text-center border-r border-white/10">{item.UseTime}</td>
                        <td className="px-3 py-2">
                          {item.CateError}
                          {item.IsMagam && <span className="ml-2 text-xs">(마감됨)</span>}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* 빈 상태 */}
          {okList.length === 0 && ngList.length === 0 && !isChecking && (
            <div className="text-center py-12 text-white/50">
              검사 버튼을 클릭하여 근태 자료를 검사하세요.
            </div>
          )}
        </div>

        {/* 하단 버튼 */}
        <div className="px-6 py-4 border-t border-white/10">
          <button
            onClick={handleFix}
            disabled={isChecking || isFixing || selectedErrors.size === 0}
            className="w-full py-3 bg-warning-500 hover:bg-warning-600 disabled:bg-gray-500
                       text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
          >
            {isFixing ? (
              <>
                <RefreshCw className="w-5 h-5 animate-spin" />
                수정 중...
              </>
            ) : (
              <>
                <RefreshCw className="w-5 h-5" />
                오류 수정 ({selectedErrors.size}건)
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
