'use client';

import { useState, useEffect } from 'react';
import { format, differenceInDays } from 'date-fns';
import { CalendarIcon } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Calendar } from '@/components/ui/calendar';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';
import type { VacationRequestFormData, VacationType } from './types';
import { VACATION_TYPE_LABELS } from './types';

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

const mockEmployees = [
  { id: '1', name: '김철수', department: '개발팀' },
  { id: '2', name: '이영희', department: '디자인팀' },
  { id: '3', name: '박민수', department: '기획팀' },
  { id: '4', name: '정수진', department: '영업팀' },
  { id: '5', name: '최동현', department: '인사팀' },
];

export function VacationRequestDialog({
  open,
  onOpenChange,
  onSave,
}: VacationRequestDialogProps) {
  const [formData, setFormData] = useState<VacationRequestFormData>({
    employeeId: '',
    vacationType: 'annual',
    startDate: '',
    endDate: '',
    vacationDays: 1,
  });
  const [startDate, setStartDate] = useState<Date | undefined>();
  const [endDate, setEndDate] = useState<Date | undefined>();

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

  useEffect(() => {
    if (startDate && endDate) {
      const days = differenceInDays(endDate, startDate) + 1;
      setFormData(prev => ({
        ...prev,
        startDate: format(startDate, 'yyyy-MM-dd'),
        endDate: format(endDate, 'yyyy-MM-dd'),
        vacationDays: days > 0 ? days : 1,
      }));
    }
  }, [startDate, endDate]);

  const handleSave = () => {
    if (!formData.employeeId) {
      alert('사원을 선택해주세요.');
      return;
    }
    if (!startDate || !endDate) {
      alert('휴가 기간을 선택해주세요.');
      return;
    }
    if (endDate < startDate) {
      alert('종료일은 시작일 이후여야 합니다.');
      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>
                {mockEmployees.map((emp) => (
                  <SelectItem key={emp.id} value={emp.id}>
                    {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>시작일</Label>
            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  className={cn(
                    'w-full justify-start text-left font-normal',
                    !startDate && 'text-muted-foreground'
                  )}
                >
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {startDate ? format(startDate, 'yyyy-MM-dd') : '시작일 선택'}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                  mode="single"
                  selected={startDate}
                  onSelect={setStartDate}
                  initialFocus
                />
              </PopoverContent>
            </Popover>
          </div>

          {/* 종료일 */}
          <div className="grid gap-2">
            <Label>종료일</Label>
            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  className={cn(
                    'w-full justify-start text-left font-normal',
                    !endDate && 'text-muted-foreground'
                  )}
                >
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {endDate ? format(endDate, 'yyyy-MM-dd') : '종료일 선택'}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                  mode="single"
                  selected={endDate}
                  onSelect={setEndDate}
                  disabled={(date) => startDate ? date < startDate : false}
                  initialFocus
                />
              </PopoverContent>
            </Popover>
          </div>

          {/* 휴가 일수 (자동 계산) */}
          {startDate && 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>
  );
}
