'use client';

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

const initialFormData: ReasonFormData = {
  employeeId: '',
  baseDate: format(new Date(), 'yyyy-MM-dd'),
  reasonType: '',
};

export function ReasonInfoDialog({
  open,
  onOpenChange,
  employees,
  onSubmit,
}: ReasonInfoDialogProps) {
  const [formData, setFormData] = useState<ReasonFormData>(initialFormData);
  const [selectedDate, setSelectedDate] = useState<Date | undefined>(new Date());

  // 데이터 초기화
  useEffect(() => {
    if (open) {
      setFormData(initialFormData);
      setSelectedDate(new Date());
    }
  }, [open]);

  // 입력 변경 핸들러
  const handleChange = (field: keyof ReasonFormData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 날짜 변경 핸들러
  const handleDateChange = (date: Date | undefined) => {
    setSelectedDate(date);
    if (date) {
      setFormData(prev => ({ ...prev, baseDate: format(date, 'yyyy-MM-dd') }));
    }
  };

  // 등록 (문서 작성 화면으로 이동)
  const handleSubmit = () => {
    onSubmit(formData);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>사유 정보</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-4">
          {/* 대상 선택 */}
          <div className="flex items-center justify-between">
            <Label className="text-sm font-medium min-w-[80px]">대상</Label>
            <Select
              value={formData.employeeId}
              onValueChange={(value) => handleChange('employeeId', value)}
            >
              <SelectTrigger className="w-[200px]">
                <SelectValue placeholder="선택 ▼" />
              </SelectTrigger>
              <SelectContent>
                {employees.map((employee) => (
                  <SelectItem key={employee.id} value={employee.id}>
                    {employee.department} / {employee.rank} / {employee.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* 기준일 */}
          <div className="flex items-center justify-between">
            <Label className="text-sm font-medium min-w-[80px]">기준일</Label>
            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  className={cn(
                    'w-[200px] justify-start text-left font-normal',
                    !selectedDate && 'text-muted-foreground'
                  )}
                >
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {selectedDate ? format(selectedDate, 'yyyy-MM-dd') : '날짜 선택'}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0" align="end">
                <Calendar
                  mode="single"
                  selected={selectedDate}
                  onSelect={handleDateChange}
                  locale={ko}
                  initialFocus
                />
              </PopoverContent>
            </Popover>
          </div>

          {/* 유형 선택 */}
          <div className="flex items-center justify-between">
            <Label className="text-sm font-medium min-w-[80px]">유형</Label>
            <Select
              value={formData.reasonType}
              onValueChange={(value) => handleChange('reasonType', value)}
            >
              <SelectTrigger className="w-[200px]">
                <SelectValue placeholder="선택 ▼" />
              </SelectTrigger>
              <SelectContent>
                {Object.entries(REASON_TYPE_LABELS).map(([value, label]) => (
                  <SelectItem key={value} value={value}>
                    {label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        <DialogFooter className="gap-2">
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            className="bg-gray-900 text-white hover:bg-gray-800"
          >
            취소
          </Button>
          <Button
            onClick={handleSubmit}
            className="bg-gray-900 text-white hover:bg-gray-800"
          >
            등록
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
