'use client';

import { useState, useEffect } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import type { VacationTypeConfig, VacationType } from './types';

interface VacationTypeSettingsDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  vacationTypes: VacationTypeConfig[];
  onSave: (types: VacationTypeConfig[]) => void;
}

export function VacationTypeSettingsDialog({
  open,
  onOpenChange,
  vacationTypes,
  onSave,
}: VacationTypeSettingsDialogProps) {
  const [localTypes, setLocalTypes] = useState<VacationTypeConfig[]>([]);

  // 다이얼로그가 열릴 때 로컬 상태 초기화
  useEffect(() => {
    if (open) {
      setLocalTypes([...vacationTypes]);
    }
  }, [open, vacationTypes]);

  // 사용여부 토글
  const handleToggleActive = (id: string) => {
    setLocalTypes(prev =>
      prev.map(type =>
        type.id === id ? { ...type, isActive: !type.isActive } : type
      )
    );
  };

  // 이름 변경
  const handleNameChange = (id: string, name: string) => {
    setLocalTypes(prev =>
      prev.map(type =>
        type.id === id ? { ...type, name } : type
      )
    );
  };

  // 설명 변경
  const handleDescriptionChange = (id: string, description: string) => {
    setLocalTypes(prev =>
      prev.map(type =>
        type.id === id ? { ...type, description } : type
      )
    );
  };

  // 휴가종류 추가
  const handleAddType = () => {
    const newId = String(Date.now());
    const newType: VacationTypeConfig = {
      id: newId,
      name: '새 휴가종류',
      type: 'other' as VacationType,
      isActive: true,
      description: '',
    };
    setLocalTypes(prev => [...prev, newType]);
  };

  // 휴가종류 삭제
  const handleDeleteType = (id: string) => {
    // 기본 4개 타입은 삭제 불가
    const defaultTypeIds = ['1', '2', '3', '4'];
    if (defaultTypeIds.includes(id)) {
      return;
    }
    setLocalTypes(prev => prev.filter(type => type.id !== id));
  };

  // 저장 핸들러
  const handleSave = () => {
    onSave(localTypes);
  };

  // 취소 핸들러
  const handleCancel = () => {
    onOpenChange(false);
  };

  // 기본 타입인지 확인 (삭제 불가)
  const isDefaultType = (id: string) => {
    return ['1', '2', '3', '4'].includes(id);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[700px]">
        <DialogHeader>
          <DialogTitle>휴가 종류 설정</DialogTitle>
        </DialogHeader>

        <div className="py-4">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[150px]">휴가종류명</TableHead>
                <TableHead className="w-[100px] text-center">사용여부</TableHead>
                <TableHead>설명</TableHead>
                <TableHead className="w-[60px] text-center">삭제</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {localTypes.map((type) => (
                <TableRow key={type.id}>
                  <TableCell>
                    <Input
                      value={type.name}
                      onChange={(e) => handleNameChange(type.id, e.target.value)}
                      className="h-8"
                    />
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="flex justify-center">
                      <Switch
                        checked={type.isActive}
                        onCheckedChange={() => handleToggleActive(type.id)}
                      />
                    </div>
                  </TableCell>
                  <TableCell>
                    <Input
                      value={type.description || ''}
                      onChange={(e) => handleDescriptionChange(type.id, e.target.value)}
                      placeholder="설명을 입력하세요"
                      className="h-8"
                    />
                  </TableCell>
                  <TableCell className="text-center">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDeleteType(type.id)}
                      disabled={isDefaultType(type.id)}
                      className={isDefaultType(type.id) ? 'opacity-30 cursor-not-allowed' : 'text-red-500 hover:text-red-700'}
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>

          {/* 휴가종류 추가 버튼 */}
          <div className="mt-4">
            <Button variant="outline" onClick={handleAddType} className="w-full">
              <Plus className="w-4 h-4 mr-2" />
              휴가종류 추가
            </Button>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleCancel}>
            취소
          </Button>
          <Button onClick={handleSave}>
            저장
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
