'use client';

import { useState, useEffect } from 'react';
import { differenceInDays, parseISO } from 'date-fns';
import { Loader2 } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/date-picker';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import type { VacationRequestFormData, LeaveType } from './types';
import { LEAVE_TYPE_LABELS } from './types';
import { getActiveEmployees, type EmployeeOption } from './actions';
import { toast } from 'sonner';

interface VacationRequestDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSave: (data: VacationRequestFormData) => void;
}

export function VacationRequestDialog({
  open,
  onOpenChange,
  onSave,
}: VacationRequestDialogProps) {
  const [formData, setFormData] = useState<VacationRequestFormData>({
    employeeId: '',
    leaveType: 'annual',
    startDate: '',
    endDate: '',
    vacationDays: 1,
  });
  const [employees, setEmployees] = useState<EmployeeOption[]>([]);
  const [isLoadingEmployees, setIsLoadingEmployees] = useState(false);

  // 직원 목록 로드
  useEffect(() => {
    if (open && employees.length === 0) {
      setIsLoadingEmployees(true);
      getActiveEmployees()
        .then((result) => {
          if (result.success && result.data) {
            setEmployees(result.data);
          }
        })
        .finally(() => setIsLoadingEmployees(false));
    }
  }, [open, employees.length]);

  useEffect(() => {
    if (open) {
      setFormData({
        employeeId: '',
        leaveType: 'annual',
        startDate: '',
        endDate: '',
        vacationDays: 1,
      });
    }
  }, [open]);

  // 날짜 변경 시 휴가 일수 자동 계산
  useEffect(() => {
    if (formData.startDate && formData.endDate) {
      const start = parseISO(formData.startDate);
      const end = parseISO(formData.endDate);
      const days = differenceInDays(end, start) + 1;
      if (days > 0 && days !== formData.vacationDays) {
        setFormData(prev => ({ ...prev, vacationDays: days }));
      }
    }
  }, [formData.startDate, formData.endDate, formData.vacationDays]);

  const handleSave = () => {
    if (!formData.employeeId) {
      toast.warning('사원을 선택해주세요.');
      return;
    }
    if (!formData.startDate || !formData.endDate) {
      toast.warning('휴가 기간을 선택해주세요.');
      return;
    }
    if (formData.endDate < formData.startDate) {
      toast.warning('종료일은 시작일 이후여야 합니다.');
      return;
    }
    onSave(formData);
  };

  const handleCancel = () => {
    onOpenChange(false);
  };

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

        <div className="grid gap-4 py-4">
          {/* 사원 선택 */}
          <div className="grid gap-2">
            <Label htmlFor="employee">사원 선택</Label>
            <Select
              value={formData.employeeId}
              onValueChange={(value) => setFormData(prev => ({ ...prev, employeeId: value }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="사원을 선택하세요" />
              </SelectTrigger>
              <SelectContent position="popper" className="max-h-[200px]">
                {isLoadingEmployees ? (
                  <div className="flex items-center justify-center py-2">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    <span className="ml-2 text-sm text-muted-foreground">로딩 중...</span>
                  </div>
                ) : employees.length === 0 ? (
                  <div className="py-2 text-center text-sm text-muted-foreground">
                    사원 데이터가 없습니다
                  </div>
                ) : (
                  employees.map((emp) => (
                    <SelectItem key={emp.id} value={String(emp.userId)}>
                      {emp.name} ({emp.department})
                    </SelectItem>
                  ))
                )}
              </SelectContent>
            </Select>
          </div>

          {/* 휴가 유형 */}
          <div className="grid gap-2">
            <Label htmlFor="leaveType">휴가 유형</Label>
            <Select
              value={formData.leaveType}
              onValueChange={(value) => setFormData(prev => ({ ...prev, leaveType: value as LeaveType }))}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {Object.entries(LEAVE_TYPE_LABELS).map(([key, label]) => (
                  <SelectItem key={key} value={key}>
                    {label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* 시작일 */}
          <div className="grid gap-2">
            <Label htmlFor="startDate">시작일</Label>
            <DatePicker
              value={formData.startDate}
              onChange={(date) => setFormData(prev => ({ ...prev, startDate: date }))}
            />
          </div>

          {/* 종료일 */}
          <div className="grid gap-2">
            <Label htmlFor="endDate">종료일</Label>
            <DatePicker
              value={formData.endDate}
              minDate={formData.startDate ? new Date(formData.startDate) : undefined}
              onChange={(date) => setFormData(prev => ({ ...prev, endDate: date }))}
            />
          </div>

          {/* 휴가 일수 (자동 계산) */}
          {formData.startDate && formData.endDate && (
            <div className="grid gap-2">
              <Label>휴가 일수</Label>
              <div className="p-3 bg-muted rounded-md text-center font-medium">
                {formData.vacationDays}일
              </div>
            </div>
          )}
        </div>

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