import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";
import { Button } from "./ui/button";
import { Mail, Phone, MessageCircle, Download, Printer, X, Send } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner@2.0.3";

interface QuoteDocumentProps {
  isOpen: boolean;
  onClose: () => void;
  quoteData: {
    quoteNumber: string;
    customerName: string;
    projectName?: string;
    quoteDate: string;
    validUntil: string;
    contactPerson?: string;
    contactPhone?: string;
    items?: Array<{
      no: number;
      itemName: string;
      spec?: string;
      quantity: number;
      unit: string;
      unitPrice: number;
      totalPrice: number;
    }>;
    subtotal: number;
    vat: number;
    totalAmount: number;
    notes?: string;
    // 산출 정보
    modelName?: string;
    floors?: number;
    symbol?: string;
    bodyType?: string;
    installType?: string;
    openSize?: string;
    productSize?: string;
    bendingType?: string;
    laborCost?: number;
    materialCost?: number;
    overhead?: number;
    profitMargin?: number;
  };
  onSend?: (method: 'email' | 'fax' | 'kakao' | 'download' | 'print') => void;
}

export function QuoteDocument({ isOpen, onClose, quoteData, onSend }: QuoteDocumentProps) {
  const [isSending, setIsSending] = useState(false);

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

  const handleSend = async (method: 'email' | 'fax' | 'kakao' | 'download' | 'print') => {
    setIsSending(true);
    
    if (method === 'print') {
      handlePrint();
      setIsSending(false);
      return;
    }
    
    if (method === 'download') {
      toast.info('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하여 PDF를 생성할 수 있습니다.');
      handlePrint();
      setIsSending(false);
      return;
    }

    // 발송 처리
    if (onSend) {
      onSend(method);
    }
    
    setTimeout(() => {
      setIsSending(false);
    }, 1000);
  };

  const formatAmount = (amount: number | undefined) => {
    if (amount === undefined || amount === null) return '0';
    return 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')}일`;
  };

  return (
    <>
      <style>{`
        @media print {
          @page {
            size: A4 portrait;
            margin: 15mm;
          }
          
          body {
            background: white !important;
          }
          
          .print\\:hidden {
            display: none !important;
          }
          
          #quote-document-content {
            background: white !important;
            padding: 0 !important;
          }
          
          table {
            page-break-inside: avoid;
          }
        }
        
        /* 공문서 스타일 */
        .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;
        }
        
        .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>

      {isOpen && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 overflow-auto">
          <div className="bg-white rounded-lg w-full max-w-5xl max-h-[90vh] overflow-auto print:max-w-full print:max-h-full print:overflow-visible print:rounded-none">
            {/* 프린트 시 숨김 버튼 영역 */}
            <div className="print:hidden sticky top-0 bg-white border-b z-10">
              <div className="flex justify-between items-center p-4">
                <h2 className="text-lg font-semibold">견적서</h2>
                <div className="flex gap-2">
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={() => handleSend('email')}
                    disabled={isSending}
                    className="bg-blue-600 hover:bg-blue-700 text-white"
                  >
                    <Mail className="w-4 h-4 mr-2" />
                    이메일 발송
                  </Button>
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={() => handleSend('fax')}
                    disabled={isSending}
                    className="bg-green-600 hover:bg-green-700 text-white"
                  >
                    <Phone className="w-4 h-4 mr-2" />
                    팩스 발송
                  </Button>
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={() => handleSend('kakao')}
                    disabled={isSending}
                    className="bg-yellow-500 hover:bg-yellow-600 text-white"
                  >
                    <MessageCircle className="w-4 h-4 mr-2" />
                    카카오톡
                  </Button>
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={() => handleSend('download')}
                    className="bg-red-600 hover:bg-red-700 text-white"
                  >
                    <Download className="w-4 h-4 mr-2" />
                    PDF 저장
                  </Button>
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={handlePrint}
                  >
                    <Printer className="w-4 h-4 mr-2" />
                    인쇄
                  </Button>
                  <Button variant="outline" size="sm" onClick={onClose}>
                    <X className="w-4 h-4 mr-2" />
                    닫기
                  </Button>
                </div>
              </div>
            </div>

            {/* 견적서 내용 */}
            <div id="quote-document-content" className="official-doc p-12 print:p-8">
              {/* 문서 헤더 */}
              <div className="doc-header">
                <div className="doc-title">견 적 서</div>
                <div className="doc-number">
                  문서번호: {quoteData.quoteNumber} | 작성일자: {formatDate(quoteData.quoteDate)}
                </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}>{quoteData.customerName}</td>
                      </tr>
                      <tr>
                        <th>프로젝트명</th>
                        <td>{quoteData.projectName || '-'}</td>
                        <th>담당자</th>
                        <td>{quoteData.contactPerson || '-'}</td>
                      </tr>
                      <tr>
                        <th>견적일자</th>
                        <td>{formatDate(quoteData.quoteDate)}</td>
                        <th>연락처</th>
                        <td>{quoteData.contactPhone || '-'}</td>
                      </tr>
                      <tr>
                        <th>유효기간</th>
                        <td colSpan={3}>{formatDate(quoteData.validUntil)}</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-00333</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(quoteData.totalAmount)}</div>
                <div className="amount-note">※ 부가가치세 포함</div>
              </div>

              {/* 제품구성 정보 */}
              {(quoteData.modelName || quoteData.productSize) && (
                <>
                  <div className="section-title">제 품 구 성 정 보</div>
                  <div className="info-box" style={{ marginTop: '15px' }}>
                    <div className="info-box-content">
                      <table className="info-table">
                        <tbody>
                          {quoteData.modelName && (
                            <tr>
                              <th>모델</th>
                              <td>{quoteData.modelName}</td>
                              {quoteData.floors && (
                                <>
                                  <th>층수</th>
                                  <td>{quoteData.floors}층</td>
                                </>
                              )}
                            </tr>
                          )}
                          {quoteData.symbol && (
                            <tr>
                              <th>부호</th>
                              <td>{quoteData.symbol}</td>
                              {quoteData.bodyType && (
                                <>
                                  <th>본체종류</th>
                                  <td>{quoteData.bodyType}</td>
                                </>
                              )}
                            </tr>
                          )}
                          {quoteData.installType && (
                            <tr>
                              <th>설치유형</th>
                              <td>{quoteData.installType}</td>
                              {quoteData.openSize && (
                                <>
                                  <th>오픈사이즈</th>
                                  <td>{quoteData.openSize}</td>
                                </>
                              )}
                            </tr>
                          )}
                          {quoteData.productSize && (
                            <tr>
                              <th>제작치수</th>
                              <td>{quoteData.productSize}</td>
                              {quoteData.bendingType && (
                                <>
                                  <th>절곡물</th>
                                  <td>{quoteData.bendingType}</td>
                                </>
                              )}
                            </tr>
                          )}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </>
              )}

              {/* 품목 내역 */}
              {quoteData.items && quoteData.items.length > 0 && (
                <>
                  <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>
                      {quoteData.items.map((item) => (
                        <tr key={item.no}>
                          <td style={{ textAlign: 'center' }}>{item.no}</td>
                          <td>{item.itemName}</td>
                          <td style={{ textAlign: 'center' }}>{item.spec || '-'}</td>
                          <td style={{ textAlign: 'right' }}>{item.quantity}</td>
                          <td style={{ textAlign: 'center' }}>{item.unit}</td>
                          <td style={{ textAlign: 'right' }}>{formatAmount(item.unitPrice)}</td>
                          <td style={{ textAlign: 'right', fontWeight: '600' }}>{formatAmount(item.totalPrice)}</td>
                        </tr>
                      ))}
                    </tbody>
                    <tfoot>
                      <tr>
                        <td colSpan={6} style={{ textAlign: 'right', padding: '12px' }}>공급가액 합계</td>
                        <td style={{ textAlign: 'right', padding: '12px' }}>{formatAmount(quoteData.subtotal)}</td>
                      </tr>
                      <tr>
                        <td colSpan={6} style={{ textAlign: 'right', padding: '12px' }}>부가가치세 (10%)</td>
                        <td style={{ textAlign: 'right', padding: '12px' }}>{formatAmount(quoteData.vat)}</td>
                      </tr>
                      <tr>
                        <td colSpan={6} style={{ textAlign: 'right', padding: '12px', background: '#e0e0e0' }}>총 견적금액</td>
                        <td style={{ textAlign: 'right', padding: '12px', background: '#e0e0e0', fontSize: '15px', fontWeight: '700' }}>
                          {formatAmount(quoteData.totalAmount)}
                        </td>
                      </tr>
                    </tfoot>
                  </table>
                </>
              )}

              {/* 비용 산출 */}
              {(quoteData.laborCost || quoteData.materialCost || quoteData.overhead || quoteData.profitMargin) && (
                <>
                  <div className="section-title">비 용 산 출</div>
                  <div className="info-box" style={{ marginTop: '15px' }}>
                    <div className="info-box-content">
                      <table className="info-table">
                        <tbody>
                          <tr>
                            {quoteData.laborCost !== undefined && (
                              <>
                                <th>인건비</th>
                                <td>{formatAmount(quoteData.laborCost)}원</td>
                              </>
                            )}
                            {quoteData.materialCost !== undefined && (
                              <>
                                <th>재료비</th>
                                <td>{formatAmount(quoteData.materialCost)}원</td>
                              </>
                            )}
                          </tr>
                          <tr>
                            {quoteData.overhead !== undefined && (
                              <>
                                <th>경비</th>
                                <td>{formatAmount(quoteData.overhead)}원</td>
                              </>
                            )}
                            {quoteData.profitMargin !== undefined && (
                              <>
                                <th>이윤</th>
                                <td>{formatAmount(quoteData.profitMargin)}원</td>
                              </>
                            )}
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </>
              )}

              {/* 비고사항 */}
              {quoteData.notes && (
                <>
                  <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'
                  }}>
                    {quoteData.notes}
                  </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(quoteData.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(quoteData.quoteDate)} 기준으로 작성되었으며, 자재 가격 변동 시 조정될 수 있습니다.</p>
                <p>2. 견적 유효기간은 {formatDate(quoteData.validUntil)}까지이며, 기간 경과 시 재견적이 필요합니다.</p>
                <p>3. 제작 사양 및 수량 변경 시 견적 금액이 변동될 수 있습니다.</p>
                <p>4. 현장 여건에 따라 추가 비용이 발생할 수 있습니다.</p>
                <p style={{ marginTop: '12px', textAlign: 'center', fontWeight: '600' }}>
                  문의: {quoteData.contactPerson || '담당자'} | {quoteData.contactPhone || '031-983-5130'}
                </p>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}