import type { Quote } from "./contexts/DataContext";
import { useData } from "./contexts/DataContext";

interface QuoteCalculationReportProps {
  quote: Quote;
  documentType?: "견적산출내역서" | "견적서";
  showDetailedBreakdown?: boolean;
  showMaterialList?: boolean;
}

export function QuoteCalculationReport({ 
  quote, 
  documentType = "견적산출내역서",
  showDetailedBreakdown = true,
  showMaterialList = true
}: QuoteCalculationReportProps) {
  const { itemMasters } = useData();

  const handlePrint = () => {
    window.print();
  };

  const handlePDFDownload = () => {
    alert('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하여 PDF를 생성할 수 있습니다.');
    window.print();
  };

  const handleEmailSend = () => {
    alert('이메일 전송 기능은 백엔드 연동이 필요합니다.\\n담당자 이메일: ' + (quote.contact || '미등록'));
  };

  const handleFaxSend = () => {
    alert('팩스 전송 기능은 백엔드 연동이 필요합니다.\\n팩스번호: 02-6911-6315');
  };

  const handleKakaoSend = () => {
    alert('카카오톡 전송 기능은 백엔드 연동이 필요합니다.\\n담당자 카카오톡: ' + (quote.contact || '미등록'));
  };

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

  const formatDate = (dateStr: string) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return `${date.getFullYear()}년 ${String(date.getMonth() + 1).padStart(2, '0')}월 ${String(date.getDate()).padStart(2, '0')}일`;
  };
  
  // 총 금액 계산
  const materialCost = quote.bomCalculations?.reduce((sum, calc) => sum + calc.totalPrice, 0) || 0;
  const totalAmount = quote.amount || quote.totalAmount || 0;
  
  // 수량별 합계 계산
  const costEstimateTotal = totalAmount;
  const detailedEstimateTotal = materialCost;
  
  // 오픈사이즈 파싱
  const openWidth = parseInt(quote.openSizeWidth || '0') || 0;
  const openHeight = parseInt(quote.openSizeHeight || '0') || 0;
  const manufactureWidth = openWidth > 0 ? openWidth + 100 : 0;
  const manufactureHeight = openHeight > 0 ? openHeight + 100 : 0;
  
  // 제품 카테고리 확인
  const productType = quote.productCategory || (quote.type === '스크린' ? 'SCREEN' : 'STEEL');
  
  // 자재 사이즈 계산
  const calculateRailSize = (height: number) => {
    if (height <= 2438) return '2438';
    if (height <= 3000) return '3000';
    if (height <= 3500) return '3500';
    if (height <= 4000) return '4000';
    return '4300';
  };
  
  const calculateCaseSize = (width: number) => {
    if (width <= 1219) return '1219';
    if (width <= 2438) return '2438';
    if (width <= 3000) return '3000';
    if (width <= 3500) return '3500';
    return '4000';
  };
  
  const railSize = calculateRailSize(openHeight);
  const caseSize = calculateCaseSize(openWidth);
  
  // 모터 용량 계산 (면적 기반)
  const area = (openWidth * openHeight) / 1000000; // 제곱미터
  const getMotorCapacity = (area: number) => {
    if (area <= 2) return '150';
    if (area <= 4) return '300';
    if (area <= 6) return '400';
    return '500';
  };
  
  const motorCapacity = getMotorCapacity(area);

  // 선택된 사이즈 설정
  const selectedRailSize = railSize;
  const selectedCaseSize = caseSize;

  // 소요자재 내역 - 값이 있는 항목만 필터링
  const materialItems = [
    selectedRailSize && {
      name: '가이드레일',
      spec: `${railSize}mm (EGI 1.6T, SUS 1.2T)`,
      quantity: 2,
      unit: '개'
    },
    selectedCaseSize && {
      name: '케이스',
      spec: `${caseSize}mm (EGI 1.6T)`,
      quantity: 1,
      unit: '개'
    },
    openWidth > 0 && {
      name: '하단마감재',
      spec: `${openWidth <= 3000 ? '3000' : '4000'}mm (SUS 1.2T)`,
      quantity: 2,
      unit: '개'
    },
    motorCapacity && {
      name: '모터',
      spec: `${motorCapacity}KG`,
      quantity: 1,
      unit: '개'
    },
    {
      name: '연동제어기',
      spec: '매입형',
      quantity: 1,
      unit: '개'
    },
    {
      name: '브라켓',
      spec: '백박스',
      quantity: 1,
      unit: '개'
    },
    {
      name: '영끝',
      spec: '-',
      quantity: 4,
      unit: '개'
    },
    selectedRailSize && {
      name: '연기차단재 (해당몰)',
      spec: `${railSize}mm`,
      quantity: 2,
      unit: '개'
    },
    {
      name: '연기차단재 (케이스용)',
      spec: '3000mm',
      quantity: 4,
      unit: '개'
    },
    {
      name: '참가시트',
      spec: '4500mm (5인치)',
      quantity: 1,
      unit: '개'
    },
    {
      name: '조인트바',
      spec: '300mm',
      quantity: 5,
      unit: '개'
    },
    {
      name: '영끝 (추가)',
      spec: '6000mm',
      quantity: 4,
      unit: '개'
    }
  ].filter(Boolean);

  return (
    <>
      <style>{`
        @media print {
          @page {
            size: A4 portrait;
            margin: 15mm;
          }
          
          body {
            background: white !important;
          }
          
          .print\\\\\\\\:hidden {
            display: none !important;
          }
          
          #quote-report-content {
            background: white !important;
            padding: 0 !important;
          }
          
          table {
            page-break-inside: avoid;
          }
          
          .page-break-after {
            page-break-after: always;
          }
        }
        
        /* 공문서 스타일 */
        .official-doc {
          font-family: 'Malgun Gothic', 'Apple SD Gothic Neo', sans-serif;
          background: white;
          color: #000;
          line-height: 1.5;
        }
        
        .doc-header {
          text-align: center;
          border-bottom: 3px double #000;
          padding-bottom: 20px;
          margin-bottom: 30px;
        }
        
        .doc-title {
          font-size: 26px;
          font-weight: 700;
          letter-spacing: 2px;
          margin-bottom: 12px;
        }
        
        .doc-number {
          font-size: 14px;
          color: #333;
        }
        
        .info-box {
          border: 2px solid #000;
          margin-bottom: 20px;
        }
        
        .info-box-header {
          background: #f0f0f0;
          border-bottom: 2px solid #000;
          padding: 8px 12px;
          font-weight: 700;
          text-align: center;
          font-size: 14px;
        }
        
        .info-box-content {
          padding: 0;
        }
        
        .info-table {
          width: 100%;
          border-collapse: collapse;
        }
        
        .info-table th {
          background: #f8f8f8;
          border: 1px solid #999;
          padding: 8px 10px;
          text-align: center;
          font-weight: 600;
          font-size: 13px;
          width: 100px;
        }
        
        .info-table td {
          border: 1px solid #999;
          padding: 8px 10px;
          font-size: 13px;
        }
        
        .amount-box {
          border: 3px double #000;
          padding: 20px;
          text-align: center;
          margin: 30px 0;
          background: #fafafa;
        }
        
        .amount-label {
          font-size: 16px;
          font-weight: 600;
          margin-bottom: 10px;
        }
        
        .amount-value {
          font-size: 32px;
          font-weight: 700;
          color: #000;
          letter-spacing: 1px;
        }
        
        .amount-note {
          font-size: 13px;
          color: #666;
          margin-top: 8px;
        }
        
        .section-title {
          background: #000;
          color: white;
          padding: 10px 15px;
          font-weight: 700;
          font-size: 15px;
          margin: 30px 0 15px 0;
          text-align: center;
          letter-spacing: 1px;
        }
        
        .detail-table {
          width: 100%;
          border-collapse: collapse;
          border: 2px solid #000;
        }
        
        .detail-table thead th {
          background: #e8e8e8;
          border: 1px solid #666;
          padding: 10px 6px;
          text-align: center;
          font-weight: 700;
          font-size: 12px;
        }
        
        .detail-table tbody td {
          border: 1px solid #999;
          padding: 8px 6px;
          font-size: 12px;
        }
        
        .detail-table tbody tr:hover {
          background: #f9f9f9;
        }
        
        .detail-table tfoot td {
          background: #f0f0f0;
          border: 1px solid #666;
          padding: 10px;
          font-weight: 700;
          font-size: 13px;
        }
        
        .material-table {
          width: 100%;
          border-collapse: collapse;
          border: 2px solid #000;
          margin-top: 15px;
        }
        
        .material-table th {
          background: #e8e8e8;
          border: 1px solid #666;
          padding: 8px;
          text-align: center;
          font-weight: 600;
          font-size: 12px;
        }
        
        .material-table td {
          border: 1px solid #999;
          padding: 8px;
          font-size: 12px;
        }
        
        .stamp-area {
          border: 2px solid #000;
          width: 80px;
          height: 80px;
          display: inline-block;
          position: relative;
          margin-left: 20px;
        }
        
        .stamp-text {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          font-size: 10px;
          color: #999;
          text-align: center;
          line-height: 1.3;
        }
        
        .footer-note {
          margin-top: 40px;
          padding-top: 20px;
          border-top: 1px solid #ccc;
          font-size: 11px;
          color: #666;
          line-height: 1.6;
        }
        
        .signature-section {
          margin-top: 30px;
          text-align: right;
        }
      `}</style>
      
      {/* 순수한 문서 컴포넌트 - 모달 구조 제거 */}
      <div className="official-doc">
        {/* 문서 헤더 */}
        <div className="doc-header">
          <div className="doc-title">
            {documentType === "견적서" ? "견 적 서" : "견 적 산 출 내 역 서"}
          </div>
          <div className="doc-number">
            문서번호: {quote.quoteNumber || '-'} | 작성일자: {formatDate(quote.registrationDate || quote.quoteDate || quote.receiptDate || '')}
          </div>
        </div>

        {/* 수요자 정보 */}
        <div className="info-box">
          <div className="info-box-header">수 요 자</div>
          <div className="info-box-content">
            <table className="info-table">
              <tbody>
                <tr>
                  <th>업체명</th>
                  <td colSpan={3}>{quote.client || quote.customerName || '-'}</td>
                </tr>
                <tr>
                  <th>현장명</th>
                  <td>{quote.site || quote.projectName || '-'}</td>
                  <th>담당자</th>
                  <td>{quote.manager || quote.author || '-'}</td>
                </tr>
                <tr>
                  <th>제품명</th>
                  <td>{quote.modelSelection || quote.productCode || '-'}</td>
                  <th>연락처</th>
                  <td>{quote.contact || quote.contactPhone || '-'}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        {/* 공급자 정보 */}
        <div className="info-box">
          <div className="info-box-header">공 급 자</div>
          <div className="info-box-content">
            <table className="info-table">
              <tbody>
                <tr>
                  <th>상호</th>
                  <td>(주)염진건설</td>
                  <th>사업자등록번호</th>
                  <td>139-87-00353</td>
                </tr>
                <tr>
                  <th>대표자</th>
                  <td>김 용 진</td>
                  <th>업태</th>
                  <td>제조</td>
                </tr>
                <tr>
                  <th>종목</th>
                  <td colSpan={3}>방창, 셔터, 금속창호</td>
                </tr>
                <tr>
                  <th>사업장주소</th>
                  <td colSpan={3}>경기도 안성시 공업용지 오성길 45-22</td>
                </tr>
                <tr>
                  <th>전화</th>
                  <td>031-983-5130</td>
                  <th>팩스</th>
                  <td>02-6911-6315</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        {/* 총 견적금액 */}
        <div className="amount-box">
          <div className="amount-label">총 견적금액</div>
          <div className="amount-value">₩ {formatAmount(totalAmount)}</div>
          <div className="amount-note">※ 부가가치세 별도</div>
        </div>

        {/* 세부 산출내역서 */}
        {showDetailedBreakdown && quote.bomCalculations && quote.bomCalculations.length > 0 && (
          <div className="page-break-after">
            <div className="section-title">세 부 산 출 내 역</div>
            
            <table className="detail-table">
              <thead>
                <tr>
                  <th style={{ width: '40px' }}>No.</th>
                  <th style={{ width: '200px' }}>품목명</th>
                  <th style={{ width: '150px' }}>규격</th>
                  <th style={{ width: '70px' }}>수량</th>
                  <th style={{ width: '50px' }}>단위</th>
                  <th style={{ width: '110px' }}>단가</th>
                  <th style={{ width: '130px' }}>금액</th>
                </tr>
              </thead>
              <tbody>
                {quote.bomCalculations.map((bom, index) => {
                  // ItemMaster에서 규격 정보 찾기
                  const itemMaster = itemMasters.find(item => item.itemCode === bom.itemCode || item.itemName === bom.itemName);
                  const specification = bom.note || bom.formula || itemMaster?.specification || '-';
                  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}`}>
                      <td style={{ textAlign: 'center' }}>{index + 1}</td>
                      <td>{bom.itemName}</td>
                      <td style={{ fontSize: '11px' }}>{specification}</td>
                      <td style={{ textAlign: 'right' }}>{displayQty}</td>
                      <td style={{ textAlign: 'center' }}>{bom.unit || 'SET'}</td>
                      <td style={{ textAlign: 'right' }}>{formatAmount(bom.unitPrice)}</td>
                      <td style={{ textAlign: 'right', fontWeight: '600' }}>{formatAmount(bom.totalPrice)}</td>
                    </tr>
                  );
                })}
              </tbody>
              <tfoot>
                <tr>
                  <td colSpan={6} style={{ textAlign: 'right', padding: '12px', background: '#e0e0e0', fontWeight: '700' }}>공급가액 합계</td>
                  <td style={{ textAlign: 'right', padding: '12px', background: '#e0e0e0', fontSize: '15px', fontWeight: '700' }}>{formatAmount(materialCost)}</td>
                </tr>
              </tfoot>
            </table>
          </div>
        )}

        {/* 소요자재 내역 */}
        {showMaterialList && documentType !== "견적서" && (
          <div>
            <div className="section-title">소 요 자 재 내 역</div>
            
            {/* 제품 정보 */}
            <div className="info-box" style={{ marginTop: '15px' }}>
              <div className="info-box-content">
                <table className="info-table">
                  <tbody>
                    <tr>
                      <th>제품구분</th>
                      <td>{productType === 'SCREEN' ? '스크린' : '철재'}</td>
                      <th>부호</th>
                      <td>{quote.code || '-'}</td>
                    </tr>
                    <tr>
                      <th>오픈사이즈</th>
                      <td>W {quote.openSizeWidth || '-'} × H {quote.openSizeHeight || '-'} (mm)</td>
                      <th>제작사이즈</th>
                      <td>W {manufactureWidth > 0 ? manufactureWidth : '-'} × H {manufactureHeight > 0 ? manufactureHeight : '-'} (mm)</td>
                    </tr>
                    <tr>
                      <th>수량</th>
                      <td>{quote.quantity || 1} SET</td>
                      <th>케이스</th>
                      <td>{caseSize} × 550 (mm)</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            {/* 자재 목록 테이블 */}
            <table className="material-table">
              <thead>
                <tr>
                  <th style={{ width: '40px' }}>No.</th>
                  <th>자재명</th>
                  <th style={{ width: '250px' }}>규격</th>
                  <th style={{ width: '80px' }}>수량</th>
                  <th style={{ width: '60px' }}>단위</th>
                </tr>
              </thead>
              <tbody>
                {materialItems.map((item: any, index: number) => (
                  <tr key={index}>
                    <td style={{ textAlign: 'center' }}>{index + 1}</td>
                    <td>{item.name}</td>
                    <td>{item.spec}</td>
                    <td style={{ textAlign: 'center', fontWeight: '600' }}>{item.quantity}</td>
                    <td style={{ textAlign: 'center' }}>{item.unit}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* 비고사항 */}
        {(quote.memo || quote.notes || quote.commitment || quote.remarks) && (
          <div style={{ marginTop: '30px' }}>
            <div className="section-title">비 고 사 항</div>
            <div style={{ 
              border: '2px solid #000', 
              padding: '15px', 
              minHeight: '100px', 
              whiteSpace: 'pre-wrap',
              fontSize: '13px',
              lineHeight: '1.8',
              marginTop: '15px'
            }}>
              {quote.memo || quote.notes || quote.commitment || quote.remarks}
            </div>
          </div>
        )}

        {/* 서명란 */}
        <div className="signature-section">
          <div style={{ display: 'inline-block', textAlign: 'left' }}>
            <div style={{ marginBottom: '15px', fontSize: '14px' }}>
              상기와 같이 견적합니다.
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
              <div>
                <div style={{ fontSize: '13px', marginBottom: '5px' }}>{formatDate(quote.registrationDate || quote.quoteDate || '')}</div>
                <div style={{ fontSize: '15px', fontWeight: '600' }}>
                  공급자: (주)염진건설 (인)
                </div>
              </div>
              <div className="stamp-area">
                <div className="stamp-text">
                  (인감<br/>날인)
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 하단 안내사항 */}
        <div className="footer-note">
          <p style={{ fontWeight: '600', marginBottom: '8px' }}>【 유의사항 】</p>
          <p>1. 본 견적서는 {formatDate(quote.registrationDate || quote.quoteDate || '')} 기준으로 작성되었으며, 자재 가격 변동 시 조정될 수 있습니다.</p>
          <p>2. 견적 유효기간은 발행일로부터 30일이며, 기간 경과 시 재견적이 필요합니다.</p>
          <p>3. 제작 사양 및 수량 변경 시 견적 금액이 변동될 수 있습니다.</p>
          <p>4. 현장 여건에 따라 추가 비용이 발생할 수 있습니다.</p>
          <p style={{ marginTop: '12px', textAlign: 'center', fontWeight: '600' }}>
            문의: {quote.manager || quote.author} | {quote.contact || '031-983-5130'}
          </p>
        </div>
      </div>
    </>
  );
}