'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 { DatePicker } from '@/components/ui/date-picker';
import { format } from 'date-fns';
import type {
  AttendanceInfoDialogProps,
  AttendanceFormData,
} from './types';
import {
  HOUR_OPTIONS,
  MINUTE_OPTIONS,
  OVERTIME_HOUR_OPTIONS,
} from './types';

const initialFormData: AttendanceFormData = {
  employeeId: '',
  baseDate: format(new Date(), 'yyyy-MM-dd'),
  checkInHour: '9',
  checkInMinute: '0',
  checkOutHour: '18',
  checkOutMinute: '0',
  nightOvertimeHours: '0',
  nightOvertimeMinutes: '0',
  weekendOvertimeHours: '0',
  weekendOvertimeMinutes: '0',
};

export function AttendanceInfoDialog({
  open,
  onOpenChange,
  mode,
  attendance,
  employees,
  onSave,
}: AttendanceInfoDialogProps) {
  const [formData, setFormData] = useState<AttendanceFormData>(initialFormData);

  // 모드별 타이틀
  const title = mode === 'create' ? '근태 정보' : '근태 정보';

  // 데이터 초기화
  useEffect(() => {
    if (open && attendance && mode === 'edit') {
      const [checkInHour, checkInMinute] = (attendance.checkIn || '09:00').split(':');
      const [checkOutHour, checkOutMinute] = (attendance.checkOut || '18:00').split(':');

      setFormData({
        employeeId: attendance.employeeId,
        baseDate: attendance.baseDate,
        checkInHour: checkInHour || '9',
        checkInMinute: checkInMinute === '30' ? '30' : '0',
        checkOutHour: checkOutHour || '18',
        checkOutMinute: checkOutMinute === '30' ? '30' : '0',
        nightOvertimeHours: '0',
        nightOvertimeMinutes: '0',
        weekendOvertimeHours: '0',
        weekendOvertimeMinutes: '0',
      });
    } else if (open && mode === 'create') {
      setFormData(initialFormData);
    }
  }, [open, attendance, mode]);

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

  // 저장
  const handleSubmit = () => {
    onSave(formData);
    onOpenChange(false);
  };

  // 선택된 사원 정보
  const _selectedEmployee = employees.find(e => e.id === formData.employeeId);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md max-h-[78vh] !grid !grid-rows-[auto_1fr_auto] !overflow-hidden p-4 sm:p-6">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
        </DialogHeader>

        <div className="space-y-3 py-2 overflow-y-auto min-h-0">
          {/* 대상 선택 */}
          <div className="flex items-center gap-3">
            <Label className="text-sm font-medium shrink-0 w-[90px]">대상</Label>
            <Select
              value={formData.employeeId}
              onValueChange={(value) => handleChange('employeeId', value)}
            >
              <SelectTrigger className="flex-1 min-w-0">
                <SelectValue placeholder="선택" />
              </SelectTrigger>
              <SelectContent>
                {employees.map((employee) => (
                  <SelectItem key={employee.id} value={employee.id}>
                    {[employee.department, employee.position, employee.rank, employee.name].filter(Boolean).join(' / ')}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* 기준일 */}
          <div className="flex items-center gap-3">
            <Label className="text-sm font-medium shrink-0 w-[90px]">기준일</Label>
            <DatePicker
              value={formData.baseDate}
              onChange={(date) => handleChange('baseDate', date)}
              className="flex-1 min-w-0"
              align="end"
            />
          </div>

          {/* 출근 시간 */}
          <div className="flex items-center gap-3">
            <Label className="text-sm font-medium shrink-0 w-[90px]">출근 시간</Label>
            <div className="flex items-center gap-2 flex-1 min-w-0">
              <Select
                value={formData.checkInHour}
                onValueChange={(value) => handleChange('checkInHour', value)}
              >
                <SelectTrigger className="flex-1 min-w-0">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {HOUR_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select
                value={formData.checkInMinute}
                onValueChange={(value) => handleChange('checkInMinute', value)}
              >
                <SelectTrigger className="flex-1 min-w-0">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {MINUTE_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 퇴근 시간 */}
          <div className="flex items-center gap-3">
            <Label className="text-sm font-medium shrink-0 w-[90px]">퇴근 시간</Label>
            <div className="flex items-center gap-2 flex-1 min-w-0">
              <Select
                value={formData.checkOutHour}
                onValueChange={(value) => handleChange('checkOutHour', value)}
              >
                <SelectTrigger className="flex-1 min-w-0">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {HOUR_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select
                value={formData.checkOutMinute}
                onValueChange={(value) => handleChange('checkOutMinute', value)}
              >
                <SelectTrigger className="flex-1 min-w-0">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {MINUTE_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 야간 연장 시간 */}
          <div className="flex items-center gap-3">
            <Label className="text-sm font-medium shrink-0 w-[90px]">야간 연장</Label>
            <div className="flex items-center gap-2 flex-1 min-w-0">
              <Select
                value={formData.nightOvertimeHours}
                onValueChange={(value) => handleChange('nightOvertimeHours', value)}
              >
                <SelectTrigger className="flex-1 min-w-0">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {OVERTIME_HOUR_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select
                value={formData.nightOvertimeMinutes}
                onValueChange={(value) => handleChange('nightOvertimeMinutes', value)}
              >
                <SelectTrigger className="flex-1 min-w-0">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {MINUTE_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 주말 연장 시간 */}
          <div className="flex items-center gap-3">
            <Label className="text-sm font-medium shrink-0 w-[90px]">주말 연장</Label>
            <div className="flex items-center gap-2 flex-1 min-w-0">
              <Select
                value={formData.weekendOvertimeHours}
                onValueChange={(value) => handleChange('weekendOvertimeHours', value)}
              >
                <SelectTrigger className="flex-1 min-w-0">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {OVERTIME_HOUR_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select
                value={formData.weekendOvertimeMinutes}
                onValueChange={(value) => handleChange('weekendOvertimeMinutes', value)}
              >
                <SelectTrigger className="flex-1 min-w-0">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {MINUTE_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </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>
  );
}