'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 { getEmployeeOptions, getEmployeeAutoFill, getLeaveBalanceAutoFill } from './form-actions';
import type { LeaveNotice1stData } from './types';

interface LeaveNotice1stFormProps {
  data: LeaveNotice1stData;
  onChange: (data: LeaveNotice1stData) => void;
}

const DEFAULT_LEGAL_NOTICE = `근로기준법 제61조에 의거하여 미사용 연차유급휴가에 대하여 사용을 촉진합니다.\n\n아래 잔여 연차를 기한 내에 사용하여 주시기 바랍니다. 기한 내 미사용 시 사용시기를 지정하여 통보할 예정이며, 회사가 지정한 시기에 사용하지 않을 경우 해당 연차는 소멸됩니다.`;

export function LeaveNotice1stForm({ data, onChange }: LeaveNotice1stFormProps) {
  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 [empResult, leaveResult] = await Promise.all([
      getEmployeeAutoFill(employeeId),
      getLeaveBalanceAutoFill(parseInt(employeeId)),
    ]);

    const updates: Partial<LeaveNotice1stData> = { employeeId };

    if (empResult.success && empResult.data) {
      updates.department = empResult.data.department;
      updates.position = empResult.data.position;
    }

    if (leaveResult.success && leaveResult.data) {
      updates.totalDays = leaveResult.data.totalDays;
      updates.usedDays = leaveResult.data.usedDays;
      updates.remainingDays = leaveResult.data.remainingDays;
    }

    if (!data.legalNotice) {
      updates.legalNotice = DEFAULT_LEGAL_NOTICE;
    }

    onChange({ ...data, ...updates });
  };

  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-3 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.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>
      </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-3 gap-4">
          <div className="space-y-2">
            <Label>발생 <span className="text-red-500">*</span></Label>
            <Input
              type="number"
              value={data.totalDays || ''}
              onChange={(e) => onChange({ ...data, totalDays: Number(e.target.value) })}
              placeholder="발생 일수"
            />
          </div>
          <div className="space-y-2">
            <Label>사용</Label>
            <Input
              type="number"
              value={data.usedDays || ''}
              onChange={(e) => onChange({ ...data, usedDays: Number(e.target.value) })}
              placeholder="사용 일수"
            />
          </div>
          <div className="space-y-2">
            <Label>잔여</Label>
            <Input
              type="number"
              value={data.remainingDays || ''}
              onChange={(e) => onChange({ ...data, remainingDays: Number(e.target.value) })}
              placeholder="잔여 일수"
            />
          </div>
        </div>
      </div>

      {/* 3. 제출 기한 */}
      <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>
          <DatePicker
            value={data.deadline}
            onChange={(date) => onChange({ ...data, deadline: date })}
          />
        </div>
      </div>

      {/* 4. 법적 통지 문구 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">법적 통지 문구</h3>
        <Textarea
          value={data.legalNotice}
          onChange={(e) => onChange({ ...data, legalNotice: e.target.value })}
          className="min-h-[150px]"
          placeholder="법적 통지 문구"
        />
      </div>
    </div>
  );
}
