'use client';

import { useEffect, useState } from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/date-picker';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Plus, X } from 'lucide-react';
import { getEmployeeOptions, getEmployeeAutoFill, getLeaveBalanceAutoFill } from './form-actions';
import type { LeaveNotice2ndData } from './types';

interface LeaveNotice2ndFormProps {
  data: LeaveNotice2ndData;
  onChange: (data: LeaveNotice2ndData) => void;
}

const LEGAL_NOTICE_PARAGRAPHS = [
  '귀하는 연차 사용촉진 1차 통보 이후에도 연차 사용 시기를 제출하지 않아 근로기준법 제61조에 따라 회사가 다음과 같이 휴가 사용일을 지정합니다.',
  '위 지정된 날짜에 연차휴가를 사용하여 주시기 바랍니다.',
  '본 통지서는 근로기준법 제61조에 따른 연차 사용촉진 절차에 의한 통보입니다.',
];

const LEGAL_NOTICE_TEXT = LEGAL_NOTICE_PARAGRAPHS.join('\n\n');

export function LeaveNotice2ndForm({ data, onChange }: LeaveNotice2ndFormProps) {
  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();
  }, []);

  // 법적 통지 문구 자동 설정
  useEffect(() => {
    if (!data.legalNotice) {
      onChange({ ...data, legalNotice: LEGAL_NOTICE_TEXT });
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleEmployeeSelect = async (employeeId: string) => {
    onChange({ ...data, employeeId });

    const [empResult, leaveResult] = await Promise.all([
      getEmployeeAutoFill(employeeId),
      getLeaveBalanceAutoFill(parseInt(employeeId)),
    ]);

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

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

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

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

  const handleAddDate = () => {
    onChange({ ...data, designatedDates: [...data.designatedDates, ''] });
  };

  const handleDateChange = (index: number, value: string) => {
    const newDates = [...data.designatedDates];
    newDates[index] = value;
    onChange({ ...data, designatedDates: newDates });
  };

  const handleRemoveDate = (index: number) => {
    const newDates = data.designatedDates.filter((_, i) => i !== index);
    onChange({ ...data, designatedDates: newDates.length > 0 ? newDates : [''] });
  };

  return (
    <div className="space-y-6">
      {/* 1. 수신자 정보 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">1. 수신자 정보</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">2. 잔여 연차</h3>
        <div className="space-y-2">
          <Label>잔여연차 <span className="text-red-500">*</span></Label>
          <Input
            type="number"
            value={data.remainingDays || ''}
            onChange={(e) => onChange({ ...data, remainingDays: Number(e.target.value) })}
            placeholder="잔여 일수"
          />
        </div>
      </div>

      {/* 3. 회사 지정 휴가일 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">
          3. 회사 지정 휴가일 <span className="text-red-500">*</span>
        </h3>
        <div className="space-y-3">
          {data.designatedDates.map((date, index) => (
            <div key={index} className="flex items-center gap-3">
              <span className="text-sm font-medium text-gray-600 w-6">{index + 1}.</span>
              <DatePicker
                value={date}
                onChange={(value) => handleDateChange(index, value)}
                placeholder="날짜를 선택하세요"
              />
              {data.designatedDates.length > 1 && (
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={() => handleRemoveDate(index)}
                  className="text-red-500 hover:text-red-700"
                >
                  <X className="h-4 w-4" />
                </Button>
              )}
            </div>
          ))}
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={handleAddDate}
          >
            <Plus className="h-4 w-4 mr-1" />
            휴가일 추가
          </Button>
          <p className="text-sm text-muted-foreground">* 잔여연차 일수만큼 지정해주세요.</p>
        </div>
      </div>

      {/* 4. 법적 통지 문구 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">4. 법적 통지 문구</h3>
        <div className="bg-red-50 border border-red-200 rounded-lg p-4 space-y-3">
          {LEGAL_NOTICE_PARAGRAPHS.map((paragraph, index) => (
            <p key={index} className="text-sm text-red-800">{paragraph}</p>
          ))}
        </div>
      </div>
    </div>
  );
}
