"use client";

/**
 * 수주 등록 페이지
 * API 연동 완료 (2025-01-08)
 *
 * quoteId 파라미터 지원 (2026-01-27)
 * - /sales/order-management-sales/new?quoteId=123 형태로 접근 시
 * - 해당 견적 정보를 자동으로 불러와 폼에 채움
 */

import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { OrderRegistration, OrderFormData, createOrder, createOrderFromQuote, getQuoteByIdForSelect } from "@/components/orders";
import type { QuotationForSelect, QuotationItem } from "@/components/orders/actions";
import { toast } from "sonner";
import { Loader2 } from "lucide-react";

export default function OrderNewPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const quoteId = searchParams.get("quoteId");

  const [initialQuotation, setInitialQuotation] = useState<QuotationForSelect | undefined>();
  const [isLoading, setIsLoading] = useState(!!quoteId);

  // quoteId가 있으면 견적 데이터 로드
  useEffect(() => {
    const loadQuoteData = async () => {
      if (!quoteId) return;

      setIsLoading(true);
      try {
        const result = await getQuoteByIdForSelect(quoteId);

        if (result.success && result.data) {
          setInitialQuotation(result.data);
          toast.success("견적 정보가 불러와졌습니다.");
        } else {
          toast.error(result.error || "견적 정보를 불러오는데 실패했습니다.");
        }
      } catch (error) {
        console.error("Error loading quote:", error);
        toast.error("견적 정보를 불러오는데 실패했습니다.");
      } finally {
        setIsLoading(false);
      }
    };

    loadQuoteData();
  }, [quoteId]);

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

  const handleSave = async (formData: OrderFormData) => {
    try {
      // quoteId가 있으면 견적→수주 변환 API 호출 (개소별 분리 포함)
      if (quoteId) {
        const result = await createOrderFromQuote(Number(quoteId), {
           deliveryDate: formData.expectedShipDate,
          memo: formData.remarks,
          deliveryMethodCode: formData.deliveryMethod,
          options: {
            receiver: formData.receiver,
            receiver_contact: formData.receiverContact,
            shipping_address: formData.address,
            shipping_address_detail: formData.addressDetail,
            shipping_cost_code: formData.shippingCost,
          },
        });

        if (result.success) {
          toast.success("견적에서 수주가 생성되었습니다.");
          router.push("/sales/order-management-sales");
        } else {
          toast.error(result.error || "수주 생성에 실패했습니다.");
        }
        return;
      }

      const result = await createOrder(formData);

      if (result.success) {
        toast.success("수주가 등록되었습니다.");
        router.push("/sales/order-management-sales");
      } else {
        toast.error(result.error || "수주 등록에 실패했습니다.");
      }
    } catch (error) {
      console.error("Error creating order:", error);
      toast.error("수주 등록 중 오류가 발생했습니다.");
    }
  };

  // 로딩 중일 때 로딩 표시
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
          <p className="text-gray-600">견적 정보를 불러오는 중...</p>
        </div>
      </div>
    );
  }

  // initialData 생성 - 견적 데이터가 있으면 변환하여 전달
  const initialData: Partial<OrderFormData> | undefined = initialQuotation
    ? {
        selectedQuotation: initialQuotation,
        clientId: initialQuotation.clientId || "",
        clientName: initialQuotation.client,
        siteName: initialQuotation.siteName,
        manager: initialQuotation.manager || "",
        contact: initialQuotation.contact || "",
        items: (initialQuotation.items || []).map((qi: QuotationItem) => ({
          id: qi.id,
          itemId: qi.itemId ? Number(qi.itemId) : undefined,
          itemCode: qi.itemCode,
          itemName: qi.itemName,
          type: qi.type,
          symbol: qi.symbol,
          spec: qi.spec,
          width: 0,
          height: 0,
          quantity: qi.quantity,
          unit: qi.unit,
          unitPrice: qi.unitPrice,
          amount: qi.amount,
          isFromQuotation: true,
        })),
      }
    : undefined;

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