'use client';

import { useEffect, useState } from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
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 { ResignationData } from './types';

interface ResignationFormProps {
  data: ResignationData;
  onChange: (data: ResignationData) => void;
}

const REASON_OPTIONS = [
  { value: 'personal', label: '개인 사유' },
  { value: 'health', label: '건강 문제' },
  { value: 'family', label: '가정 사정' },
  { value: 'career', label: '이직/전직' },
  { value: 'study', label: '학업' },
  { value: 'other', label: '기타' },
];

export function ResignationForm({ data, onChange }: ResignationFormProps) {
  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,
        department: e.department,
        position: e.position,
        residentNumber: e.residentNumber,
        joinDate: e.joinDate,
        employeeAddress: e.address,
        submitDate: data.submitDate || format(new Date(), 'yyyy-MM-dd'),
      });
    }
  };

  return (
    <div className="space-y-6">
      {/* 대상 사원 선택 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">대상 사원</h3>
        <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>

      {/* 인적 사항 */}
      <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.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>
            <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.joinDate} disabled className="bg-gray-50" />
          </div>
          <div className="space-y-2">
            <Label>퇴사예정일 <span className="text-red-500">*</span></Label>
            <DatePicker
              value={data.resignDate}
              onChange={(date) => onChange({ ...data, resignDate: date })}
            />
          </div>
          <div className="md:col-span-2 space-y-2">
            <Label>주소</Label>
            <Input value={data.employeeAddress} disabled className="bg-gray-50" />
          </div>
        </div>
      </div>

      {/* 사직 사유 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">사직 사유</h3>
        <div className="space-y-4">
          <div className="space-y-2">
            <Label>사유 선택 <span className="text-red-500">*</span></Label>
            <Select
              value={data.reasonType || ''}
              onValueChange={(value) => onChange({ ...data, reasonType: value })}
            >
              <SelectTrigger>
                <SelectValue placeholder="사유를 선택해주세요" />
              </SelectTrigger>
              <SelectContent>
                {REASON_OPTIONS.map((opt) => (
                  <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>상세 사유</Label>
            <Textarea
              placeholder="상세 사유를 입력해주세요"
              value={data.reasonDetail}
              onChange={(e) => onChange({ ...data, reasonDetail: e.target.value })}
              className="min-h-[100px]"
            />
          </div>
        </div>
      </div>

      {/* 제출일 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">제출 정보</h3>
        <div className="space-y-2">
          <Label>제출일</Label>
          <DatePicker
            value={data.submitDate}
            onChange={(date) => onChange({ ...data, submitDate: date })}
          />
        </div>
      </div>
    </div>
  );
}
