/**
 * 견적 상세/수정 페이지 (V2 UI)
 *
 * IntegratedDetailTemplate + QuoteRegistration
 * URL 패턴:
 * - /quote-management/[id] → 상세 보기 (view)
 * - /quote-management/[id]?mode=edit → 수정 모드 (edit)
 */

"use client";

import { useRouter, useParams, useSearchParams } from "next/navigation";
import { useState, useEffect, useMemo, useCallback } from "react";
import { QuoteRegistration } from "@/components/quotes/QuoteRegistration";
import type { QuoteFormDataV2 } from "@/components/quotes/QuoteRegistration";
import { IntegratedDetailTemplate } from "@/components/templates/IntegratedDetailTemplate";
import { quoteConfig } from "@/components/quotes/quoteConfig";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { getQuoteById, updateQuote, finalizeQuote, calculateBomBulk, BomCalculateItem } from "@/components/quotes/actions";
import { transformApiToV2, transformV2ToApi, type QuoteFormDataV2 as QuoteFormDataV2Types } from "@/components/quotes/types";

export default function QuoteDetailPage() {
  const router = useRouter();
  const params = useParams();
  const searchParams = useSearchParams();
  const quoteId = params.id as string;

  // mode 체크
  const mode = searchParams.get("mode") || "view";
  const isEditMode = mode === "edit";

  const [quote, setQuote] = useState<QuoteFormDataV2Types | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    const loadQuote = async () => {
      setIsLoading(true);
      try {
        const result = await getQuoteById(quoteId);

        if (!result.success || !result.data) {
          toast.error(result.error || "견적 정보를 불러오는데 실패했습니다.");
          router.push("/sales/quote-management");
          return;
        }

        // API 응답을 V2 폼 데이터로 변환
        const v2Data = transformApiToV2(result.data as unknown as Parameters<typeof transformApiToV2>[0]);

        // bomResult 없는 개소가 있으면 자동 재계산
        const locationsNeedingRecalc = v2Data.locations.filter(
          loc => !loc.bomResult && loc.productCode && loc.openWidth > 0 && loc.openHeight > 0
        );

        if (locationsNeedingRecalc.length > 0) {

          // BOM 계산 요청 데이터 생성
          const bomItems: BomCalculateItem[] = locationsNeedingRecalc.map(loc => ({
            finished_goods_code: loc.productCode,
            openWidth: loc.openWidth,
            openHeight: loc.openHeight,
            quantity: loc.quantity,
            guideRailType: loc.guideRailType,
            motorPower: loc.motorPower,
            controller: loc.controller,
            wingSize: loc.wingSize,
            inspectionFee: loc.inspectionFee,
          }));

          const calcResult = await calculateBomBulk(bomItems);

          if (calcResult.success && calcResult.data?.items) {

            // 재계산 결과를 locations에 적용
            const updatedLocations = v2Data.locations.map((loc, _index) => {
              // productCode가 있고 bomResult가 없는 경우에만 업데이트
              if (!loc.bomResult && loc.productCode) {
                const calcItem = calcResult.data?.items.find(
                  item => item.finished_goods_code === loc.productCode
                );
                if (calcItem?.result) {
                  return { ...loc, bomResult: calcItem.result };
                }
              }
              return loc;
            });

            v2Data.locations = updatedLocations;
          } else {
            // no BOM result to merge
          }
        }

        setQuote(v2Data);
      } catch (error) {
        console.error("[QuoteDetailPage] 로드 오류:", error);
        toast.error("견적 정보를 불러오는데 실패했습니다.");
        router.push("/sales/quote-management");
      } finally {
        setIsLoading(false);
      }
    };

    if (quoteId) {
      loadQuote();
    }
  }, [quoteId, router]);

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

  // 수정 모드로 전환 핸들러
  const handleEdit = useCallback(() => {
    router.push(`/sales/quote-management/${quoteId}?mode=edit`);
  }, [router, quoteId]);

  // 수주등록 페이지로 이동 핸들러
  const handleOrderRegister = useCallback(() => {
    router.push(`/sales/order-management-sales/new?mode=new&quoteId=${quoteId}`);
  }, [router, quoteId]);

  // 기존 수주 보기 핸들러 (이미 수주가 있는 경우)
  const handleOrderView = useCallback(() => {
    if (quote?.orderId) {
      router.push(`/sales/order-management-sales/${quote.orderId}?mode=view`);
    }
  }, [router, quote?.orderId]);

  // 수정 저장 핸들러
  const handleSave = useCallback(async (data: QuoteFormDataV2, saveType: "temporary" | "final") => {
    setIsSaving(true);
    try {
      // V2 폼 데이터를 API 형식으로 변환
      const apiData = transformV2ToApi(data as unknown as QuoteFormDataV2Types);
      // status와 is_final은 finalizeQuote API가 담당하므로 제거
      delete (apiData as Record<string, unknown>).status;
      delete (apiData as Record<string, unknown>).is_final;


      // 1. 먼저 데이터 저장 (status는 변경하지 않음)
      const updateResult = await updateQuote(quoteId, apiData);

      if (!updateResult.success) {
        throw new Error(updateResult.error || "저장 중 오류가 발생했습니다.");
      }

      // 2. 견적 확정인 경우 finalize API 호출 (status 변경은 여기서 처리)
      if (saveType === "final") {
        const finalizeResult = await finalizeQuote(quoteId);

        if (!finalizeResult.success) {
          throw new Error(finalizeResult.error || "견적 확정 중 오류가 발생했습니다.");
        }

        toast.success("견적이 확정되었습니다.");
      } else {
        toast.success("저장되었습니다.");
      }

      if (isEditMode) {
        // edit 모드에서 저장 후 view 모드로 전환
        router.push(`/sales/quote-management/${quoteId}?mode=view`);
      } else {
        // view 모드에서 최종저장 후 페이지 새로고침 (데이터 갱신)
        router.refresh();
      }
    } catch (error) {
      console.error("[QuoteDetailPage] 저장 오류:", error);
      toast.error("저장 중 오류가 발생했습니다.");
    } finally {
      setIsSaving(false);
    }
  }, [router, quoteId, isEditMode]);

  // 동적 config (모드별 타이틀)
  // 참고: IntegratedDetailTemplate에서 mode에 따라 자동으로 "등록/수정" suffix 추가됨
  const dynamicConfig = useMemo(() => {
    return {
      ...quoteConfig,
      title: '견적',
    };
  }, []);

  // 커스텀 헤더 액션 (상태 뱃지)
  const customHeaderActions = useMemo(() => {
    if (!quote) return null;
    return (
      <Badge variant={quote.status === "final" ? "default" : quote.status === "temporary" ? "secondary" : "outline"}>
        {quote.status === "final" ? "견적 확정" : quote.status === "temporary" ? "저장됨" : "작성중"}
      </Badge>
    );
  }, [quote]);

  // 폼 콘텐츠 렌더링
  const renderFormContent = useCallback(() => {
    return (
      <QuoteRegistration
        mode={isEditMode ? "edit" : "view"}
        onBack={handleBack}
        onSave={handleSave}
        onEdit={handleEdit}
        onOrderRegister={handleOrderRegister}
        onOrderView={handleOrderView}
        initialData={quote as QuoteFormDataV2 | null}
        isLoading={isSaving}
        hideHeader={true}
      />
    );
  }, [isEditMode, handleBack, handleSave, handleEdit, handleOrderRegister, handleOrderView, quote, isSaving]);

  // IntegratedDetailTemplate 사용
  return (
    <IntegratedDetailTemplate
      config={dynamicConfig}
      mode={isEditMode ? "edit" : "view"}
      initialData={quote || {}}
      itemId={quoteId}
      isLoading={isLoading}
      headerActions={customHeaderActions}
      renderView={() => renderFormContent()}
      renderForm={() => renderFormContent()}
    />
  );
}