'use client';

import { useState, useCallback } from 'react';
import type { BillFormData } from '../types';
import { INITIAL_BILL_FORM_DATA } from '../types';
import {
  VALID_CHECK_RECEIVED_STATUSES,
  VALID_CHECK_ISSUED_STATUSES,
} from '../constants';

export function useBillForm(initialData?: Partial<BillFormData>) {
  const [formData, setFormData] = useState<BillFormData>({
    ...INITIAL_BILL_FORM_DATA,
    ...initialData,
  });

  const updateField = useCallback(<K extends keyof BillFormData>(field: K, value: BillFormData[K]) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  }, []);

  // 증권종류 변경 시 연관 필드 초기화
  const handleInstrumentTypeChange = useCallback((newType: string) => {
    setFormData(prev => {
      const next = { ...prev, instrumentType: newType as BillFormData['instrumentType'] };
      const isCheckType = newType === 'cashierCheck' || newType === 'currentCheck';

      // 약속어음 외에는 전자 불가 → 지류로 리셋
      if (newType !== 'promissory' && prev.medium === 'electronic') {
        next.medium = 'paper';
      }

      // 수표 전환 시: 만기일, 할인, 관련 필드 리셋
      if (isCheckType) {
        next.maturityDate = '';
        next.isDiscounted = false;
        if (!VALID_CHECK_RECEIVED_STATUSES.includes(prev.receivedStatus)) {
          next.receivedStatus = 'stored';
        }
        if (!VALID_CHECK_ISSUED_STATUSES.includes(prev.issuedStatus)) {
          next.issuedStatus = 'stored';
        }
        if (prev.paymentPlace === 'payerAddress' || prev.paymentPlace === 'other') {
          next.paymentPlace = '';
        }
      }

      return next;
    });
  }, []);

  // 거래방향 변경 시 상태 초기화
  const handleDirectionChange = useCallback((newDirection: string) => {
    setFormData(prev => ({
      ...prev,
      direction: newDirection as BillFormData['direction'],
      receivedStatus: 'stored',
      issuedStatus: 'stored',
    }));
  }, []);

  // 이력 관리
  const addInstallment = useCallback(() => {
    setFormData(prev => ({
      ...prev,
      installments: [
        ...prev.installments,
        { id: `inst-${Date.now()}`, date: '', type: 'other', amount: 0, counterparty: '', note: '' },
      ],
    }));
  }, []);

  const removeInstallment = useCallback((id: string) => {
    setFormData(prev => ({
      ...prev,
      installments: prev.installments.filter(inst => inst.id !== id),
    }));
  }, []);

  const updateInstallment = useCallback((id: string, field: string, value: string | number) => {
    setFormData(prev => ({
      ...prev,
      installments: prev.installments.map(inst =>
        inst.id === id ? { ...inst, [field]: value } : inst
      ),
    }));
  }, []);

  // 폼 전체 덮어쓰기 (API 데이터 로드 시)
  const setFormDataFull = useCallback((data: BillFormData) => {
    setFormData(data);
  }, []);

  return {
    formData,
    updateField,
    handleInstrumentTypeChange,
    handleDirectionChange,
    addInstallment,
    removeInstallment,
    updateInstallment,
    setFormDataFull,
  };
}
