'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 { cardTransactionDetailConfig } from './cardTransactionDetailConfig';
import type { CardTransaction } from './types';
import {
  getCardTransactionById,
  createCardTransaction,
  updateCardTransaction,
  deleteCardTransaction,
  getCardList,
} from './actions';
import { useDevFill, generateCardTransactionData } from '@/components/dev';

// ===== Props =====
interface CardTransactionDetailClientProps {
  transactionId?: string;
  initialMode?: DetailMode;
}

export default function CardTransactionDetailClient({
  transactionId,
  initialMode = 'view',
}: CardTransactionDetailClientProps) {
  const router = useRouter();
  const [mode, setMode] = useState<DetailMode>(initialMode);
  const [transaction, setTransaction] = useState<CardTransaction | null>(null);
  const [isLoading, setIsLoading] = useState(initialMode !== 'create');

  // ===== DevFill: 자동 입력 기능 =====
  useDevFill('cardTransaction', useCallback(async () => {
    if (initialMode === 'create') {
      // 카드 목록 가져오기
      const cardResult = await getCardList();
      const cards = cardResult.success ? cardResult.data : undefined;

      const mockData = generateCardTransactionData({ cards });
      setTransaction(mockData as unknown as CardTransaction);
      toast.success('카드 사용내역 데이터가 자동 입력되었습니다.');
    }
  }, [initialMode]));

  // ===== 데이터 로드 =====
  useEffect(() => {
    const loadTransaction = async () => {
      if (transactionId && initialMode !== 'create') {
        setIsLoading(true);
        const result = await getCardTransactionById(transactionId);
        if (result.success && result.data) {
          setTransaction(result.data);
        } else {
          toast.error(result.error || '카드 사용내역을 불러오는데 실패했습니다.');
        }
        setIsLoading(false);
      }
    };
    loadTransaction();
  }, [transactionId, initialMode]);

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

      if (!submitData.merchantName) {
        toast.error('가맹점명을 입력해주세요.');
        return { success: false, error: '가맹점명을 입력해주세요.' };
      }
      if (!submitData.amount || Number(submitData.amount) <= 0) {
        toast.error('사용금액을 입력해주세요.');
        return { success: false, error: '사용금액을 입력해주세요.' };
      }
      if (!submitData.usedAt) {
        toast.error('사용일시를 선택해주세요.');
        return { success: false, error: '사용일시를 선택해주세요.' };
      }

      const result =
        mode === 'create'
          ? await createCardTransaction(submitData as Parameters<typeof createCardTransaction>[0])
          : await updateCardTransaction(transactionId!, submitData as Parameters<typeof updateCardTransaction>[1]);

      if (result.success) {
        toast.success(mode === 'create' ? '카드 사용내역이 등록되었습니다.' : '카드 사용내역이 수정되었습니다.');
        router.push('/ko/accounting/card-transactions');
        return { success: true };
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
        return { success: false, error: result.error };
      }
    },
    [mode, transactionId, router]
  );

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

    const result = await deleteCardTransaction(transactionId);
    if (result.success) {
      toast.success('카드 사용내역이 삭제되었습니다.');
      router.push('/ko/accounting/card-transactions');
      return { success: true };
    } else {
      toast.error(result.error || '삭제에 실패했습니다.');
      return { success: false, error: result.error };
    }
  }, [transactionId, router]);

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

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