'use client';

import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { NumberInput } from '@/components/ui/number-input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import type {
  VacationFormData,
  VacationTypeConfig,
  EmployeeOption,
  VacationType,
} from './types';

interface VacationRegisterDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  employees: EmployeeOption[];
  vacationTypes: VacationTypeConfig[];
  onSave: (data: VacationFormData) => void;
}

export function VacationRegisterDialog({
  open,
  onOpenChange,
  employees,
  vacationTypes,
  onSave,
}: VacationRegisterDialogProps) {
  const [formData, setFormData] = useState<VacationFormData>({
    employeeId: '',
    vacationType: 'annual',
    days: 0,
    memo: '',
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  // 다이얼로그가 열릴 때 폼 초기화
  useEffect(() => {
    if (open) {
      setFormData({
        employeeId: '',
        vacationType: 'annual',
        days: 0,
        memo: '',
      });
      setErrors({});
    }
  }, [open]);

  // 폼 유효성 검사
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.employeeId) {
      newErrors.employeeId = '사원을 선택해주세요';
    }

    if (!formData.vacationType) {
      newErrors.vacationType = '휴가 종류를 선택해주세요';
    }

    if (formData.days <= 0) {
      newErrors.days = '지급 일수를 입력해주세요';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

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

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>휴가 등록</DialogTitle>
        </DialogHeader>

        <div className="grid gap-4 py-4">
          {/* 사원 선택 */}
          <div className="grid gap-2">
            <Label htmlFor="employee">
              사원 선택 <span className="text-red-500">*</span>
            </Label>
            <Select
              value={formData.employeeId}
              onValueChange={(value) => setFormData((prev: VacationFormData) => ({ ...prev, employeeId: value }))}
            >
              <SelectTrigger id="employee" className={errors.employeeId ? 'border-red-500' : ''}>
                <SelectValue placeholder="사원을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                {employees.map((employee) => (
                  <SelectItem key={employee.id} value={employee.id}>
                    {employee.department} / {employee.name} / {employee.rank}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {errors.employeeId && (
              <p className="text-sm text-red-500">{errors.employeeId}</p>
            )}
          </div>

          {/* 휴가 종류 */}
          <div className="grid gap-2">
            <Label htmlFor="vacationType">
              휴가 종류 <span className="text-red-500">*</span>
            </Label>
            <Select
              value={formData.vacationType}
              onValueChange={(value) => setFormData((prev: VacationFormData) => ({ ...prev, vacationType: value as VacationType }))}
            >
              <SelectTrigger id="vacationType" className={errors.vacationType ? 'border-red-500' : ''}>
                <SelectValue placeholder="휴가 종류를 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                {vacationTypes.map((type) => (
                  <SelectItem key={type.id} value={type.type}>
                    {type.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {errors.vacationType && (
              <p className="text-sm text-red-500">{errors.vacationType}</p>
            )}
          </div>

          {/* 지급 일수 */}
          <div className="grid gap-2">
            <Label htmlFor="days">
              지급 일수 <span className="text-red-500">*</span>
            </Label>
            <NumberInput
              id="days"
              min={0}
              step={0.5}
              value={formData.days}
              onChange={(value) => setFormData((prev: VacationFormData) => ({ ...prev, days: value ?? 0 }))}
              error={!!errors.days}
              placeholder="일수를 입력하세요"
              allowDecimal
            />
            {errors.days && (
              <p className="text-sm text-red-500">{errors.days}</p>
            )}
          </div>

          {/* 비고 */}
          <div className="grid gap-2">
            <Label htmlFor="memo">비고</Label>
            <Textarea
              id="memo"
              value={formData.memo || ''}
              onChange={(e) => setFormData((prev: VacationFormData) => ({ ...prev, memo: e.target.value }))}
              placeholder="비고를 입력하세요 (선택)"
              rows={3}
            />
          </div>
        </div>

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