'use client';

import { useState, useEffect } from 'react';
import { format } 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 { Textarea } from '@/components/ui/textarea';
import { QuantityInput } from '@/components/ui/quantity-input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import type { VacationGrantFormData, VacationType } from './types';
import { VACATION_TYPE_LABELS } from './types';
import { getActiveEmployees, type EmployeeOption } from './actions';
import { toast } from 'sonner';

interface VacationGrantDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSave: (data: VacationGrantFormData) => void;
}

export function VacationGrantDialog({
  open,
  onOpenChange,
  onSave,
}: VacationGrantDialogProps) {
  const today = format(new Date(), 'yyyy-MM-dd');
  const [formData, setFormData] = useState<VacationGrantFormData>({
    employeeId: '',
    vacationType: 'annual',
    grantDate: today,
    grantDays: 1,
    reason: '',
  });
  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: '',
        vacationType: 'annual',
        grantDate: format(new Date(), 'yyyy-MM-dd'),
        grantDays: 1,
        reason: '',
      });
    }
  }, [open]);

  const handleSave = () => {
    if (!formData.employeeId) {
      toast.warning('사원을 선택해주세요.');
      return;
    }
    if (!formData.grantDate) {
      toast.warning('부여일을 선택해주세요.');
      return;
    }
    if (formData.grantDays < 1) {
      toast.warning('부여 일수는 1 이상이어야 합니다.');
      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="vacationType">휴가 유형</Label>
            <Select
              value={formData.vacationType}
              onValueChange={(value) => setFormData(prev => ({ ...prev, vacationType: value as VacationType }))}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {Object.entries(VACATION_TYPE_LABELS).map(([key, label]) => (
                  <SelectItem key={key} value={key}>
                    {label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

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

          {/* 부여 일수 */}
          <div className="grid gap-2">
            <Label htmlFor="grantDays">부여 일수</Label>
            <QuantityInput
              id="grantDays"
              min={1}
              value={formData.grantDays}
              onChange={(value) => setFormData(prev => ({ ...prev, grantDays: value ?? 1 }))}
            />
          </div>

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

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