'use client';

/**
 * 거래처(영업) 상세 클라이언트 컴포넌트 V2
 * IntegratedDetailTemplate 기반 마이그레이션
 *
 * 클라이언트 사이드 데이터 페칭 (useClientList 훅 활용)
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import type { DetailMode, IntegratedDetailTemplateRef } from '@/components/templates/IntegratedDetailTemplate/types';
import type { Client, ClientFormData } from '@/hooks/useClientList';
import { useClientList } from '@/hooks/useClientList';
import { clientDetailConfig } from './clientDetailConfig';
import { toast } from 'sonner';
import { useDevFillContext } from '@/components/dev/DevFillContext';
import { generateClientData } from '@/components/dev/generators/clientData';

interface ClientDetailClientV2Props {
  clientId?: string;
  initialMode?: DetailMode;
}

// 8자리 영문+숫자 코드 생성
function generateCode(): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let result = '';
  for (let i = 0; i < 8; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

export function ClientDetailClientV2({ clientId, initialMode }: ClientDetailClientV2Props) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { fetchClient, createClient, updateClient, deleteClient } = useClientList();
  const templateRef = useRef<IntegratedDetailTemplateRef>(null);
  const { isEnabled, registerFillForm, unregisterFillForm } = useDevFillContext();

  // URL 쿼리에서 모드 결정
  const modeFromQuery = searchParams.get('mode') as DetailMode | null;
  const isNewMode = !clientId || clientId === 'new';

  const [mode, setMode] = useState<DetailMode>(() => {
    if (isNewMode) return 'create';
    if (initialMode) return initialMode;
    if (modeFromQuery === 'edit') return 'edit';
    return 'view';
  });

  const [clientData, setClientData] = useState<Client | null>(null);
  const [isLoading, setIsLoading] = useState(!isNewMode);
  const [generatedCode, setGeneratedCode] = useState<string>('');

  // 데이터 로드
  useEffect(() => {
    const loadData = async () => {
      if (isNewMode) {
        // 신규 등록 시 코드 생성
        const code = generateCode();
        setGeneratedCode(code);
        setIsLoading(false);
        return;
      }

      setIsLoading(true);
      try {
        const data = await fetchClient(clientId!);
        if (data) {
          setClientData(data);
        } else {
          toast.error('거래처를 불러오는데 실패했습니다.');
          router.push(clientDetailConfig.basePath);
        }
      } catch (error) {
        console.error('거래처 조회 실패:', error);
        toast.error('거래처를 불러오는데 실패했습니다.');
        router.push(clientDetailConfig.basePath);
      } finally {
        setIsLoading(false);
      }
    };

    loadData();
  }, [clientId, isNewMode, router, fetchClient]);

  // URL 쿼리 변경 감지
  useEffect(() => {
    if (!isNewMode && modeFromQuery === 'edit') {
      setMode('edit');
    } else if (!isNewMode && !modeFromQuery) {
      setMode('view');
    }
  }, [modeFromQuery, isNewMode]);

  // DevFill 등록 (신규 등록 모드일 때만)
  useEffect(() => {
    if (!isEnabled || !isNewMode) return;

    const handleDevFill = () => {
      const data = generateClientData();
      if (templateRef.current) {
        templateRef.current.setFormData(data as unknown as Record<string, unknown>);
      }
    };

    registerFillForm('client', handleDevFill);

    return () => {
      unregisterFillForm('client');
    };
  }, [isEnabled, isNewMode, registerFillForm, unregisterFillForm]);

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

  // 저장 핸들러
  const handleSubmit = useCallback(
    async (formData: Record<string, unknown>) => {
      try {
        // formData를 ClientFormData로 변환
        const clientFormData: ClientFormData = {
          clientCode: (formData.clientCode as string) || generatedCode,
          name: formData.name as string,
          businessNo: formData.businessNo as string,
          representative: formData.representative as string,
          phone: formData.phone as string,
          address: formData.address as string,
          email: formData.email as string,
          businessType: formData.businessType as string,
          businessItem: formData.businessItem as string,
          isActive: formData.isActive === 'true',
          clientType: (formData.clientType as ClientFormData['clientType']) || '매입',
          mobile: formData.mobile as string,
          fax: formData.fax as string,
          managerName: formData.managerName as string,
          managerTel: formData.managerTel as string,
          systemManager: formData.systemManager as string,
          accountId: formData.accountId as string || '',
          accountPassword: formData.accountPassword as string || '',
          purchasePaymentDay: '말일',
          salesPaymentDay: '말일',
          taxAgreement: false,
          taxAmount: '',
          taxStartDate: '',
          taxEndDate: '',
          badDebt: false,
          badDebtAmount: '',
          badDebtReceiveDate: '',
          badDebtEndDate: '',
          badDebtProgress: '',
          memo: formData.memo as string || '',
        };

        if (isNewMode) {
          const result = await createClient(clientFormData);
          if (result) {
            toast.success('거래처가 등록되었습니다.');
            router.push(clientDetailConfig.basePath);
            return { success: true };
          }
          return { success: false, error: '거래처 등록에 실패했습니다.' };
        } else {
          const result = await updateClient(clientId!, clientFormData);
          if (result) {
            toast.success('거래처가 수정되었습니다.');
            router.push(`${clientDetailConfig.basePath}/${clientId}?mode=view`);
            return { success: true };
          }
          return { success: false, error: '거래처 수정에 실패했습니다.' };
        }
      } catch (error) {
        console.error('저장 실패:', error);
        return { success: false, error: error instanceof Error ? error.message : '저장 중 오류가 발생했습니다.' };
      }
    },
    [isNewMode, clientId, generatedCode, router, createClient, updateClient]
  );

  // 삭제 핸들러
  const handleDelete = useCallback(
    async (id: string | number) => {
      try {
        const result = await deleteClient(String(id));
        if (result) {
          toast.success('거래처가 삭제되었습니다.');
          router.push(clientDetailConfig.basePath);
          return { success: true };
        }
        return { success: false, error: '거래처 삭제에 실패했습니다.' };
      } catch (error) {
        console.error('삭제 실패:', error);
        return { success: false, error: error instanceof Error ? error.message : '삭제 중 오류가 발생했습니다.' };
      }
    },
    [router, deleteClient]
  );

  // 취소 핸들러
  const handleCancel = useCallback(() => {
    if (isNewMode) {
      router.push(clientDetailConfig.basePath);
    } else {
      setMode('view');
      router.push(`${clientDetailConfig.basePath}/${clientId}?mode=view`);
    }
  }, [router, clientId, isNewMode]);

  // 초기 데이터 (신규 등록 시 코드 포함)
  const initialData = isNewMode
    ? ({ code: generatedCode } as Client)
    : clientData || undefined;

  // 타이틀 동적 설정
  const dynamicConfig = {
    ...clientDetailConfig,
    title:
      mode === 'create'
        ? '거래처'
        : mode === 'edit'
          ? clientData?.name || '거래처'
          : clientData?.name || '거래처 상세',
  };

  return (
    <IntegratedDetailTemplate
      ref={templateRef}
      config={dynamicConfig}
      mode={mode}
      initialData={initialData as Record<string, unknown> | undefined}
      itemId={clientId}
      isLoading={isLoading}
      onSubmit={handleSubmit}
      onDelete={handleDelete}
      onCancel={handleCancel}
      onModeChange={handleModeChange}
    />
  );
}
