'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, getCompanyAutoFill } from './form-actions';
import type { EmploymentCertData } from './types';

interface EmploymentCertFormProps {
  data: EmploymentCertData;
  onChange: (data: EmploymentCertData) => void;
}

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

  useEffect(() => {
    async function load() {
      setIsLoadingEmployees(true);
      const [empResult, companyResult] = await Promise.all([
        getEmployeeOptions(),
        !data.companyName ? getCompanyAutoFill() : Promise.resolve(null),
      ]);
      if (empResult.success) setEmployees(empResult.data);

      if (companyResult?.success && companyResult.data) {
        const c = companyResult.data;
        onChange({
          ...data,
          companyName: data.companyName || c.companyName,
          businessNumber: data.businessNumber || c.businessNumber,
          issueDate: data.issueDate || format(new Date(), 'yyyy-MM-dd'),
        });
      }
      setIsLoadingEmployees(false);
    }
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  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,
        employeeAddress: e.address,
        department: e.department,
        position: e.position,
        employmentPeriodStart: e.joinDate,
      });
    }
  };

  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="md:col-span-2 space-y-2">
            <Label>주소</Label>
            <Input value={data.employeeAddress} 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>
            <Input value={data.companyName} disabled className="bg-gray-50" />
          </div>
          <div className="space-y-2">
            <Label>사업자번호</Label>
            <Input value={data.businessNumber} 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.position} disabled className="bg-gray-50" />
          </div>
          <div className="space-y-2">
            <Label>재직기간 시작</Label>
            <DatePicker
              value={data.employmentPeriodStart}
              onChange={(date) => onChange({ ...data, employmentPeriodStart: date })}
            />
          </div>
          <div className="space-y-2">
            <Label>재직기간 종료</Label>
            <DatePicker
              value={data.employmentPeriodEnd}
              onChange={(date) => onChange({ ...data, employmentPeriodEnd: date })}
            />
          </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>
  );
}
