'use client';

import { useQuery, useMutation } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { getFedexCodes, insertFedex } from '@/lib/api/fedex';
import { useToast } from '@/components/common/Toast';

interface FormValues {
  ieGbn: string;
  sCode: string;
  sYear: string;
  sJechl: string;
  comNm: string;
  jSingoDt: string;
  sSingoDt: string;
  jGwiCd: string;
  fStCd: string;
  fJjCd: string;
  fJjContents: string;
  fJjNm: string;
  fJjRegDt: string;
  fJjRegGbn: string;
}

export default function Fedex0010WritePage() {
  const router = useRouter();
  const { success, error: toastError } = useToast();

  const { data: codes } = useQuery({
    queryKey: ['fedex', 'codes'],
    queryFn: getFedexCodes,
  });

  const { register, handleSubmit, formState: { errors } } = useForm<FormValues>({
    defaultValues: { fJjRegGbn: '1' },
  });

  const saveMut = useMutation({
    mutationFn: (data: FormValues) => insertFedex(data as Record<string, unknown>),
    onSuccess: (sq) => {
      success('등록되었습니다.');
      router.push(`/fedex/0010/${sq}`);
    },
    onError: () => toastError('등록 중 오류가 발생했습니다.'),
  });

  return (
    <div className="p-4 max-w-2xl">
      <div className="flex items-center justify-between mb-4">
        <h1 className="text-xl font-bold">수입정정 등록</h1>
        <button
          onClick={() => router.back()}
          className="text-sm text-gray-500 hover:text-gray-700"
        >
          ← 목록
        </button>
      </div>

      <form onSubmit={handleSubmit((d) => saveMut.mutate(d))} className="space-y-4">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">신고 구분</label>
            <select
              {...register('ieGbn')}
              className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="I">수입</option>
              <option value="E">수출</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">업체명 *</label>
            <input
              {...register('comNm', { required: '업체명을 입력하세요.' })}
              className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            {errors.comNm && <p className="text-red-500 text-xs mt-1">{errors.comNm.message}</p>}
          </div>
        </div>

        <div className="grid grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">신고번호 코드</label>
            <input {...register('sCode')} className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">연도</label>
            <input {...register('sYear')} placeholder="2024" className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">제출번호</label>
            <input {...register('sJechl')} className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">원신고일</label>
            <input type="date" {...register('jSingoDt')} className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">정정신고일</label>
            <input type="date" {...register('sSingoDt')} className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">관세청 구분</label>
            <select
              {...register('jGwiCd')}
              className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
            >
              <option value="">선택</option>
              {codes?.gwiList.map((g) => (
                <option key={g.jGwiCd} value={g.jGwiCd}>{g.jGwiDes}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">처리상태</label>
            <select
              {...register('fStCd')}
              className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
            >
              <option value="">선택</option>
              {codes?.fstList.map((f) => (
                <option key={f.fStCd} value={f.fStCd}>{f.fStDes}</option>
              ))}
            </select>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">정정사유</label>
          <select
            {...register('fJjCd')}
            className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
          >
            <option value="">선택</option>
            {codes?.fjjList.map((f) => (
              <option key={f.fJjCd} value={f.fJjCd}>{f.fJjDes1}</option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">정정내용</label>
          <textarea
            {...register('fJjContents')}
            rows={4}
            className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">담당자명</label>
            <input {...register('fJjNm')} className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">처리일</label>
            <input type="date" {...register('fJjRegDt')} className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
        </div>

        <div className="flex justify-end gap-2 pt-2 border-t">
          <button
            type="button"
            onClick={() => router.back()}
            className="px-4 py-2 text-sm border rounded hover:bg-gray-50"
          >
            취소
          </button>
          <button
            type="submit"
            disabled={saveMut.isPending}
            className="px-4 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50"
          >
            {saveMut.isPending ? '저장 중...' : '저장'}
          </button>
        </div>
      </form>
    </div>
  );
}
