'use client';

import { useState, useCallback } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { getPresetStyle } from '@/lib/utils/status-config';
import { FileSpreadsheet, AlertCircle, CheckCircle } from 'lucide-react';
import { FileDropzone } from '@/components/ui/file-dropzone';
import type { Employee, CSVEmployeeRow, CSVValidationResult } from './types';

interface CSVUploadDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onUpload: (employees: Employee[]) => void;
}

export function CSVUploadDialog({
  open,
  onOpenChange,
  onUpload,
}: CSVUploadDialogProps) {
  const [file, setFile] = useState<File | null>(null);
  const [validationResults, setValidationResults] = useState<CSVValidationResult[]>([]);
  const [isProcessing, setIsProcessing] = useState(false);

  // 파일 선택
  const handleFilesSelect = useCallback((files: File[]) => {
    const selectedFile = files[0];
    if (selectedFile && selectedFile.type === 'text/csv') {
      setFile(selectedFile);
      processCSV(selectedFile);
    }
  }, []);

  // CSV 파싱 및 유효성 검사
  const processCSV = async (csvFile: File) => {
    setIsProcessing(true);
    try {
      const text = await csvFile.text();
      const lines = text.split('\n').map(line => line.trim()).filter(line => line);

      if (lines.length < 2) {
        setValidationResults([]);
        return;
      }

      // 헤더 파싱
      const headers = lines[0].split(',').map(h => h.trim());

      // 데이터 파싱 및 유효성 검사
      const results: CSVValidationResult[] = lines.slice(1).map((line, index) => {
        const values = line.split(',').map(v => v.trim());
        const data: CSVEmployeeRow = {
          name: values[headers.indexOf('이름')] || values[headers.indexOf('name')] || '',
          phone: values[headers.indexOf('휴대폰')] || values[headers.indexOf('phone')] || undefined,
          email: values[headers.indexOf('이메일')] || values[headers.indexOf('email')] || undefined,
          departmentName: values[headers.indexOf('부서')] || values[headers.indexOf('department')] || undefined,
          positionName: values[headers.indexOf('직책')] || values[headers.indexOf('position')] || undefined,
          hireDate: values[headers.indexOf('입사일')] || values[headers.indexOf('hireDate')] || undefined,
          status: values[headers.indexOf('상태')] || values[headers.indexOf('status')] || undefined,
        };

        // 유효성 검사
        const errors: string[] = [];
        if (!data.name) {
          errors.push('이름은 필수입니다');
        }
        if (data.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
          errors.push('이메일 형식이 올바르지 않습니다');
        }
        if (data.phone && !/^\d{3}-\d{4}-\d{4}$/.test(data.phone)) {
          errors.push('휴대폰 형식이 올바르지 않습니다 (000-0000-0000)');
        }

        return {
          row: index + 2, // 1-indexed, 헤더 제외
          data,
          isValid: errors.length === 0,
          errors,
        };
      });

      setValidationResults(results);
    } catch {
      console.error('CSV 파싱 오류');
    } finally {
      setIsProcessing(false);
    }
  };

  // 업로드 실행
  const handleUpload = () => {
    const validRows = validationResults.filter(r => r.isValid);
    const employees: Employee[] = validRows.map((r, index) => ({
      id: String(Date.now() + index),
      name: r.data.name,
      phone: r.data.phone,
      email: r.data.email,
      status: (r.data.status === '재직' || r.data.status === 'active') ? 'active' :
              (r.data.status === '휴직' || r.data.status === 'leave') ? 'leave' :
              (r.data.status === '퇴직' || r.data.status === 'resigned') ? 'resigned' : 'active',
      hireDate: r.data.hireDate,
      departmentPositions: r.data.departmentName ? [{
        id: String(Date.now() + index),
        departmentId: '',
        departmentName: r.data.departmentName,
        positionId: '',
        positionName: r.data.positionName || '',
      }] : [],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    }));

    onUpload(employees);
    handleReset();
  };

  // 초기화
  const handleReset = () => {
    setFile(null);
    setValidationResults([]);
  };

  const validCount = validationResults.filter(r => r.isValid).length;
  const invalidCount = validationResults.filter(r => !r.isValid).length;

  return (
    <Dialog open={open} onOpenChange={(open) => { if (!open) handleReset(); onOpenChange(open); }}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>CSV 일괄등록</DialogTitle>
          <DialogDescription>
            CSV 파일을 업로드하여 사원을 일괄 등록합니다
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          {/* 파일 업로드 영역 */}
          {!file && (
            <FileDropzone
              onFilesSelect={handleFilesSelect}
              accept=".csv"
              maxSize={10}
              title="CSV 파일을 드래그하거나 클릭하여 업로드"
              description="필수 컬럼: 이름 | 선택 컬럼: 휴대폰, 이메일, 부서, 직책, 입사일, 상태"
            />
          )}

          {/* 파일 정보 및 미리보기 */}
          {file && (
            <>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <FileSpreadsheet className="w-5 h-5 text-muted-foreground" />
                  <span className="text-sm font-medium">{file.name}</span>
                </div>
                <div className="flex items-center gap-4">
                  <div className="flex items-center gap-2">
                    <CheckCircle className="w-4 h-4 text-green-500" />
                    <span className="text-sm">유효: {validCount}건</span>
                  </div>
                  {invalidCount > 0 && (
                    <div className="flex items-center gap-2">
                      <AlertCircle className="w-4 h-4 text-red-500" />
                      <span className="text-sm">오류: {invalidCount}건</span>
                    </div>
                  )}
                  <Button variant="ghost" size="sm" onClick={handleReset}>
                    다시 선택
                  </Button>
                </div>
              </div>

              {/* 미리보기 테이블 */}
              {validationResults.length > 0 && (
                <div className="rounded-md border max-h-[400px] overflow-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-[60px]">행</TableHead>
                        <TableHead className="w-[80px]">상태</TableHead>
                        <TableHead>이름</TableHead>
                        <TableHead>휴대폰</TableHead>
                        <TableHead>이메일</TableHead>
                        <TableHead>부서</TableHead>
                        <TableHead>직책</TableHead>
                        <TableHead>오류</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {validationResults.map((result) => (
                        <TableRow
                          key={result.row}
                          className={result.isValid ? '' : 'bg-red-50'}
                        >
                          <TableCell className="font-medium">{result.row}</TableCell>
                          <TableCell>
                            {result.isValid ? (
                              <Badge className={getPresetStyle('success')}>유효</Badge>
                            ) : (
                              <Badge className={getPresetStyle('destructive')}>오류</Badge>
                            )}
                          </TableCell>
                          <TableCell>{result.data.name || '-'}</TableCell>
                          <TableCell>{result.data.phone || '-'}</TableCell>
                          <TableCell>{result.data.email || '-'}</TableCell>
                          <TableCell>{result.data.departmentName || '-'}</TableCell>
                          <TableCell>{result.data.positionName || '-'}</TableCell>
                          <TableCell className="text-sm text-red-600">
                            {result.errors.join(', ')}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button
            onClick={handleUpload}
            disabled={!file || validCount === 0 || isProcessing}
          >
            {validCount}건 등록
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}