'use client';

import { useEffect, useState } from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { DatePicker } from '@/components/ui/date-picker';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { format } from 'date-fns';
import { getEmployeeOptions, getEmployeeAutoFill } from './form-actions';
import type { AppointmentCertData } from './types';

interface AppointmentCertFormProps {
  data: AppointmentCertData;
  onChange: (data: AppointmentCertData) => void;
}

export function AppointmentCertForm({ data, onChange }: AppointmentCertFormProps) {
  const [employees, setEmployees] = useState<{ id: string; name: string; department: string }[]>([]);
  const [isLoadingEmployees, setIsLoadingEmployees] = useState(true);

  useEffect(() => {
    async function loadEmployees() {
      setIsLoadingEmployees(true);
      const result = await getEmployeeOptions();
      if (result.success) setEmployees(result.data);
      setIsLoadingEmployees(false);
    }
    loadEmployees();
  }, []);

  const handleEmployeeSelect = async (employeeId: string) => {
    onChange({ ...data, employeeId });
    const result = await getEmployeeAutoFill(employeeId);
    if (result.success && result.data) {
      const e = result.data;
      onChange({
        ...data,
        employeeId,
        employeeName: e.name,
        residentNumber: e.residentNumber,
        department: e.department,
        phone: e.phone,
        issueDate: data.issueDate || format(new Date(), 'yyyy-MM-dd'),
      });
    }
  };

  return (
    <div className="space-y-6">
      {/* 1. 인적 사항 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">인적 사항</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label>대상사원 <span className="text-red-500">*</span></Label>
            <Select
              value={data.employeeId || ''}
              onValueChange={handleEmployeeSelect}
              disabled={isLoadingEmployees}
            >
              <SelectTrigger>
                <SelectValue placeholder={isLoadingEmployees ? '불러오는 중...' : '사원을 선택해주세요'} />
              </SelectTrigger>
              <SelectContent>
                {employees.map((emp) => (
                  <SelectItem key={emp.id} value={emp.id}>
                    {emp.name} ({emp.department})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>성명</Label>
            <Input value={data.employeeName} disabled className="bg-gray-50" />
          </div>
          <div className="space-y-2">
            <Label>주민등록번호</Label>
            <Input value={data.residentNumber} disabled className="bg-gray-50" />
          </div>
          <div className="space-y-2">
            <Label>소속</Label>
            <Input value={data.department} disabled className="bg-gray-50" />
          </div>
          <div className="space-y-2">
            <Label>연락처</Label>
            <Input value={data.phone} disabled className="bg-gray-50" />
          </div>
        </div>
      </div>

      {/* 2. 위촉 정보 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">위촉 정보</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label>기간 시작</Label>
            <DatePicker
              value={data.appointmentPeriodStart}
              onChange={(date) => onChange({ ...data, appointmentPeriodStart: date })}
            />
          </div>
          <div className="space-y-2">
            <Label>기간 종료</Label>
            <DatePicker
              value={data.appointmentPeriodEnd}
              onChange={(date) => onChange({ ...data, appointmentPeriodEnd: date })}
            />
          </div>
          <div className="md:col-span-2 space-y-2">
            <Label>계약 자격</Label>
            <Input
              placeholder="계약 자격을 입력해주세요"
              value={data.contractQualification}
              onChange={(e) => onChange({ ...data, contractQualification: e.target.value })}
            />
          </div>
        </div>
      </div>

      {/* 3. 발급 정보 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">발급 정보</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label>용도 <span className="text-red-500">*</span></Label>
            <Input
              placeholder="사용 용도를 입력해주세요"
              value={data.purpose}
              onChange={(e) => onChange({ ...data, purpose: e.target.value })}
            />
          </div>
          <div className="space-y-2">
            <Label>발급일</Label>
            <DatePicker
              value={data.issueDate}
              onChange={(date) => onChange({ ...data, issueDate: date })}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
