import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { Badge } from "./ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";
import { 
  FileText,
  History,
  List,
  Edit,
  FileCheck,
  Printer,
  FileOutput,
  Download,
  Mail,
  MessageCircle,
  X,
  ShoppingCart
} from "lucide-react";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { QuoteData } from "./QuoteManagement3Write";
import { useData } from "./contexts/DataContext";
import { toast } from "sonner@2.0.3";
import { QuoteCalculationReport } from "./QuoteCalculationReport";
import { PurchaseOrderDocument } from "./PurchaseOrderDocument";

interface QuoteManagement3DetailProps {
  quote: QuoteData;
  onEdit?: () => void;
  onBack: () => void;
  onConvertToOrder?: (quote: QuoteData) => void;
}

export function QuoteManagement3Detail({ 
  quote, 
  onEdit,
  onBack,
  onConvertToOrder 
}: QuoteManagement3DetailProps) {
  const { itemMasters, updateQuote } = useData();
  
  // 디버깅: 전달된 quote 데이터 확인
  useEffect(() => {
    console.log("🔍 QuoteManagement3Detail - 전달된 quote:", quote);
    console.log("🔍 quote.bomCalculations:", quote.bomCalculations);
    console.log("🔍 bomCalculations 개수:", quote.bomCalculations?.length || 0);
    console.log("🔍 quote.autoCalculationSettings:", quote.autoCalculationSettings);
  }, [quote]);
  
  // 다이얼로그 상태
  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);
  
  // 선택된 제품 정보
  const selectedProduct = itemMasters.find(item => item.id === quote.selectedProductId);
  
  // 제품명 표시 로직 - 여러 제품 지원
  const getProductDisplayName = () => {
    // selectedProducts 배열이 있는 경우
    if (quote.selectedProducts && quote.selectedProducts.length > 0) {
      if (quote.selectedProducts.length === 1) {
        return quote.selectedProducts[0];
      } else {
        return `${quote.selectedProducts[0]} 외 ${quote.selectedProducts.length - 1}건`;
      }
    }
    // 단일 제품 ID가 있는 경우
    if (selectedProduct) {
      return selectedProduct.itemName;
    }
    // modelSelection이 있는 경우
    if (quote.modelSelection) {
      return quote.modelSelection;
    }
    return '-';
  };
  
  // 최종확정 상태 확인
  const isFinalized = quote.status === 'finalized' || quote.status === 'approved' || quote.status === 'completed';
  
  // 최종확정 버튼 핸들러
  const handleFinalize = () => {
    updateQuote(quote.id, { status: 'finalized' });
    toast.success("견적이 최종 확정되었습니다.");
  };
  
  // 수주전환 버튼 핸들러
  const handleConvertToOrder = () => {
    if (onConvertToOrder) {
      onConvertToOrder(quote);
    } else {
      toast.info("수주 등록 화면으로 이동합니다.");
    }
  };

  // 상태 배지 표시
  const getStatusBadge = (status?: string) => {
    const statusMap: Record<string, { variant: "default" | "secondary" | "destructive" | "outline", label: string }> = {
      draft: { variant: "secondary", label: "임시저장" },
      sent: { variant: "default", label: "발송완료" },
      approved: { variant: "default", label: "승인" },
      rejected: { variant: "destructive", label: "반려" },
      converted: { variant: "default", label: "수주전환" },
      finalized: { variant: "default", label: "확정" },
    };
    
    const statusInfo = statusMap[status || 'draft'];
    return (
      <Badge variant={statusInfo.variant}>
        {statusInfo.label}
      </Badge>
    );
  };

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader 
        title="견적 상세"
        description={`견적번호: ${quote.quoteNumber}`}
        icon={FileText}
        leftActions={
          <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>
          </div>
        }
        rightActions={
          <div className="flex flex-wrap gap-2">
            <Button variant="outline" className="hidden md:flex" onClick={onBack}>
              <List className="w-4 h-4 mr-2" />
              목록
            </Button>
            {onEdit && !isFinalized && (
              <Button onClick={onEdit}>
                <Edit className="w-4 h-4 mr-2" />
                수정
              </Button>
            )}
            {!isFinalized ? (
              <Button 
                onClick={handleFinalize}
                className="bg-green-600 hover:bg-green-700 text-white"
              >
                <FileCheck className="w-4 h-4 mr-2" />
                최종확정
              </Button>
            ) : (
              <Button 
                onClick={handleConvertToOrder}
                className="bg-purple-600 hover:bg-purple-700 text-white"
              >
                <ShoppingCart className="w-4 h-4 mr-2" />
                수주전환
              </Button>
            )}
          </div>
        }
      />

      <div className="space-y-6">
        {/* 견적 수정 이력 */}
        {quote.revisions && quote.revisions.length > 0 && (
          <Card className="border-purple-200 bg-purple-50">
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-purple-700">
                <History className="h-5 w-5" />
                견적 수정 이력
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <div className="flex items-center gap-2 mb-4">
                  <Badge variant="default">현재</Badge>
                  <span className="font-semibold">버전 {quote.currentRevision || 0}</span>
                  {quote.isFinal && (
                    <Badge variant="default" className="ml-2">
                      <FileCheck className="w-3 h-3 mr-1" />
                      확정
                    </Badge>
                  )}
                </div>
                <div className="bg-white rounded-lg p-4 space-y-2">
                  {quote.revisions
                    .sort((a, b) => b.revisionNumber - a.revisionNumber)
                    .map((revision) => (
                      <div key={revision.revisionNumber} className="flex items-start gap-3 pb-2 border-b last:border-0">
                        <Badge variant="outline">{revision.revisionNumber}차</Badge>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 text-sm">
                            <span>{revision.revisionDate}</span>
                            <span className="text-muted-foreground">•</span>
                            <span>{revision.revisionBy}</span>
                          </div>
                          {revision.revisionReason && (
                            <div className="text-sm text-muted-foreground mt-1">
                              {revision.revisionReason}
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* 기본 정보 - 태블릿 2컬럼, 데스크톱 3컬럼 */}
        <Card>
          <CardHeader>
            <CardTitle>기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 모바일: 1컬럼 | 태블릿(768-1279px): 2컬럼 | 데스크톱(1280px+): 3컬럼 */}
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
              <div>
                <Label>견적번호</Label>
                <Input
                  value={quote.quoteNumber}
                  disabled
                  className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                />
              </div>
              <div>
                <Label>작성자</Label>
                <Input
                  value={quote.author}
                  disabled
                  className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                />
              </div>
              <div>
                <Label>발주처</Label>
                <Input
                  value={quote.client}
                  disabled
                  className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                />
              </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 disabled:text-black disabled:opacity-100"
                />
              </div>
              <div>
                <Label>연락처</Label>
                <Input
                  value={quote.contact || '-'}
                  disabled
                  className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                />
              </div>
              <div>
                <Label>현장명</Label>
                <Input
                  value={quote.site || '-'}
                  disabled
                  className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
              <div>
                <Label>현장코드</Label>
                <Input
                  value={quote.siteCode || '-'}
                  disabled
                  className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                />
              </div>
              <div>
                <Label>상태</Label>
                <Input
                  value={(() => {
                    const statusMap: Record<string, string> = {
                      'draft': '최초 등록',
                      'pending': '최초 등록',
                      'approved': '최종 확정',
                      'completed': '최종 확정',
                      'revision_2': '2차 수정',
                      'revision_3': '3차 수정',
                      'revision_4': '4차 수정',
                      'revision_5': '5차 수정',
                      'converted': '수주 전환',
                      'order_converted': '수주 전환'
                    };
                    return statusMap[quote.status] || quote.status || '-';
                  })()}
                  disabled
                  className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                />
              </div>
              <div>
                <Label>접수일</Label>
                <Input
                  value={quote.receiptDate || '-'}
                  disabled
                  className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
              <div>
                <Label>납기일</Label>
                <Input
                  value={quote.completionDate || '-'}
                  disabled
                  className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
              <div className="md:col-span-2 xl:col-span-3">
                <Label>비고</Label>
                <Textarea
                  value={quote.remarks || '-'}
                  disabled
                  className="bg-gray-50 text-black font-medium min-h-[80px] disabled:text-black disabled:opacity-100"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 자동 견적 산출 정보 - 태블릿에서 카드형, 데스크톱에서 그리드 */}
        <Card>
          <CardHeader>
            <CardTitle>자동 견적 산출 정보</CardTitle>
          </CardHeader>
          <CardContent>
            {/* 모바일 및 태블릿: 카드형 레이아웃 */}
            <div className="xl:hidden space-y-3">
              <div className="p-3 bg-muted/30 rounded-lg">
                <Label className="text-xs text-muted-foreground">제품 카테고리</Label>
                <p className="mt-1 font-medium">{quote.productCategory === 'SCREEN' ? '스크린' : '철재'}</p>
              </div>
              <div className="p-3 bg-muted/30 rounded-lg">
                <Label className="text-xs text-muted-foreground">선택된 제품</Label>
                <p className="mt-1 font-medium">{getProductDisplayName()}</p>
              </div>
              <div className="p-3 bg-muted/30 rounded-lg">
                <Label className="text-xs text-muted-foreground">수량</Label>
                <p className="mt-1 font-medium">{quote.quantity || 0}</p>
              </div>
              <div className="p-3 bg-muted/30 rounded-lg">
                <Label className="text-xs text-muted-foreground">오픈사이즈 (가로)</Label>
                <p className="mt-1 font-medium">{quote.openSizeWidth ? `${quote.openSizeWidth} mm` : (quote.autoCalculationSettings?.openSizeWidth ? `${quote.autoCalculationSettings.openSizeWidth} mm` : '-')}</p>
              </div>
              <div className="p-3 bg-muted/30 rounded-lg">
                <Label className="text-xs text-muted-foreground">오픈사이즈 (세로)</Label>
                <p className="mt-1 font-medium">{quote.openSizeHeight ? `${quote.openSizeHeight} mm` : (quote.autoCalculationSettings?.openSizeHeight ? `${quote.autoCalculationSettings.openSizeHeight} mm` : '-')}</p>
              </div>
              <div className="p-3 bg-muted/30 rounded-lg">
                <Label className="text-xs text-muted-foreground">부호</Label>
                <p className="mt-1 font-medium">{quote.code || (quote.autoCalculationSettings?.sign) || '-'}</p>
              </div>
              <div className="p-3 bg-muted/30 rounded-lg">
                <Label className="text-xs text-muted-foreground">층수</Label>
                <p className="mt-1 font-medium">{quote.floors || (quote.autoCalculationSettings?.floors) || '-'}</p>
              </div>
            </div>

            {/* 데스크톱: 그리드 레이아웃 */}
            <div className="hidden xl:block space-y-4">
              <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
                <div>
                  <Label>제품 카테고리</Label>
                  <Input
                    value={quote.productCategory === 'SCREEN' ? '스크린' : '철재'}
                    disabled
                    className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                  />
                </div>
                <div>
                  <Label>선택된 제품</Label>
                  <Input
                    value={getProductDisplayName()}
                    disabled
                    className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                  />
                </div>
                <div>
                  <Label>수량</Label>
                  <Input
                    value={quote.quantity || 0}
                    disabled
                    className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
                <div>
                  <Label>오픈사이즈 (가로)</Label>
                  <Input
                    value={quote.openSizeWidth ? `${quote.openSizeWidth} mm` : (quote.autoCalculationSettings?.openSizeWidth ? `${quote.autoCalculationSettings.openSizeWidth} mm` : '-')}
                    disabled
                    className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                  />
                </div>
                <div>
                  <Label>오픈사이즈 (세로)</Label>
                  <Input
                    value={quote.openSizeHeight ? `${quote.openSizeHeight} mm` : (quote.autoCalculationSettings?.openSizeHeight ? `${quote.autoCalculationSettings.openSizeHeight} mm` : '-')}
                    disabled
                    className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                  />
                </div>
                <div>
                  <Label>부호</Label>
                  <Input
                    value={quote.code || (quote.autoCalculationSettings?.sign) || '-'}
                    disabled
                    className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
                <div>
                  <Label>층수</Label>
                  <Input
                    value={quote.floors || (quote.autoCalculationSettings?.floors) || '-'}
                    disabled
                    className="bg-gray-50 text-black font-medium disabled:text-black disabled:opacity-100"
                  />
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 부품구성표(BOM) 계산 결과 */}
        {quote.bomCalculations && quote.bomCalculations.length > 0 ? (
          <Card>
            <CardHeader>
              <CardTitle>부품구성표(BOM) 계산 결과</CardTitle>
            </CardHeader>
            <CardContent>
              {/* 데스크톱 테이블 */}
              <div className="hidden xl:block overflow-x-auto border rounded-lg">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50 border-b">
                      <TableHead className="h-11 text-center">순번</TableHead>
                      <TableHead className="h-11">품목코드</TableHead>
                      <TableHead className="h-11">품명</TableHead>
                      <TableHead className="h-11">규격</TableHead>
                      <TableHead className="h-11 text-center">수량</TableHead>
                      <TableHead className="h-11 text-center">단위</TableHead>
                      <TableHead className="h-11 text-right">단가</TableHead>
                      <TableHead className="h-11 text-right">금액</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {quote.bomCalculations.map((row, index) => (
                      <TableRow key={row.id} className="hover:bg-muted/30 border-b">
                        <TableCell className="text-center">{index + 1}</TableCell>
                        <TableCell>{row.itemCode}</TableCell>
                        <TableCell>{row.itemName}</TableCell>
                        <TableCell>{quote.openSizeWidth && quote.openSizeHeight ? `${quote.openSizeWidth}×${quote.openSizeHeight}` : '-'}</TableCell>
                        <TableCell className="text-center">{row.calculatedQuantity != null ? Number(row.calculatedQuantity).toLocaleString() : '0'}</TableCell>
                        <TableCell className="text-center">{row.unit}</TableCell>
                        <TableCell className="text-right">{row.unitPrice != null ? Number(row.unitPrice).toLocaleString() : '0'}</TableCell>
                        <TableCell className="text-right">{row.totalPrice != null ? Number(row.totalPrice).toLocaleString() : '0'}원</TableCell>
                      </TableRow>
                    ))}
                    <TableRow className="bg-muted/50 border-b">
                      <TableCell colSpan={7} className="text-right">소계</TableCell>
                      <TableCell className="text-right">
                        {quote.amount.toLocaleString()}원
                      </TableCell>
                    </TableRow>
                    <TableRow className="bg-muted/30 border-b">
                      <TableCell colSpan={7} className="text-right">할인율</TableCell>
                      <TableCell className="text-right text-red-600">
                        0 %
                      </TableCell>
                    </TableRow>
                    <TableRow className="bg-blue-50">
                      <TableCell colSpan={7} className="text-right">착용 금액</TableCell>
                      <TableCell className="text-right text-blue-700">
                        {quote.amount.toLocaleString()}원
                      </TableCell>
                    </TableRow>
                  </TableBody>
                </Table>
              </div>

              {/* 모바일 및 태블릿 카드 */}
              <div className="xl:hidden space-y-3">
                {quote.bomCalculations.map((row, index) => (
                  <Card key={row.id}>
                    <CardContent className="p-4 space-y-3">
                      <div className="flex items-start justify-between pb-3 border-b">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <Badge variant="outline" className="text-xs">{index + 1}</Badge>
                            <span className="font-medium">{row.itemCode}</span>
                          </div>
                          <div className="text-sm">{row.itemName}</div>
                        </div>
                      </div>
                      <div className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">규격</span>
                          <span>{quote.openSizeWidth && quote.openSizeHeight ? `${quote.openSizeWidth}×${quote.openSizeHeight}` : '-'}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">수량</span>
                          <span>{row.calculatedQuantity != null ? Number(row.calculatedQuantity).toLocaleString() : '0'}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">단위</span>
                          <span>{row.unit}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">단가</span>
                          <span>{row.unitPrice != null ? Number(row.unitPrice).toLocaleString() : '0'}</span>
                        </div>
                      </div>
                      <div className="flex justify-between pt-3 border-t">
                        <span className="text-muted-foreground">금액</span>
                        <span className="font-medium">{row.totalPrice != null ? Number(row.totalPrice).toLocaleString() : '0'}원</span>
                      </div>
                    </CardContent>
                  </Card>
                ))}
                
                {/* 모바일 합계 정보 */}
                <div className="border rounded-lg overflow-hidden mt-4">
                  <div className="flex items-center justify-between p-3 bg-muted/50 border-b">
                    <span>소계</span>
                    <span>
                      {quote.amount.toLocaleString()}원
                    </span>
                  </div>
                  
                  <div className="flex items-center justify-between p-3 border-b">
                    <span>할인율</span>
                    <span className="text-red-600">
                      0 %
                    </span>
                  </div>
                  
                  <div className="flex items-center justify-between p-3 bg-blue-50">
                    <span>착용 금액</span>
                    <span className="text-blue-700">
                      {quote.amount.toLocaleString()}원
                    </span>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        ) : null}

        {/* 추가 메모 */}
        {quote.notes && (
          <Card>
            <CardHeader>
              <CardTitle>특이사항</CardTitle>
            </CardHeader>
            <CardContent>
              <Textarea
                value={quote.notes}
                disabled
                className="bg-muted/50 min-h-[120px]"
              />
            </CardContent>
          </Card>
        )}
      </div>

      {/* 견적서 다이얼로그 */}
      <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={quote 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-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={() => {
                  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>
              
              {/* 표시 옵션 체크박스 */}
              <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-hidden bg-gray-100">
            <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={quote as any} 
                  documentType="견적산출내역서"
                  showDetailedBreakdown={showDetailedBreakdown}
                  showMaterialList={showMaterialList}
                />
              </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={quote as any} />
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}