/**
 * 견적 상세 페이지
 * - 기본 정보 표시
 * - 자동 견적 산출 정보
 * - 견적서 / 산출내역서 / 발주서 모달
 */

"use client";

import { useRouter, useParams } from "next/navigation";
import { useState, useEffect } from "react";
import { QuoteFormData, INITIAL_QUOTE_FORM } from "@/components/quotes/QuoteRegistration";
import { QuoteDocument } from "@/components/quotes/QuoteDocument";
import { QuoteCalculationReport } from "@/components/quotes/QuoteCalculationReport";
import { PurchaseOrderDocument } from "@/components/quotes/PurchaseOrderDocument";
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 {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  FileText,
  Edit,
  List,
  Printer,
  FileOutput,
  Download,
  Mail,
  MessageCircle,
  X,
  FileCheck,
  ShoppingCart,
} from "lucide-react";
import { ContentLoadingSpinner } from "@/components/ui/loading-spinner";

// 샘플 견적 데이터 (TODO: API에서 가져오기)
const SAMPLE_QUOTE: QuoteFormData = {
  id: "Q2024-001",
  registrationDate: "2025-10-29",
  writer: "드미트리",
  clientId: "client-1",
  clientName: "인천건설",
  siteName: "송도 오피스텔 A동",
  manager: "김영업",
  contact: "010-1234-5678",
  dueDate: "2025-11-30",
  remarks: "스크린 셔터 부품구성표 기반 자동 견적",
  items: [
    {
      id: "item-1",
      floor: "1층",
      code: "A",
      productCategory: "screen",
      productName: "스크린 셔터 (표준형)",
      openWidth: "2000",
      openHeight: "2500",
      guideRailType: "wall",
      motorPower: "single",
      controller: "basic",
      quantity: 1,
      wingSize: "50",
      inspectionFee: 337000,
    },
  ],
};

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

  const [quote, setQuote] = useState<QuoteFormData | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 다이얼로그 상태
  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);

  useEffect(() => {
    // TODO: API에서 견적 데이터 가져오기
    const fetchQuote = async () => {
      setIsLoading(true);
      try {
        // 임시: 샘플 데이터 사용
        await new Promise((resolve) => setTimeout(resolve, 300));
        setQuote({ ...SAMPLE_QUOTE, id: quoteId });
      } catch (error) {
        toast.error("견적 정보를 불러오는데 실패했습니다.");
        router.push("/sales/quote-management");
      } finally {
        setIsLoading(false);
      }
    };

    fetchQuote();
  }, [quoteId, router]);

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

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

  const handleFinalize = () => {
    toast.success("견적이 최종 확정되었습니다. (API 연동 필요)");
  };

  const handleConvertToOrder = () => {
    toast.info("수주 등록 화면으로 이동합니다. (API 연동 필요)");
  };

  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) => {
      return sum + (item.inspectionFee || 0) * (item.quantity || 1);
    }, 0) || 0;

  if (isLoading) {
    return <ContentLoadingSpinner text="견적 정보를 불러오는 중..." />;
  }

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

  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}
            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.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>

      {/* 견적서 다이얼로그 */}
      <Dialog open={isQuoteDocumentOpen} onOpenChange={setIsQuoteDocumentOpen}>
        <DialogContent className="max-w-[95vw] md:max-w-[800px] lg:max-w-[900px] h-[95vh] flex flex-col p-0">
          <DialogHeader className="flex-shrink-0 px-6 py-4 border-b">
            <DialogTitle>견적서</DialogTitle>
          </DialogHeader>

          {/* 버튼 영역 */}
          <div className="flex-shrink-0 px-6 py-3 border-b bg-muted/30 flex flex-wrap gap-2 justify-between items-center">
            <div className="flex gap-2 flex-wrap">
              <Button
                size="sm"
                variant="default"
                className="bg-red-600 hover:bg-red-700"
                onClick={() => {
                  toast.info('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하세요.');
                  window.print();
                }}
              >
                <Download className="w-4 h-4 mr-2" />
                PDF
              </Button>
              <Button
                size="sm"
                variant="default"
                className="bg-blue-600 hover:bg-blue-700"
                onClick={() => toast.info("이메일 전송 기능은 API 연동이 필요합니다.")}
              >
                <Mail className="w-4 h-4 mr-2" />
                이메일
              </Button>
              <Button
                size="sm"
                variant="default"
                className="bg-purple-600 hover:bg-purple-700"
                onClick={() => toast.info("팩스 전송 기능은 API 연동이 필요합니다.")}
              >
                <FileOutput className="w-4 h-4 mr-2" />
                팩스
              </Button>
              <Button
                size="sm"
                variant="default"
                className="bg-yellow-500 hover:bg-yellow-600"
                onClick={() => toast.info("카카오톡 전송 기능은 API 연동이 필요합니다.")}
              >
                <MessageCircle className="w-4 h-4 mr-2" />
                카카오톡
              </Button>
              <Button size="sm" variant="outline" onClick={() => window.print()}>
                <Printer className="w-4 h-4 mr-2" />
                인쇄
              </Button>
            </div>
            <Button
              size="sm"
              variant="outline"
              onClick={() => setIsQuoteDocumentOpen(false)}
            >
              <X className="w-4 h-4 mr-2" />
              닫기
            </Button>
          </div>

          {/* 문서 영역 */}
          <div className="flex-1 overflow-y-auto bg-gray-100 p-4">
            <div className="max-w-[210mm] mx-auto bg-white shadow-lg rounded-lg p-8">
              <QuoteDocument quote={quote} />
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 산출내역서 다이얼로그 */}
      <Dialog
        open={isCalculationReportOpen}
        onOpenChange={setIsCalculationReportOpen}
      >
        <DialogContent className="max-w-[95vw] md:max-w-[800px] lg:max-w-[900px] h-[95vh] flex flex-col p-0 overflow-hidden">
          <DialogHeader className="flex-shrink-0 px-6 py-4 border-b">
            <DialogTitle>산출내역서</DialogTitle>
          </DialogHeader>

          {/* 버튼 영역 */}
          <div className="flex-shrink-0 px-6 py-3 border-b bg-muted/30 flex flex-wrap gap-2 justify-between items-center">
            <div className="flex gap-4 flex-wrap items-center">
              <div className="flex gap-2 flex-wrap">
                <Button
                  size="sm"
                  variant="default"
                  className="bg-red-600 hover:bg-red-700"
                  onClick={() => {
                    toast.info('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하세요.');
                    window.print();
                  }}
                >
                  <Download className="w-4 h-4 mr-2" />
                  PDF
                </Button>
                <Button
                  size="sm"
                  variant="default"
                  className="bg-blue-600 hover:bg-blue-700"
                  onClick={() => toast.info("이메일 전송 기능은 API 연동이 필요합니다.")}
                >
                  <Mail className="w-4 h-4 mr-2" />
                  이메일
                </Button>
                <Button
                  size="sm"
                  variant="default"
                  className="bg-purple-600 hover:bg-purple-700"
                  onClick={() => toast.info("팩스 전송 기능은 API 연동이 필요합니다.")}
                >
                  <FileOutput className="w-4 h-4 mr-2" />
                  팩스
                </Button>
                <Button
                  size="sm"
                  variant="default"
                  className="bg-yellow-500 hover:bg-yellow-600"
                  onClick={() => toast.info("카카오톡 전송 기능은 API 연동이 필요합니다.")}
                >
                  <MessageCircle className="w-4 h-4 mr-2" />
                  카카오톡
                </Button>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => window.print()}
                >
                  <Printer className="w-4 h-4 mr-2" />
                  인쇄
                </Button>
              </div>

              {/* 표시 옵션 체크박스 */}
              <div className="flex gap-4 pl-4 border-l">
                <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>
              </div>
            </div>

            <Button
              size="sm"
              variant="outline"
              onClick={() => setIsCalculationReportOpen(false)}
            >
              <X className="w-4 h-4 mr-2" />
              닫기
            </Button>
          </div>

          {/* 문서 영역 */}
          <div className="flex-1 overflow-y-auto bg-gray-100 p-4">
            <div className="max-w-[210mm] mx-auto bg-white shadow-lg rounded-lg p-8">
              <QuoteCalculationReport
                quote={quote}
                documentType="견적산출내역서"
                showDetailedBreakdown={showDetailedBreakdown}
                showMaterialList={showMaterialList}
              />
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 발주서 다이얼로그 */}
      <Dialog open={isPurchaseOrderOpen} onOpenChange={setIsPurchaseOrderOpen}>
        <DialogContent className="max-w-[95vw] md:max-w-[800px] lg:max-w-[900px] h-[95vh] flex flex-col p-0 overflow-hidden">
          <DialogHeader className="flex-shrink-0 px-6 py-4 border-b">
            <DialogTitle>발주서</DialogTitle>
          </DialogHeader>

          {/* 버튼 영역 */}
          <div className="flex-shrink-0 px-6 py-3 border-b bg-muted/30 flex flex-wrap gap-2 justify-between items-center">
            <div className="flex gap-2 flex-wrap">
              <Button
                size="sm"
                variant="default"
                className="bg-red-600 hover:bg-red-700"
                onClick={() => {
                  toast.info('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하세요.');
                  window.print();
                }}
              >
                <Download className="w-4 h-4 mr-2" />
                PDF
              </Button>
              <Button
                size="sm"
                variant="default"
                className="bg-blue-600 hover:bg-blue-700"
                onClick={() => toast.info("이메일 전송 기능은 API 연동이 필요합니다.")}
              >
                <Mail className="w-4 h-4 mr-2" />
                이메일
              </Button>
              <Button
                size="sm"
                variant="default"
                className="bg-purple-600 hover:bg-purple-700"
                onClick={() => toast.info("팩스 전송 기능은 API 연동이 필요합니다.")}
              >
                <FileOutput className="w-4 h-4 mr-2" />
                팩스
              </Button>
              <Button
                size="sm"
                variant="default"
                className="bg-yellow-500 hover:bg-yellow-600"
                onClick={() => toast.info("카카오톡 전송 기능은 API 연동이 필요합니다.")}
              >
                <MessageCircle className="w-4 h-4 mr-2" />
                카카오톡
              </Button>
              <Button size="sm" variant="outline" onClick={() => window.print()}>
                <Printer className="w-4 h-4 mr-2" />
                인쇄
              </Button>
            </div>
            <Button
              size="sm"
              variant="outline"
              onClick={() => setIsPurchaseOrderOpen(false)}
            >
              <X className="w-4 h-4 mr-2" />
              닫기
            </Button>
          </div>

          {/* 문서 영역 */}
          <div className="flex-1 overflow-y-auto bg-gray-100 p-4">
            <div className="max-w-[210mm] mx-auto bg-white shadow-lg rounded-lg p-8">
              <PurchaseOrderDocument quote={quote} />
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}