/**
 * 견적 상세/수정 페이지 (V2 통합)
 * - 기본 정보 표시 (view mode)
 * - 자동 견적 산출 정보
 * - 견적서 / 산출내역서 / 발주서 모달
 * - 수정 모드 (edit mode)
 *
 * URL 패턴:
 * - /quote-management/[id] → 상세 보기 (view)
 * - /quote-management/[id]?mode=edit → 수정 모드 (edit)
 */

"use client";

import { useRouter, useParams, useSearchParams } from "next/navigation";
import { useState, useEffect, useCallback } from "react";
import { QuoteRegistration, QuoteFormData } from "@/components/quotes/QuoteRegistration";
import { QuoteDocument } from "@/components/quotes/QuoteDocument";
import { QuoteCalculationReport } from "@/components/quotes/QuoteCalculationReport";
import { PurchaseOrderDocument } from "@/components/quotes/PurchaseOrderDocument";
import {
  getQuoteById,
  finalizeQuote,
  convertQuoteToOrder,
  sendQuoteEmail,
  sendQuoteKakao,
  transformQuoteToFormData,
  updateQuote,
  transformFormDataToApi,
} from "@/components/quotes";
import { getCompanyInfo } from "@/components/settings/CompanyInfoManagement/actions";
import type { CompanyFormData } from "@/components/settings/CompanyInfoManagement/types";
import { getItemTypeCodes, type CommonCode } from "@/lib/api/common-codes";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { DocumentViewer } from "@/components/document-system";
import {
  FileText,
  Edit,
  List,
  Printer,
  FileOutput,
  FileCheck,
  Package,
  ChevronDown,
  ChevronUp,
} from "lucide-react";
import { DetailPageSkeleton } from "@/components/ui/skeleton";

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

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

  const [quote, setQuote] = useState<QuoteFormData | null>(null);
  const [companyInfo, setCompanyInfo] = useState<CompanyFormData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isProcessing, setIsProcessing] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

  // 다이얼로그 상태
  const [isQuoteDocumentOpen, setIsQuoteDocumentOpen] = useState(false);
  const [isCalculationReportOpen, setIsCalculationReportOpen] = useState(false);
  const [isPurchaseOrderOpen, setIsPurchaseOrderOpen] = useState(false);

  // 산출내역서 표시 옵션
  const [showDetailedBreakdown, setShowDetailedBreakdown] = useState(true);
  const [showMaterialList, setShowMaterialList] = useState(true);

  // BOM 자재 상세 펼침/접힘 상태
  const [isBomExpanded, setIsBomExpanded] = useState(true);

  // 공통 코드 (item_type)
  const [itemTypeCodes, setItemTypeCodes] = useState<CommonCode[]>([]);

  // 견적 데이터 조회
  const fetchQuote = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await getQuoteById(quoteId);
      if (result.success && result.data) {
        // 디버깅: Quote 변환 전 데이터
        console.log('[QuoteDetail] Quote data:', {
          clientId: result.data.clientId,
          clientName: result.data.clientName,
          calculationInputs: result.data.calculationInputs,
          items: result.data.items?.map(item => ({
            productName: item.productName,
            quantity: item.quantity,
            unitPrice: item.unitPrice,
            totalAmount: item.totalAmount,
          })),
        });

        const formData = transformQuoteToFormData(result.data);

        // 디버깅: QuoteFormData 변환 후 데이터
        console.log('[QuoteDetail] FormData:', {
          clientId: formData.clientId,
          clientName: formData.clientName,
          items: formData.items?.map(item => ({
            productName: item.productName,
            quantity: item.quantity,
            inspectionFee: item.inspectionFee,
            totalAmount: item.totalAmount,
          })),
        });

        setQuote(formData);
      } else {
        toast.error(result.error || "견적 정보를 불러오는데 실패했습니다.");
        router.push("/sales/quote-management");
      }
    } catch (error) {
      toast.error("견적 정보를 불러오는데 실패했습니다.");
      router.push("/sales/quote-management");
    } finally {
      setIsLoading(false);
    }
  }, [quoteId, router]);

  // 회사 정보 조회
  const fetchCompanyInfo = useCallback(async () => {
    try {
      const result = await getCompanyInfo();
      if (result.success && result.data) {
        setCompanyInfo(result.data);
      }
    } catch (error) {
      console.error('[QuoteDetail] Failed to fetch company info:', error);
    }
  }, []);

  // 공통 코드 조회
  const fetchItemTypeCodes = useCallback(async () => {
    const result = await getItemTypeCodes();
    if (result.success && result.data) {
      setItemTypeCodes(result.data);
    }
  }, []);

  // item_type 코드 → 이름 변환 헬퍼
  const getItemTypeLabel = useCallback((code: string | undefined | null): string => {
    if (!code) return '-';
    const found = itemTypeCodes.find(item => item.code === code);
    return found?.name || code;
  }, [itemTypeCodes]);

  useEffect(() => {
    fetchQuote();
    fetchCompanyInfo();
    fetchItemTypeCodes();
  }, [fetchQuote, fetchCompanyInfo, fetchItemTypeCodes]);

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

  const handleEdit = () => {
    router.push(`/sales/quote-management/${quoteId}?mode=edit`);
  };

  // V2 패턴: 수정 저장 핸들러
  const handleSave = async (formData: QuoteFormData): Promise<{ success: boolean; error?: string }> => {
    if (isSaving) return { success: false, error: '저장 중입니다.' };
    setIsSaving(true);

    try {
      const apiData = transformFormDataToApi(formData);
      const result = await updateQuote(quoteId, apiData as any);

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

  const handleFinalize = async () => {
    if (isProcessing) return;
    setIsProcessing(true);
    try {
      const result = await finalizeQuote(quoteId);
      if (result.success) {
        toast.success("견적이 최종 확정되었습니다.");
        fetchQuote(); // 데이터 새로고침
      } else {
        toast.error(result.error || "견적 확정에 실패했습니다.");
      }
    } catch (error) {
      toast.error("견적 확정에 실패했습니다.");
    } finally {
      setIsProcessing(false);
    }
  };

  const handleConvertToOrder = async () => {
    if (isProcessing) return;
    setIsProcessing(true);
    try {
      const result = await convertQuoteToOrder(quoteId);
      if (result.success) {
        toast.success("수주로 전환되었습니다.");
        if (result.orderId) {
          router.push(`/sales/order-management/${result.orderId}`);
        } else {
          router.push("/sales/order-management");
        }
      } else {
        toast.error(result.error || "수주 전환에 실패했습니다.");
      }
    } catch (error) {
      toast.error("수주 전환에 실패했습니다.");
    } finally {
      setIsProcessing(false);
    }
  };

  const handleSendEmail = async () => {
    if (isProcessing) return;
    // TODO: 이메일 입력 다이얼로그 추가
    const email = prompt("발송할 이메일 주소를 입력하세요:");
    if (!email) return;

    setIsProcessing(true);
    try {
      const result = await sendQuoteEmail(quoteId, { email });
      if (result.success) {
        toast.success("이메일이 발송되었습니다.");
      } else {
        toast.error(result.error || "이메일 발송에 실패했습니다.");
      }
    } catch (error) {
      toast.error("이메일 발송에 실패했습니다.");
    } finally {
      setIsProcessing(false);
    }
  };

  const handleSendKakao = async () => {
    if (isProcessing) return;
    // TODO: 카카오 발송 다이얼로그 추가
    const phone = prompt("발송할 전화번호를 입력하세요:");
    if (!phone) return;

    setIsProcessing(true);
    try {
      const result = await sendQuoteKakao(quoteId, { phone });
      if (result.success) {
        toast.success("카카오톡이 발송되었습니다.");
      } else {
        toast.error(result.error || "카카오톡 발송에 실패했습니다.");
      }
    } catch (error) {
      toast.error("카카오톡 발송에 실패했습니다.");
    } finally {
      setIsProcessing(false);
    }
  };

  const formatDate = (dateStr: string) => {
    if (!dateStr) return "-";
    return dateStr;
  };

  const formatAmount = (amount: number | undefined) => {
    if (!amount) return "0";
    return amount.toLocaleString("ko-KR");
  };

  // 총 금액 계산 (실제 금액 우선, 없으면 검사비 사용)
  const totalAmount =
    quote?.items?.reduce((sum, item) => {
      // totalAmount가 있으면 사용, 없으면 unitPrice * quantity, 마지막으로 inspectionFee
      const itemAmount = item.totalAmount || (item.unitPrice || 0) * (item.quantity || 1) || (item.inspectionFee || 0) * (item.quantity || 1);
      return sum + itemAmount;
    }, 0) || 0;

  if (isLoading) {
    return <DetailPageSkeleton sections={2} fieldsPerSection={6} />;
  }

  if (!quote) {
    return (
      <div className="p-6">
        <p className="text-gray-500">견적 정보를 찾을 수 없습니다.</p>
        <Button onClick={handleBack} className="mt-4">
          목록으로 돌아가기
        </Button>
      </div>
    );
  }

  // V2 패턴: Edit 모드일 때 QuoteRegistration 컴포넌트 렌더링
  if (isEditMode) {
    return (
      <QuoteRegistration
        onBack={handleBack}
        onSave={handleSave}
        editingQuote={quote}
      />
    );
  }

  // View 모드: 상세 보기
  return (
    <div className="p-6 space-y-6">
      {/* 헤더 */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <FileText className="w-6 h-6" />
            견적 상세
          </h1>
          <p className="text-gray-500 mt-1">견적번호: {quote.id}</p>
        </div>

        <div className="flex flex-wrap gap-2">
          {/* 문서 버튼들 */}
          <Button
            variant="outline"
            onClick={() => setIsQuoteDocumentOpen(true)}
          >
            <Printer className="w-4 h-4 mr-2" />
            견적서
          </Button>
          <Button
            variant="outline"
            onClick={() => setIsCalculationReportOpen(true)}
          >
            <FileText className="w-4 h-4 mr-2" />
            산출내역서
          </Button>
          <Button
            variant="outline"
            onClick={() => setIsPurchaseOrderOpen(true)}
          >
            <FileOutput className="w-4 h-4 mr-2" />
            발주서
          </Button>

          {/* 액션 버튼들 */}
          <Button variant="outline" onClick={handleBack}>
            <List className="w-4 h-4 mr-2" />
            목록
          </Button>
          <Button variant="outline" onClick={handleEdit}>
            <Edit className="w-4 h-4 mr-2" />
            수정
          </Button>
          <Button
            onClick={handleFinalize}
            disabled={isProcessing}
            className="bg-green-600 hover:bg-green-700 text-white"
          >
            <FileCheck className="w-4 h-4 mr-2" />
            최종확정
          </Button>
        </div>
      </div>

      {/* 기본 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>기본 정보</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
            <div>
              <Label>견적번호</Label>
              <Input
                value={quote.id || "-"}
                disabled
                className="bg-gray-50 text-black font-medium"
              />
            </div>
            <div>
              <Label>작성자</Label>
              <Input
                value={quote.writer || "-"}
                disabled
                className="bg-gray-50 text-black font-medium"
              />
            </div>
            <div>
              <Label>발주처</Label>
              <Input
                value={quote.clientName || "-"}
                disabled
                className="bg-gray-50 text-black font-medium"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
            <div>
              <Label>담당자</Label>
              <Input
                value={quote.manager || "-"}
                disabled
                className="bg-gray-50 text-black font-medium"
              />
            </div>
            <div>
              <Label>연락처</Label>
              <Input
                value={quote.contact || "-"}
                disabled
                className="bg-gray-50 text-black font-medium"
              />
            </div>
            <div>
              <Label>현장명</Label>
              <Input
                value={quote.siteName || "-"}
                disabled
                className="bg-gray-50 text-black font-medium"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
            <div>
              <Label>등록일</Label>
              <Input
                value={formatDate(quote.registrationDate || "")}
                disabled
                className="bg-gray-50 text-black font-medium"
              />
            </div>
            <div>
              <Label>납기일</Label>
              <Input
                value={formatDate(quote.dueDate || "")}
                disabled
                className="bg-gray-50 text-black font-medium"
              />
            </div>
          </div>

          {quote.remarks && (
            <div>
              <Label>비고</Label>
              <Textarea
                value={quote.remarks}
                disabled
                className="bg-gray-50 text-black font-medium min-h-[80px]"
              />
            </div>
          )}
        </CardContent>
      </Card>

      {/* 자동 견적 산출 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>자동 견적 산출 정보</CardTitle>
        </CardHeader>
        <CardContent>
          {quote.items && quote.items.length > 0 ? (
            <div className="space-y-4">
              {quote.items.map((item, index) => (
                <div
                  key={item.id}
                  className="border rounded-lg p-4 bg-gray-50"
                >
                  <div className="flex items-center justify-between mb-3">
                    <Badge variant="outline">항목 {index + 1}</Badge>
                    <Badge variant="secondary">{item.floor}</Badge>
                  </div>

                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                    <div>
                      <span className="text-gray-500">제품명</span>
                      <p className="font-medium">{item.productName}</p>
                    </div>
                    <div>
                      <span className="text-gray-500">오픈사이즈</span>
                      <p className="font-medium">
                        {item.openWidth} × {item.openHeight} mm
                      </p>
                    </div>
                    <div>
                      <span className="text-gray-500">수량</span>
                      <p className="font-medium">{item.quantity} SET</p>
                    </div>
                    <div>
                      <span className="text-gray-500">금액</span>
                      <p className="font-medium text-blue-600">
                        ₩{formatAmount(item.totalAmount || (item.unitPrice || 0) * (item.quantity || 1) || (item.inspectionFee || 0) * (item.quantity || 1))}
                      </p>
                    </div>
                  </div>
                </div>
              ))}

              {/* 합계 */}
              <div className="border-t pt-4 mt-4">
                <div className="flex justify-between items-center text-lg font-bold">
                  <span>총 견적금액</span>
                  <span className="text-blue-600">
                    ₩{formatAmount(totalAmount)}
                  </span>
                </div>
              </div>
            </div>
          ) : (
            <p className="text-gray-500 text-center py-8">
              산출 항목이 없습니다.
            </p>
          )}
        </CardContent>
      </Card>

      {/* BOM 자재 상세 */}
      {quote.bomMaterials && quote.bomMaterials.length > 0 && (
        <Card>
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between">
              <CardTitle className="text-lg flex items-center gap-2">
                <Package className="h-5 w-5" />
                BOM 자재 상세
                <Badge variant="secondary" className="ml-2">
                  {quote.bomMaterials.length}개 품목
                </Badge>
              </CardTitle>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setIsBomExpanded(!isBomExpanded)}
              >
                {isBomExpanded ? (
                  <ChevronUp className="h-4 w-4" />
                ) : (
                  <ChevronDown className="h-4 w-4" />
                )}
              </Button>
            </div>
          </CardHeader>
          {isBomExpanded && (
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b bg-muted/50">
                      <th className="text-left p-2 font-medium">No</th>
                      <th className="text-left p-2 font-medium">품목코드</th>
                      <th className="text-left p-2 font-medium">품목명</th>
                      <th className="text-left p-2 font-medium">유형</th>
                      <th className="text-left p-2 font-medium">규격</th>
                      <th className="text-center p-2 font-medium">단위</th>
                      <th className="text-right p-2 font-medium">수량</th>
                      <th className="text-right p-2 font-medium">단가</th>
                      <th className="text-right p-2 font-medium">금액</th>
                    </tr>
                  </thead>
                  <tbody>
                    {quote.bomMaterials.map((material, index) => (
                      <tr key={index} className="border-b hover:bg-muted/30">
                        <td className="p-2 text-muted-foreground">{index + 1}</td>
                        <td className="p-2 font-mono text-xs">{material.itemCode}</td>
                        <td className="p-2">{material.itemName}</td>
                        <td className="p-2">
                          <Badge variant="outline" className="text-xs">
                            {getItemTypeLabel(material.itemType)}
                          </Badge>
                        </td>
                        <td className="p-2 text-muted-foreground">{material.specification || '-'}</td>
                        <td className="p-2 text-center">{material.unit}</td>
                        <td className="p-2 text-right">{material.quantity.toLocaleString()}</td>
                        <td className="p-2 text-right">₩{material.unitPrice.toLocaleString()}</td>
                        <td className="p-2 text-right font-medium">₩{material.totalPrice.toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                  <tfoot>
                    <tr className="border-t-2 bg-muted/30">
                      <td colSpan={8} className="p-2 text-right font-medium">합계</td>
                      <td className="p-2 text-right font-bold text-blue-600">
                        ₩{quote.bomMaterials.reduce((sum, m) => sum + m.totalPrice, 0).toLocaleString()}
                      </td>
                    </tr>
                  </tfoot>
                </table>
              </div>
            </CardContent>
          )}
        </Card>
      )}

      {/* 견적서 다이얼로그 */}
      <DocumentViewer
        title="견적서"
        preset="quote"
        open={isQuoteDocumentOpen}
        onOpenChange={setIsQuoteDocumentOpen}
        onPdf={() => {
          toast.info('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하세요.');
          window.print();
        }}
        onEmail={handleSendEmail}
        onFax={() => toast.info("팩스 전송 기능은 준비 중입니다.")}
        onKakao={handleSendKakao}
      >
        <QuoteDocument quote={quote} companyInfo={companyInfo} />
      </DocumentViewer>

      {/* 산출내역서 다이얼로그 */}
      <DocumentViewer
        title="산출내역서"
        preset="quote"
        open={isCalculationReportOpen}
        onOpenChange={setIsCalculationReportOpen}
        onPdf={() => {
          toast.info('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하세요.');
          window.print();
        }}
        onEmail={handleSendEmail}
        onFax={() => toast.info("팩스 전송 기능은 준비 중입니다.")}
        onKakao={handleSendKakao}
        toolbarExtra={
          <>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={showDetailedBreakdown}
                onChange={(e) => setShowDetailedBreakdown(e.target.checked)}
                className="w-4 h-4 rounded border-gray-300"
              />
              <span className="text-sm">산출내역서</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={showMaterialList}
                onChange={(e) => setShowMaterialList(e.target.checked)}
                className="w-4 h-4 rounded border-gray-300"
              />
              <span className="text-sm">소요자재 내역</span>
            </label>
          </>
        }
      >
        <QuoteCalculationReport
          quote={quote}
          companyInfo={companyInfo}
          documentType="견적산출내역서"
          showDetailedBreakdown={showDetailedBreakdown}
          showMaterialList={showMaterialList}
        />
      </DocumentViewer>

      {/* 발주서 다이얼로그 */}
      <DocumentViewer
        title="발주서"
        preset="quote"
        open={isPurchaseOrderOpen}
        onOpenChange={setIsPurchaseOrderOpen}
        onPdf={() => {
          toast.info('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하세요.');
          window.print();
        }}
        onEmail={handleSendEmail}
        onFax={() => toast.info("팩스 전송 기능은 준비 중입니다.")}
        onKakao={handleSendKakao}
      >
        <PurchaseOrderDocument quote={quote} companyInfo={companyInfo} />
      </DocumentViewer>
    </div>
  );
}
