'use client';

import { useState, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import type { DetailMode } from '@/components/templates/IntegratedDetailTemplate/types';
import { withdrawalDetailConfig } from './withdrawalDetailConfig';
import type { WithdrawalRecord } from './types';
import {
  getWithdrawalById,
  createWithdrawal,
  updateWithdrawal,
  deleteWithdrawal,
  getVendors,
  getBankAccounts,
} from './actions';
import { useDevFill, generateWithdrawalData } from '@/components/dev';
import { invalidateDashboard } from '@/lib/dashboard-invalidation';

// ===== Props =====
interface WithdrawalDetailClientV2Props {
  withdrawalId?: string;
  initialMode?: DetailMode;
}

export default function WithdrawalDetailClientV2({
  withdrawalId,
  initialMode = 'view',
}: WithdrawalDetailClientV2Props) {
  const router = useRouter();
  const [mode, setMode] = useState<DetailMode>(initialMode);
  const [withdrawal, setWithdrawal] = useState<WithdrawalRecord | null>(null);
  const [isLoading, setIsLoading] = useState(initialMode !== 'create');

  // ===== DevFill: 자동 입력 기능 =====
  useDevFill('withdrawal', useCallback(async () => {
    if (initialMode === 'create') {
      // 거래처 및 계좌 목록 가져오기
      const [vendorResult, bankAccountResult] = await Promise.all([
        getVendors(),
        getBankAccounts(),
      ]);
      const vendors = vendorResult.success ? vendorResult.data : undefined;
      const bankAccounts = bankAccountResult.success ? bankAccountResult.data : undefined;

      const mockData = generateWithdrawalData({ vendors, bankAccounts });
      setWithdrawal(mockData as unknown as WithdrawalRecord);
      toast.success('출금 데이터가 자동 입력되었습니다.');
    }
  }, [initialMode]));

  // ===== 데이터 로드 =====
  useEffect(() => {
    const loadWithdrawal = async () => {
      if (withdrawalId && initialMode !== 'create') {
        setIsLoading(true);
        const result = await getWithdrawalById(withdrawalId);
        if (result.success && result.data) {
          setWithdrawal(result.data);
        } else {
          toast.error(result.error || '출금 내역을 불러오는데 실패했습니다.');
        }
        setIsLoading(false);
      }
    };
    loadWithdrawal();
  }, [withdrawalId, initialMode]);

  // ===== 저장/등록 핸들러 =====
  const handleSubmit = useCallback(
    async (formData: Record<string, unknown>): Promise<{ success: boolean; error?: string }> => {
      const submitData = withdrawalDetailConfig.transformSubmitData?.(formData) || formData;

      if (!submitData.vendorId) {
        toast.error('거래처를 선택해주세요.');
        return { success: false, error: '거래처를 선택해주세요.' };
      }

      const result =
        mode === 'create'
          ? await createWithdrawal(submitData as Partial<WithdrawalRecord>)
          : await updateWithdrawal(withdrawalId!, submitData as Partial<WithdrawalRecord>);

      if (result.success) {
        invalidateDashboard('withdrawal');
        toast.success(mode === 'create' ? '출금 내역이 등록되었습니다.' : '출금 내역이 수정되었습니다.');
        router.push('/ko/accounting/withdrawals');
        return { success: true };
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
        return { success: false, error: result.error };
      }
    },
    [mode, withdrawalId, router]
  );

  // ===== 삭제 핸들러 =====
  const handleDelete = useCallback(async (): Promise<{ success: boolean; error?: string }> => {
    if (!withdrawalId) return { success: false, error: 'ID가 없습니다.' };

    const result = await deleteWithdrawal(withdrawalId);
    if (result.success) {
      invalidateDashboard('withdrawal');
      toast.success('출금 내역이 삭제되었습니다.');
      router.push('/ko/accounting/withdrawals');
      return { success: true };
    } else {
      toast.error(result.error || '삭제에 실패했습니다.');
      return { success: false, error: result.error };
    }
  }, [withdrawalId, router]);

  // ===== 모드 변경 핸들러 =====
  const handleModeChange = useCallback(
    (newMode: DetailMode) => {
      if (newMode === 'edit' && withdrawalId) {
        router.push(`/ko/accounting/withdrawals/${withdrawalId}?mode=edit`);
      } else {
        setMode(newMode);
      }
    },
    [withdrawalId, router]
  );

  // 타이틀 동적 설정
  // IntegratedDetailTemplate: create → "{title} 등록", view → "{title}", edit → "{title} 수정"
  // view 모드에서 "출금 상세"로 표시하려면 직접 설정 필요
  const dynamicConfig = {
    ...withdrawalDetailConfig,
    title: mode === 'view' ? '출금 상세' : '출금',
  };

  return (
    <IntegratedDetailTemplate
      config={dynamicConfig as Parameters<typeof IntegratedDetailTemplate>[0]['config']}
      mode={mode}
      initialData={withdrawal as unknown as Record<string, unknown> | undefined}
      itemId={withdrawalId}
      isLoading={isLoading}
      onSubmit={handleSubmit}
      onDelete={handleDelete}
      onModeChange={handleModeChange}
    />
  );
}
