/**
 * 견적 등록 페이지
 */

"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { QuoteRegistration, QuoteFormData } from "@/components/quotes/QuoteRegistration";
import { createQuote, transformFormDataToApi } from "@/components/quotes";
import { toast } from "sonner";

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

  const handleBack = () => {
    router.push("/sales/quote-management");
  };

  const handleSave = async (formData: QuoteFormData): Promise<{ success: boolean; error?: string }> => {
    if (isSaving) return { success: false, error: '저장 중입니다.' };
    setIsSaving(true);

    try {
      // DEBUG: 원본 formData 확인
      console.log('[QuoteNewPage] formData 원본:', {
        writer: formData.writer,
        manager: formData.manager,
        contact: formData.contact,
        remarks: formData.remarks,
      });

      // FormData를 API 요청 형식으로 변환
      const apiData = transformFormDataToApi(formData);

      // DEBUG: 변환된 apiData 확인
      console.log('[QuoteNewPage] apiData 변환 후:', {
        author: (apiData as any).author,
        manager: (apiData as any).manager,
        contact: (apiData as any).contact,
        remarks: (apiData as any).remarks,
      });

      const result = await createQuote(apiData as any);

      if (result.success && result.data) {
        // toast는 IntegratedDetailTemplate에서 처리
        router.push(`/sales/quote-management/${result.data.id}`);
        return { success: true };
      } else {
        return { success: false, error: result.error || "견적 등록에 실패했습니다." };
      }
    } catch (error) {
      return { success: false, error: "견적 등록에 실패했습니다." };
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <QuoteRegistration
      onBack={handleBack}
      onSave={handleSave}
    />
  );
}
