/**
 * 견적 등록 페이지 (V2 UI)
 *
 * IntegratedDetailTemplate + QuoteRegistration
 * URL: /sales/quote-management/new
 */

'use client';

import { useRouter } from 'next/navigation';
import { useState, useCallback } from 'react';
import { QuoteRegistration } from '@/components/quotes/QuoteRegistration';
import type { QuoteFormDataV2 } from '@/components/quotes/QuoteRegistration';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { quoteCreateConfig } from '@/components/quotes/quoteConfig';
import { toast } from 'sonner';
import { createQuote } from '@/components/quotes/actions';
import { transformV2ToApi, type QuoteFormDataV2 as QuoteFormDataV2Types } from '@/components/quotes/types';

export default function QuoteNewPage() {
  const router = useRouter();
  const [isSaving, setIsSaving] = useState(false);

  const handleBack = useCallback(() => {
    router.push('/sales/quote-management');
  }, [router]);

  const handleSave = useCallback(async (data: QuoteFormDataV2, saveType: 'temporary' | 'final') => {
    setIsSaving(true);
    try {
      // V2 폼 데이터를 API 형식으로 변환
      const updatedData = { ...data, status: saveType };
      const apiData = transformV2ToApi(updatedData as unknown as QuoteFormDataV2Types);


      // API 호출
      const result = await createQuote(apiData);

      if (!result.success) {
        toast.error(result.error || '저장 중 오류가 발생했습니다.');
        return;
      }

      toast.success(`${saveType === 'temporary' ? '임시' : '최종'} 저장 완료`);

      // 저장 후 상세 페이지로 이동
      if (result.data?.id) {
        router.push(`/sales/quote-management/${result.data.id}?mode=view`);
      }
    } catch (error) {
      console.error('[QuoteNewPage] 저장 오류:', error);
      toast.error('저장 중 오류가 발생했습니다.');
    } finally {
      setIsSaving(false);
    }
  }, [router]);

  // 폼 콘텐츠 렌더링
  const renderFormContent = useCallback(() => {
    return (
      <QuoteRegistration
        mode="create"
        onBack={handleBack}
        onSave={handleSave}
        isLoading={isSaving}
        hideHeader={true}
      />
    );
  }, [handleBack, handleSave, isSaving]);

  return (
    <IntegratedDetailTemplate
      config={quoteCreateConfig}
      mode="create"
      isLoading={false}
      onCancel={handleBack}
      renderForm={renderFormContent}
    />
  );
}