import { useState } from "react";
import { useData } from "./contexts/DataContext";
import type { Quote, QuoteRevision } from "./contexts/DataContext";
import { toast } from "sonner@2.0.3";
import { QuoteCalculationReport } from "./QuoteCalculationReport";
import { PurchaseOrderDocument } from "./PurchaseOrderDocument";
import { Button } from "./ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Badge } from "./ui/badge";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "./ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { DetailViewActions } from "./organisms/DetailViewActions";
import { StandardDialog } from "./molecules/StandardDialog";
import { 
  ArrowLeft, 
  FileText, 
  Edit, 
  Download, 
  Send, 
  CheckCircle, 
  Trash2, 
  History, 
  Calculator,
  Mail,
  Phone,
  Package,
  Building2,
  Calendar,
  User,
  MapPin,
  Printer,
  X,
  FileOutput,
  MessageCircle
} from "lucide-react";

interface QuoteDetailViewProps {
  quoteId: string;
  onBack: () => void;
  onEdit: () => void;
  onCreateOrder?: (quoteId: string) => void;
}

export function QuoteDetailView({ quoteId, onBack, onEdit, onCreateOrder }: QuoteDetailViewProps) {
  const { quotes, finalizeQuote, deleteQuote, updateQuote } = useData();
  const quote = quotes.find(q => q.id === quoteId);

  const [isRevisionHistoryOpen, setIsRevisionHistoryOpen] = useState(false);
  const [isFinalizeDialogOpen, setIsFinalizeDialogOpen] = useState(false);
  const [finalizeReason, setFinalizeReason] = useState("");
  const [isCalculationReportOpen, setIsCalculationReportOpen] = useState(false);
  const [isQuoteDocumentOpen, setIsQuoteDocumentOpen] = useState(false);
  const [isPurchaseOrderOpen, setIsPurchaseOrderOpen] = useState(false);
  const [selectedRevision, setSelectedRevision] = useState<string>("current");

  if (!quote) {
    return (
      <PageLayout>
        <PageHeader
          title="견적 상세"
          description="견적 정보를 찾을 수 없습니다"
          icon={FileText}
        />
        <div className="text-center py-12">
          <p className="text-muted-foreground mb-4">요청하신 견적을 찾을 수 없습니다</p>
          <Button onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            목록으로 돌아가기
          </Button>
        </div>
      </PageLayout>
    );
  }

  // 선택된 버전의 데이터 가져오기
  const getDisplayData = () => {
    if (selectedRevision === "current") {
      return quote;
    }
    
    const revisionNumber = parseInt(selectedRevision);
    const revision = quote?.revisions?.find(r => r.revisionNumber === revisionNumber);
    
    if (revision) {
      return {
        ...quote,
        ...revision.previousData,
        isHistoricalView: true,
        viewingRevision: revisionNumber
      };
    }
    
    return quote;
  };

  const displayData = getDisplayData();

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

  const getStatusBadge = () => {
    if (quote.isFinal) {
      return <Badge variant="default" className="bg-green-600"><CheckCircle className="w-3 h-3 mr-1" />최종확정</Badge>;
    }
    switch (quote.status) {
      case 'draft':
        return <Badge variant="outline">초안</Badge>;
      case 'sent':
        return <Badge variant="secondary">발송됨</Badge>;
      case 'approved':
        return <Badge variant="default" className="bg-blue-600">승인됨</Badge>;
      case 'rejected':
        return <Badge variant="destructive">거부됨</Badge>;
      case 'converted':
        return <Badge variant="default" className="bg-purple-600">수주전환</Badge>;
      default:
        return <Badge variant="outline">-</Badge>;
    }
  };

  const getRevisionBadge = () => {
    if ((quote.currentRevision || 0) > 0) {
      return (
        <Badge variant="secondary" className="bg-orange-100 text-orange-700 border-orange-300">
          <History className="w-3 h-3 mr-1" />
          {quote.currentRevision}차 수정
        </Badge>
      );
    }
    return <Badge variant="outline" className="bg-gray-50">최초 작성</Badge>;
  };

  const handleFinalize = () => {
    if (quote.isFinal) {
      toast.warning("이미 최종 확정된 견적입니다");
      return;
    }

    setIsFinalizeDialogOpen(true);
  };

  const confirmFinalize = () => {
    finalizeQuote(quote.id, finalizeReason);
    setIsFinalizeDialogOpen(false);
    setFinalizeReason("");
    toast.success("견적이 최종 확정되었습니다");
  };

  const handleCreateSalesOrder = () => {
    if (onCreateOrder) {
      onCreateOrder(quote.id);
    }
  };

  // 총 금액 계산
  const totalAmount = displayData?.amount || 0;
  const supplyAmount = Math.round(totalAmount / 1.1);
  const taxAmount = totalAmount - supplyAmount;

  return (
    <PageLayout>
      <PageHeader
        title="견적 상세"
        description={quote.quoteNumber}
        icon={FileText}
        leftActions={
          <div className="flex gap-2 flex-wrap">
            <DetailViewActions
              onBackClick={onBack}
              onEditClick={onEdit}
              backLabel="목록"
              additionalActions={
                <>
                  {(quote.currentRevision || 0) > 0 && (
                    <Button variant="outline" onClick={() => setIsRevisionHistoryOpen(true)}>
                      <History className="w-4 h-4 mr-2" />
                      수정 이력
                    </Button>
                  )}
                  {!quote.isFinal && (
                    <Button 
                      className="bg-lime-600 hover:bg-lime-700 text-white"
                      onClick={handleFinalize}
                    >
                      <CheckCircle className="w-4 h-4 mr-2" />
                      최종 확정
                    </Button>
                  )}
                  {quote.isFinal && quote.status !== 'converted' && (
                    <Button 
                      className="bg-[#10B981] hover:bg-[#059669]"
                      onClick={handleCreateSalesOrder}
                    >
                      <FileText className="w-4 h-4 mr-2" />
                      수주 등록
                    </Button>
                  )}
                  {quote.status === 'converted' && (
                    <Button variant="outline" disabled>
                      <CheckCircle className="w-4 h-4 mr-2" />
                      수주 전환됨
                    </Button>
                  )}
                </>
              }
            />
          </div>
        }
      />

      <div className="space-y-6">
        {/* 수정 이력 선택 */}
        {quote.revisions && quote.revisions.length > 0 && (
          <Card className="border-orange-200 bg-orange-50">
            <CardHeader>
              <CardTitle className="text-orange-700">수정 이력 조회</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-4">
                <Label>버전 선택</Label>
                <Select value={selectedRevision} onValueChange={setSelectedRevision}>
                  <SelectTrigger className="w-[300px] bg-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="current">
                      <div className="flex items-center gap-2">
                        <CheckCircle className="w-4 h-4 text-green-600" />
                        현재 버전 (V{quote.currentRevision || 0})
                      </div>
                    </SelectItem>
                    {quote.revisions.map((revision) => (
                      <SelectItem key={revision.revisionNumber} value={String(revision.revisionNumber)}>
                        <div className="flex flex-col">
                          <span>V{revision.revisionNumber - 1} → V{revision.revisionNumber}</span>
                          <span className="text-xs text-muted-foreground">- {revision.revisionDate}</span>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {selectedRevision !== "current" && (
                  <Badge variant="outline" className="bg-orange-100 text-orange-700 border-orange-300">
                    <History className="w-3 h-3 mr-1" />
                    과거 버전 조회 중
                  </Badge>
                )}
              </div>
              {selectedRevision !== "current" && (
                <div className="mt-3 text-sm text-orange-700 bg-orange-100 p-2 rounded">
                  ℹ️ 과거 버전을 조회하고 있습니다. 현재 버전으로 돌아가려면 드롭다운에서 "현재 버전"을 선택하세요.
                </div>
              )}
            </CardContent>
          </Card>
        )}

        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span>기본 정보</span>
              <div className="flex gap-2">
                {getStatusBadge()}
                {getRevisionBadge()}
              </div>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              <div>
                <Label className="text-muted-foreground">
                  견적번호
                </Label>
                <p className="mt-1 font-semibold text-blue-600">{displayData?.quoteNumber || '-'}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">
                  등록일
                </Label>
                <p className="mt-1 font-medium">{displayData?.registrationDate || '-'}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">
                  작성자
                </Label>
                <p className="mt-1 font-medium">{displayData?.author || '-'}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">
                  발주처
                </Label>
                <p className="mt-1 font-semibold">{displayData?.client || '-'}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">
                  현장명
                </Label>
                <p className="mt-1 font-medium">{displayData?.site || '-'}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">현장 코드</Label>
                <p className="mt-1 font-medium font-mono text-sm">{displayData?.siteCode || '-'}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">
                  발주 담당자
                </Label>
                <p className="mt-1 font-medium">{displayData?.manager || '-'}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">
                  연락처
                </Label>
                <p className="mt-1 font-medium">{displayData?.contact || '-'}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">
                  납기일
                </Label>
                <p className="mt-1 font-medium">{displayData?.completionDate || '-'}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">층수</Label>
                <p className="mt-1 font-medium">{displayData?.floors || '-'}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">부호</Label>
                <p className="mt-1 font-medium">{displayData?.code || '-'}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">수정 차수</Label>
                <p className="mt-1 font-medium">
                  {selectedRevision !== "current" ? (
                    <span className="text-orange-600">V{selectedRevision} (이전 버전)</span>
                  ) : (quote.currentRevision || 0) > 0 ? (
                    <span className="text-orange-600">{quote.currentRevision}차 수정</span>
                  ) : (
                    <span className="text-gray-600">최초 작성</span>
                  )}
                </p>
              </div>
              {quote.isFinal && (
                <>
                  <div>
                    <Label className="text-muted-foreground">최종 확정일</Label>
                    <p className="mt-1 font-medium">{quote.finalizedDate || '-'}</p>
                  </div>
                  <div>
                    <Label className="text-muted-foreground">확정자</Label>
                    <p className="mt-1 font-medium">{quote.finalizedBy || '-'}</p>
                  </div>
                </>
              )}
            </div>

            {/* 비고 - 데이터가 있을 때만 표시 */}
            {(displayData?.memo || displayData?.notes || displayData?.remarks) && (
              <div className="mt-6 pt-6 border-t">
                <Label className="text-muted-foreground">비고</Label>
                <div className="mt-2">
                  {(() => {
                    // memo, notes, remarks 중 첫 번째로 값이 있는 것 사용
                    const remarkText = displayData?.memo || displayData?.notes || displayData?.remarks || displayData?.commitment;
                    
                    if (!remarkText) {
                      return (
                        <p className="text-sm text-muted-foreground">비고 사항 없음</p>
                      );
                    }
                    
                    return (
                      <div className="p-4 bg-muted rounded-md whitespace-pre-wrap text-[16px]">
                        {remarkText}
                      </div>
                    );
                  })()}
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 제품 정보 및 자동 산출 내역 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              자동 산출 내역
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-6">
              {/* 자동 산출 결과 */}
              {(displayData?.openSizeWidth || displayData?.openSizeHeight) ? (
                <>
                  {/* 기본 산출 결과 */}
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-blue-50 px-4 py-2 border-b border-blue-100">
                      <h5 className="text-sm font-semibold text-blue-900">자동 산출 결과 (산정 기준 적용)</h5>
                    </div>
                    <div className="bg-white">
                      <table className="w-full text-sm">
                        <thead>
                          <tr className="border-b bg-muted">
                            <th className="px-4 py-2 text-left font-medium">항목</th>
                            <th className="px-4 py-2 text-right font-medium">값</th>
                            <th className="px-4 py-2 text-left font-medium">산출식</th>
                          </tr>
                        </thead>
                        <tbody>
                          {(() => {
                            const w0 = parseFloat(displayData?.openSizeWidth || '0');
                            const h0 = parseFloat(displayData?.openSizeHeight || '0');
                            const isScreen = displayData?.type?.includes('스크린') || displayData?.productCategory === 'SCREEN';
                            
                            // 제작폭 W1 계산
                            const w1Margin = isScreen ? 140 : 110;
                            const w1 = w0 + w1Margin;
                            
                            // 제작높이 H1 계산
                            const h1 = h0 + 350;
                            
                            // 면적 계산
                            const area = (w1 * h1) / 1000000;
                            
                            // 중량 계산 (간단한 추정)
                            const weight = area * 12; // 대략적인 중량 계수
                            
                            return (
                              <>
                                <tr className="border-b hover:bg-muted/50">
                                  <td className="px-4 py-2">제작폭 (W1)</td>
                                  <td className="px-4 py-2 text-right font-semibold">{w1.toFixed(0)} mm</td>
                                  <td className="px-4 py-2 text-muted-foreground text-xs">
                                    W0 + {w1Margin} = {w0} + {w1Margin} = {w1.toFixed(0)}
                                  </td>
                                </tr>
                                <tr className="border-b hover:bg-muted/50">
                                  <td className="px-4 py-2">제작높이 (H1)</td>
                                  <td className="px-4 py-2 text-right font-semibold">{h1.toFixed(0)} mm</td>
                                  <td className="px-4 py-2 text-muted-foreground text-xs">
                                    H0 + 350 = {h0} + 350 = {h1.toFixed(0)}
                                  </td>
                                </tr>
                                <tr className="border-b hover:bg-muted/50">
                                  <td className="px-4 py-2">면적 (M)</td>
                                  <td className="px-4 py-2 text-right font-semibold">{area.toFixed(3)} m²</td>
                                  <td className="px-4 py-2 text-muted-foreground text-xs">
                                    W1 × H1 ÷ 1,000,000 = {w1.toFixed(0)} × {h1.toFixed(0)} ÷ 1,000,000 = {area.toFixed(3)}
                                  </td>
                                </tr>
                                <tr className="hover:bg-muted/50">
                                  <td className="px-4 py-2">중량 (K)</td>
                                  <td className="px-4 py-2 text-right font-semibold">{weight.toFixed(2)} kg</td>
                                  <td className="px-4 py-2 text-muted-foreground text-xs">
                                    면적 × 중량계수 = {area.toFixed(3)} × 12 = {weight.toFixed(2)}
                                  </td>
                                </tr>
                              </>
                            );
                          })()}
                        </tbody>
                      </table>
                    </div>
                  </div>

                  {/* 산출 입력값 */}
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-muted px-4 py-2 border-b">
                      <h5 className="text-sm font-semibold">산출 입력값</h5>
                    </div>
                    <div className="bg-white p-4">
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div className="p-3 bg-muted rounded border">
                          <div className="text-xs text-muted-foreground mb-1">오픈사이즈 폭 (W0)</div>
                          <div className="font-semibold">{displayData?.openSizeWidth || 0} mm</div>
                        </div>
                        <div className="p-3 bg-muted rounded border">
                          <div className="text-xs text-muted-foreground mb-1">오픈사이즈 높이 (H0)</div>
                          <div className="font-semibold">{displayData?.openSizeHeight || 0} mm</div>
                        </div>
                        <div className="p-3 bg-muted rounded border">
                          <div className="text-xs text-muted-foreground mb-1">제품 유형</div>
                          <div className="font-semibold">{displayData?.type || '-'}</div>
                        </div>
                        <div className="p-3 bg-muted rounded border">
                          <div className="text-xs text-muted-foreground mb-1">제품 코드</div>
                          <div className="font-semibold font-mono text-sm">{displayData?.productCode || '-'}</div>
                        </div>
                        <div className="p-3 bg-muted rounded border">
                          <div className="text-xs text-muted-foreground mb-1">제품명</div>
                          <div className="font-semibold">{displayData?.modelSelection || '-'}</div>
                        </div>
                        <div className="p-3 bg-muted rounded border">
                          <div className="text-xs text-muted-foreground mb-1">수량</div>
                          <div className="font-semibold">{displayData?.quantity || 0} EA</div>
                        </div>
                        {displayData?.floors && (
                          <div className="p-3 bg-muted rounded border">
                            <div className="text-xs text-muted-foreground mb-1">층수</div>
                            <div className="font-semibold">{displayData.floors}</div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* BOM 품목 및 단가 정보 - 항상 표시 */}
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-blue-50 px-4 py-2 border-b border-blue-100 flex items-center justify-between">
                      <h5 className="text-sm font-semibold text-blue-900">BOM 기준 품목 및 단가 상세 내역</h5>
                      {displayData?.bomCalculations && displayData.bomCalculations.length > 0 && (
                        <span className="text-xs text-blue-700 bg-blue-100 px-2 py-1 rounded">
                          총 {displayData.bomCalculations.length}개 품목
                        </span>
                      )}
                    </div>
                    <div className="bg-white overflow-x-auto">
                      {displayData?.bomCalculations && displayData.bomCalculations.length > 0 ? (
                        <table className="w-full text-sm">
                          <thead>
                            <tr className="border-b bg-muted">
                              <th className="px-3 py-2 text-center font-medium whitespace-nowrap">No.</th>
                              <th className="px-3 py-2 text-left font-medium whitespace-nowrap">품목명</th>
                              <th className="px-3 py-2 text-left font-medium whitespace-nowrap">산식</th>
                              <th className="px-3 py-2 text-right font-medium whitespace-nowrap">계산 수량</th>
                              <th className="px-3 py-2 text-center font-medium whitespace-nowrap">단위</th>
                              <th className="px-3 py-2 text-right font-medium whitespace-nowrap">단가</th>
                              <th className="px-3 py-2 text-right font-medium whitespace-nowrap">금액</th>
                            </tr>
                          </thead>
                          <tbody>
                            {displayData.bomCalculations.map((bom, index) => {
                              const qty = Number(bom.calculatedQuantity) || 0;
                              const displayQty = (bom.unit === 'EA' || bom.unit === 'SET') ? Math.ceil(qty) : qty.toFixed(2);
                              
                              return (
                                <tr key={bom.id || `bom-${index}`} className="border-b hover:bg-muted/50">
                                  <td className="px-3 py-2 text-center text-muted-foreground">{index + 1}</td>
                                  <td className="px-3 py-2 font-medium">{bom.itemName}</td>
                                  <td className="px-3 py-2 text-xs text-muted-foreground font-mono">{bom.formula || bom.note || '-'}</td>
                                  <td className="px-3 py-2 text-right font-semibold">{displayQty}</td>
                                  <td className="px-3 py-2 text-center text-muted-foreground">{bom.unit || 'SET'}</td>
                                  <td className="px-3 py-2 text-right font-medium">₩{bom.unitPrice?.toLocaleString() || 0}</td>
                                  <td className="px-3 py-2 text-right font-semibold">₩{bom.totalPrice?.toLocaleString() || 0}</td>
                                </tr>
                              );
                            })}
                          </tbody>
                          <tfoot>
                            <tr className="bg-muted border-t-2">
                              <td colSpan={6} className="px-3 py-3 text-right font-semibold">합계</td>
                              <td className="px-3 py-3 text-right font-bold text-base">
                                ₩{displayData.bomCalculations.reduce((sum, bom) => sum + (bom.totalPrice || 0), 0).toLocaleString()}
                              </td>
                            </tr>
                          </tfoot>
                        </table>
                      ) : (
                        <div className="text-center py-12 text-muted-foreground">
                          <Package className="w-12 h-12 mx-auto mb-3 opacity-50" />
                          <p className="font-medium">BOM 데이터가 없습니다.</p>
                          <p className="text-sm mt-1">견적 등록 시 자동 산출을 체크하면 BOM 기준으로 품목이 자동 계산됩니다.</p>
                        </div>
                      )}
                    </div>
                  </div>
                </>
              ) : (
                /* 자동 산출 결과가 없을 때 */
                <div className="text-center py-8 text-muted-foreground">
                  <Calculator className="w-12 h-12 mx-auto mb-3 opacity-50" />
                  <p>자동 산출 데이터가 없습니다.</p>
                  <p className="text-sm mt-1">오픈사이즈 정보를 입력하면 자동으로 산출됩니다.</p>
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 발송 이력 */}
        {quote.sendHistory && quote.sendHistory.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                견적서 발송 이력
                <Badge variant="secondary" className="ml-2">
                  {quote.sendHistory.length}건
                </Badge>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {[...quote.sendHistory].reverse().map((history, index) => {
                  const methodIcon = {
                    email: <Mail className="w-4 h-4 text-blue-600" />,
                    fax: <Phone className="w-4 h-4 text-gray-600" />,
                    kakao: <Send className="w-4 h-4 text-green-600" />,
                    download: <Download className="w-4 h-4 text-gray-600" />,
                    print: <FileText className="w-4 h-4 text-gray-600" />
                  };

                  const methodLabel = {
                    email: '이메일',
                    fax: '팩스',
                    kakao: '카카오톡',
                    download: '다운로드',
                    print: '출력'
                  };

                  return (
                    <div key={history.id} className="flex items-start gap-3 p-3 bg-muted rounded-lg">
                      <div className="mt-1">{methodIcon[history.sentMethod]}</div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <span className="font-semibold">{methodLabel[history.sentMethod]}</span>
                          <Badge variant={history.status === 'sent' ? 'default' : history.status === 'confirmed' ? 'default' : 'destructive'}>
                            {history.status === 'sent' ? '발송됨' : history.status === 'confirmed' ? '확인됨' : '실패'}
                          </Badge>
                        </div>
                        <div className="text-sm text-muted-foreground">
                          <div>받는 사: {history.sentTo}</div>
                          {history.recipientEmail && <div>이메일: {history.recipientEmail}</div>}
                          {history.recipientPhone && <div>연락처: {history.recipientPhone}</div>}
                          <div>발송일시: {history.sentDate}</div>
                          <div>발송자: {history.sentBy}</div>
                          {history.note && <div className="mt-1">메모: {history.note}</div>}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </CardContent>
          </Card>
        )}
      </div>

      {/* 최종 확정 다이얼로그 */}
      <StandardDialog
        open={isFinalizeDialogOpen}
        onOpenChange={setIsFinalizeDialogOpen}
        title="견적 최종 확정"
        description="견적을 최종 확정하시겠습니까? 확정 후에는 수정이 불가능합니다."
        footer={
          <>
            <Button variant="outline" onClick={() => setIsFinalizeDialogOpen(false)}>
              취소
            </Button>
            <Button onClick={confirmFinalize} className="bg-green-600 hover:bg-green-700">
              <CheckCircle className="w-4 h-4 mr-2" />
              최종 확정
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <div>
            <Label htmlFor="finalizeReason">확정 사유 (선택)</Label>
            <Textarea
              id="finalizeReason"
              value={finalizeReason}
              onChange={(e) => setFinalizeReason(e.target.value)}
              placeholder="확정 사유를 입력하세요 (선택사항)"
              rows={3}
            />
          </div>
        </div>
      </StandardDialog>

      {/* 견적서 다이얼로그 */}
      <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={() => {
                alert('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하여 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={() => {
                alert('이메일 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <Mail className="w-4 h-4 mr-2" />
                이메일
              </Button>
              <Button size="sm" variant="default" className="bg-purple-600 hover:bg-purple-700" onClick={() => {
                alert('팩스 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <FileOutput className="w-4 h-4 mr-2" />
                팩스
              </Button>
              <Button size="sm" variant="default" className="bg-yellow-500 hover:bg-yellow-600" onClick={() => {
                alert('카카오톡 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <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" style={{
            scrollbarWidth: 'thin',
            scrollbarColor: 'rgb(203 213 225) transparent'
          }}>
            <style dangerouslySetInnerHTML={{__html: `
              .flex-1.overflow-y-auto::-webkit-scrollbar {
                width: 8px;
              }
              .flex-1.overflow-y-auto::-webkit-scrollbar-track {
                background: transparent;
              }
              .flex-1.overflow-y-auto::-webkit-scrollbar-thumb {
                background-color: rgb(203 213 225);
                border-radius: 4px;
                transition: background-color 0.2s;
              }
              .flex-1.overflow-y-auto::-webkit-scrollbar-thumb:hover {
                background-color: rgb(148 163 184);
              }
              .flex-1.overflow-y-auto::-webkit-scrollbar-thumb:active {
                background-color: rgb(100 116 139);
              }
            `}} />
            <div className="max-w-[210mm] mx-auto bg-white shadow-lg rounded-lg p-8">
              <QuoteCalculationReport quote={displayData as any} documentType="견적서" />
            </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-2 flex-wrap">
              <Button size="sm" variant="default" className="bg-red-600 hover:bg-red-700" onClick={() => {
                alert('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하여 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={() => {
                alert('이메일 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <Mail className="w-4 h-4 mr-2" />
                이메일
              </Button>
              <Button size="sm" variant="default" className="bg-purple-600 hover:bg-purple-700" onClick={() => {
                alert('팩스 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <FileOutput className="w-4 h-4 mr-2" />
                팩스
              </Button>
              <Button size="sm" variant="default" className="bg-yellow-500 hover:bg-yellow-600" onClick={() => {
                alert('카카오톡 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <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={() => setIsCalculationReportOpen(false)}>
              <X className="w-4 h-4 mr-2" />
              닫기
            </Button>
          </div>
          
          {/* 스크롤 가능한 문서 영역 */}
          <div className="flex-1 overflow-hidden bg-gray-100">
            {/* A4 문서 영역 */}
            <div 
              className="h-full overflow-y-auto p-4"
              style={{
                scrollbarWidth: 'thin',
                scrollbarColor: 'rgb(203 213 225) transparent'
              }}
            >
              <style dangerouslySetInnerHTML={{__html: `
                .h-full.overflow-y-auto::-webkit-scrollbar {
                  width: 8px;
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-track {
                  background: transparent;
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-thumb {
                  background-color: rgb(203 213 225);
                  border-radius: 4px;
                  transition: background-color 0.2s;
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-thumb:hover {
                  background-color: rgb(148 163 184);
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-thumb:active {
                  background-color: rgb(100 116 139);
                }
              `}} />
              <div className="max-w-[210mm] mx-auto bg-white shadow-lg rounded-lg p-8">
                <QuoteCalculationReport quote={displayData as any} documentType="견적산출내역서" />
              </div>
            </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={() => {
                alert('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하여 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={() => {
                alert('이메일 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <Mail className="w-4 h-4 mr-2" />
                이메일
              </Button>
              <Button size="sm" variant="default" className="bg-purple-600 hover:bg-purple-700" onClick={() => {
                alert('팩스 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <FileOutput className="w-4 h-4 mr-2" />
                팩스
              </Button>
              <Button size="sm" variant="default" className="bg-yellow-500 hover:bg-yellow-600" onClick={() => {
                alert('카카오톡 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <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-hidden bg-gray-100">
            {/* A4 문서 영역 */}
            <div 
              className="h-full overflow-y-auto p-4"
              style={{
                scrollbarWidth: 'thin',
                scrollbarColor: 'rgb(203 213 225) transparent'
              }}
            >
              <style dangerouslySetInnerHTML={{__html: `
                .h-full.overflow-y-auto::-webkit-scrollbar {
                  width: 8px;
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-track {
                  background: transparent;
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-thumb {
                  background-color: rgb(203 213 225);
                  border-radius: 4px;
                  transition: background-color 0.2s;
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-thumb:hover {
                  background-color: rgb(148 163 184);
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-thumb:active {
                  background-color: rgb(100 116 139);
                }
              `}} />
              <div className="max-w-[210mm] mx-auto bg-white shadow-lg rounded-lg p-8">
                <PurchaseOrderDocument quote={displayData as any} />
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 수정 이력 다이얼로그 */}
      <StandardDialog
        open={isRevisionHistoryOpen}
        onOpenChange={setIsRevisionHistoryOpen}
        title="견적 수정 이력"
        description={`견적번호: ${quote.quoteNumber}`}
        size="lg"
      >
        <div className="space-y-4">
          {quote.revisions && quote.revisions.length > 0 ? (
            [...quote.revisions].reverse().map((revision) => (
              <Card key={revision.revisionNumber}>
                <CardHeader>
                  <CardTitle className="flex items-center justify-between text-base">
                    <span>
                      V{revision.revisionNumber - 1} → V{revision.revisionNumber}
                    </span>
                    <Badge variant="secondary">{revision.revisionNumber}차 수정</Badge>
                  </CardTitle>
                </CardHeader>
                <CardContent className="text-sm space-y-2">
                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <span className="text-muted-foreground">수정일:</span> {revision.revisionDate}
                    </div>
                    <div>
                      <span className="text-muted-foreground">수정자:</span> {revision.revisionBy}
                    </div>
                  </div>
                  {revision.revisionReason && (
                    <div>
                      <span className="text-muted-foreground">수정 사유:</span>
                      <div className="mt-1 p-2 bg-muted rounded">{revision.revisionReason}</div>
                    </div>
                  )}
                </CardContent>
              </Card>
            ))
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              수정 이력이 없습니다
            </div>
          )}
        </div>
      </StandardDialog>
    </PageLayout>
  );
}