import { Button } from "./ui/button";
import { X, Printer, Mail, Download } from "lucide-react";
import type { SalesOrder } from "./contexts/DataContext";

interface TransactionSpecificationReportProps {
  order: SalesOrder;
  onClose: () => void;
}

export function TransactionSpecificationReport({ order, onClose }: TransactionSpecificationReportProps) {
  const handlePrint = () => {
    window.print();
  };

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

  const handleEmailSend = () => {
    alert(`이메일 전송 기능은 백엔드 연동이 필요합니다.\n수신: ${order.customerName}`);
  };

  const formatAmount = (amount: number) => {
    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')}`;
  };

  // 부가세 계산 (10%)
  const vatAmount = Math.floor(order.totalAmount * 0.1);
  const totalWithVat = order.totalAmount + vatAmount;

  return (
    <>
      <style>{`
        @media print {
          @page {
            size: A4;
            margin: 15mm;
          }
          
          body {
            background: white !important;
          }
          
          .print\\\\:hidden {
            display: none !important;
          }
          
          #specification-content {
            background: white !important;
            padding: 0 !important;
          }
          
          .bg-blue-600 {
            background-color: #2563eb !important;
            color: white !important;
          }
          
          .bg-gray-100 {
            background-color: #f3f4f6 !important;
          }
          
          .border-gray-400 {
            border-color: #9ca3af !important;
          }
          
          .border-gray-300 {
            border-color: #d1d5db !important;
          }
        }
      `}</style>
      
      <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">
          {/* 프린트 시 숨김 버튼 영역 */}
          <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" className="bg-red-600 hover:bg-red-700 text-white" onClick={handlePDFDownload}>
                  <Download className="w-4 h-4 mr-2" />
                  PDF 저장
                </Button>
                <Button variant="outline" className="bg-blue-600 hover:bg-blue-700 text-white" onClick={handleEmailSend}>
                  <Mail className="w-4 h-4 mr-2" />
                  메일 전송
                </Button>
                <Button variant="outline" onClick={handlePrint}>
                  <Printer className="w-4 h-4 mr-2" />
                  인쇄
                </Button>
                <Button variant="outline" onClick={onClose}>
                  <X className="w-4 h-4 mr-2" />
                  닫기
                </Button>
              </div>
            </div>
          </div>

          {/* 거래명세표 내용 */}
          <div id="specification-content" className="p-8 print:p-4">
            {/* 상단 타이틀 */}
            <div className="text-center mb-6">
              <h1 className="text-3xl font-bold">거 래 명 세 표</h1>
              <p className="text-sm text-gray-600 mt-1">TRANSACTION SPECIFICATION</p>
            </div>

            {/* 공급자/공급받는자 정보 */}
            <div className="grid grid-cols-2 gap-4 mb-6">
              {/* 공급자 */}
              <div className="border-2 border-gray-400">
                <div className="bg-gray-100 px-3 py-2 border-b-2 border-gray-400">
                  <h3 className="font-bold text-center">공급자</h3>
                </div>
                <table className="w-full text-sm">
                  <tbody>
                    <tr>
                      <td className="border border-gray-300 bg-gray-50 px-2 py-1.5 w-24">등록번호</td>
                      <td className="border border-gray-300 px-2 py-1.5" colSpan={3}>139-87-00333</td>
                    </tr>
                    <tr>
                      <td className="border border-gray-300 bg-gray-50 px-2 py-1.5">상호<br/>(법인명)</td>
                      <td className="border border-gray-300 px-2 py-1.5 font-bold">동호기업</td>
                      <td className="border border-gray-300 bg-gray-50 px-2 py-1.5 w-20">성명</td>
                      <td className="border border-gray-300 px-2 py-1.5">이 광 호</td>
                    </tr>
                    <tr>
                      <td className="border border-gray-300 bg-gray-50 px-2 py-1.5">사업장<br/>주소</td>
                      <td className="border border-gray-300 px-2 py-1.5" colSpan={3}>
                        경기도 안성시 공업용지 오성길 45-22
                      </td>
                    </tr>
                    <tr>
                      <td className="border border-gray-300 bg-gray-50 px-2 py-1.5">업태</td>
                      <td className="border border-gray-300 px-2 py-1.5">제조</td>
                      <td className="border border-gray-300 bg-gray-50 px-2 py-1.5">종목</td>
                      <td className="border border-gray-300 px-2 py-1.5">방창,셔터,금속성호</td>
                    </tr>
                  </tbody>
                </table>
              </div>

              {/* 공급받는자 */}
              <div className="border-2 border-gray-400">
                <div className="bg-gray-100 px-3 py-2 border-b-2 border-gray-400">
                  <h3 className="font-bold text-center">공급받는자</h3>
                </div>
                <table className="w-full text-sm">
                  <tbody>
                    <tr>
                      <td className="border border-gray-300 bg-gray-50 px-2 py-1.5 w-24">등록번호</td>
                      <td className="border border-gray-300 px-2 py-1.5" colSpan={3}>
                        {order.customerCode || '-'}
                      </td>
                    </tr>
                    <tr>
                      <td className="border border-gray-300 bg-gray-50 px-2 py-1.5">상호<br/>(법인명)</td>
                      <td className="border border-gray-300 px-2 py-1.5 font-bold">
                        {order.customerName}
                      </td>
                      <td className="border border-gray-300 bg-gray-50 px-2 py-1.5 w-20">성명</td>
                      <td className="border border-gray-300 px-2 py-1.5">
                        {order.receiverName}
                      </td>
                    </tr>
                    <tr>
                      <td className="border border-gray-300 bg-gray-50 px-2 py-1.5">사업장<br/>주소</td>
                      <td className="border border-gray-300 px-2 py-1.5" colSpan={3}>
                        {order.shippingAddress}
                        {order.shippingAddressDetail && ` ${order.shippingAddressDetail}`}
                      </td>
                    </tr>
                    <tr>
                      <td className="border border-gray-300 bg-gray-50 px-2 py-1.5">연락처</td>
                      <td className="border border-gray-300 px-2 py-1.5" colSpan={3}>
                        {order.receiverPhone}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            {/* 작성일자 및 로트번호 */}
            <div className="border border-gray-400 mb-4">
              <table className="w-full border-collapse text-sm">
                <tbody>
                  <tr>
                    <td className="border border-gray-400 bg-gray-100 px-3 py-2 w-32 text-center">작성일자</td>
                    <td className="border border-gray-400 px-3 py-2 text-center">
                      {formatDate(order.orderDate)}
                    </td>
                    <td className="border border-gray-400 bg-gray-100 px-3 py-2 w-32 text-center">로트번호</td>
                    <td className="border border-gray-400 px-3 py-2 text-center font-bold text-blue-600">
                      {order.orderNumber}
                    </td>
                    <td className="border border-gray-400 bg-gray-100 px-3 py-2 w-32 text-center">현장명</td>
                    <td className="border border-gray-400 px-3 py-2 text-center font-medium">
                      {order.siteName || order.projectName}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            {/* 금액 요약 */}
            <div className="mb-4">
              <table className="w-full border-collapse text-sm border-2 border-gray-400">
                <thead>
                  <tr className="bg-gray-100">
                    <th className="border border-gray-400 px-3 py-2 w-1/3">공급가액</th>
                    <th className="border border-gray-400 px-3 py-2 w-1/3">부가세</th>
                    <th className="border border-gray-400 px-3 py-2 w-1/3">합계</th>
                  </tr>
                </thead>
                <tbody>
                  <tr className="text-center">
                    <td className="border border-gray-400 px-3 py-3 text-lg font-bold">
                      ₩ {formatAmount(order.totalAmount)}
                    </td>
                    <td className="border border-gray-400 px-3 py-3 text-lg font-bold">
                      ₩ {formatAmount(vatAmount)}
                    </td>
                    <td className="border border-gray-400 px-3 py-3 text-xl font-bold text-blue-600">
                      ₩ {formatAmount(totalWithVat)}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            {/* 할인 정보 */}
            {order.discountRate > 0 && (
              <div className="mb-4 p-3 bg-yellow-50 border border-yellow-300 rounded">
                <div className="flex justify-between items-center text-sm">
                  <span className="font-medium">할인 적용:</span>
                  <div className="flex gap-4">
                    <span>견적 금액: ₩{formatAmount(order.originalAmount)}</span>
                    <span className="text-red-600">할인율: {order.discountRate}%</span>
                    <span className="text-red-600">할인 금액: -₩{formatAmount(order.discountAmount)}</span>
                  </div>
                </div>
              </div>
            )}

            {/* 품목 명세 (개소별 금액) */}
            <div className="mb-6">
              <div className="bg-gray-100 px-3 py-2 border border-gray-400">
                <h3 className="font-semibold">품목 명세</h3>
              </div>
              <table className="w-full border-collapse text-sm border border-gray-400">
                <thead>
                  <tr className="bg-gray-50">
                    <th className="border border-gray-400 px-2 py-2 w-12">NO</th>
                    <th className="border border-gray-400 px-2 py-2">품목명</th>
                    <th className="border border-gray-400 px-2 py-2 w-32">개소/층/사이즈</th>
                    <th className="border border-gray-400 px-2 py-2 w-20">수량</th>
                    <th className="border border-gray-400 px-2 py-2 w-16">단위</th>
                    <th className="border border-gray-400 px-2 py-2 w-28">단가</th>
                    <th className="border border-gray-400 px-2 py-2 w-32">공급가액</th>
                    <th className="border border-gray-400 px-2 py-2 w-28">부가세</th>
                    <th className="border border-gray-400 px-2 py-2 w-32">합계</th>
                  </tr>
                </thead>
                <tbody>
                  {order.items && order.items.length > 0 ? (
                    <>
                      {order.items.map((item, index) => {
                        const itemVat = Math.floor(item.totalPrice * 0.1);
                        const itemTotal = item.totalPrice + itemVat;
                        
                        return (
                          <tr key={item.id}>
                            <td className="border border-gray-400 px-2 py-2 text-center">{index + 1}</td>
                            <td className="border border-gray-400 px-2 py-2">{item.itemName}</td>
                            <td className="border border-gray-400 px-2 py-2 text-center">
                              {item.specification || '-'}
                            </td>
                            <td className="border border-gray-400 px-2 py-2 text-right">
                              {item.quantity.toLocaleString()}
                            </td>
                            <td className="border border-gray-400 px-2 py-2 text-center">
                              {item.unit}
                            </td>
                            <td className="border border-gray-400 px-2 py-2 text-right">
                              {formatAmount(item.unitPrice)}
                            </td>
                            <td className="border border-gray-400 px-2 py-2 text-right font-medium">
                              {formatAmount(item.totalPrice)}
                            </td>
                            <td className="border border-gray-400 px-2 py-2 text-right">
                              {formatAmount(itemVat)}
                            </td>
                            <td className="border border-gray-400 px-2 py-2 text-right font-medium">
                              {formatAmount(itemTotal)}
                            </td>
                          </tr>
                        );
                      })}
                      <tr className="bg-gray-100 font-bold">
                        <td colSpan={6} className="border border-gray-400 px-2 py-2 text-right">
                          합계
                        </td>
                        <td className="border border-gray-400 px-2 py-2 text-right text-blue-600">
                          {formatAmount(order.totalAmount)}
                        </td>
                        <td className="border border-gray-400 px-2 py-2 text-right text-blue-600">
                          {formatAmount(vatAmount)}
                        </td>
                        <td className="border border-gray-400 px-2 py-2 text-right text-blue-600">
                          {formatAmount(totalWithVat)}
                        </td>
                      </tr>
                    </>
                  ) : (
                    <tr>
                      <td colSpan={9} className="border border-gray-400 px-2 py-4 text-center text-gray-500">
                        품목 정보가 없습니다.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>

            {/* 분할 출고 정보 */}
            {order.hasMultipleShipping && order.shippingLots && order.shippingLots.length > 0 && (
              <div className="mb-6">
                <div className="bg-blue-100 px-3 py-2 border border-blue-400">
                  <h3 className="font-semibold text-blue-800">📦 분할 출고 일정</h3>
                </div>
                <table className="w-full border-collapse text-sm border border-gray-400">
                  <thead>
                    <tr className="bg-gray-50">
                      <th className="border border-gray-400 px-2 py-2 w-20">차수</th>
                      <th className="border border-gray-400 px-2 py-2">로트번호</th>
                      <th className="border border-gray-400 px-2 py-2 w-32">출고예정일</th>
                      <th className="border border-gray-400 px-2 py-2 w-24">품목수</th>
                      <th className="border border-gray-400 px-2 py-2">배송지</th>
                    </tr>
                  </thead>
                  <tbody>
                    {order.shippingLots.map((lot) => (
                      <tr key={lot.id}>
                        <td className="border border-gray-400 px-2 py-2 text-center font-medium">
                          {lot.scheduleNumber}차
                        </td>
                        <td className="border border-gray-400 px-2 py-2 font-mono text-xs">
                          {lot.lotNumber}
                        </td>
                        <td className="border border-gray-400 px-2 py-2 text-center">
                          {formatDate(lot.scheduledDate)}
                        </td>
                        <td className="border border-gray-400 px-2 py-2 text-center">
                          {lot.items.length}개
                        </td>
                        <td className="border border-gray-400 px-2 py-2 text-sm">
                          {lot.shippingAddress || order.shippingAddress}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}

            {/* 비고 */}
            <div className="mb-6">
              <div className="bg-gray-100 px-3 py-2 border border-gray-400">
                <h3 className="font-semibold">비고사항</h3>
              </div>
              <div className="border border-gray-400 px-4 py-3 text-sm min-h-[80px]">
                <p>1. 납품 기한: {formatDate(order.deliveryDate)}</p>
                <p>2. 배송 방식: {order.shippingMethod === 'direct' ? '직송' : order.shippingMethod === 'cargo' ? '화물' : '택배'}</p>
                {order.note && <p>3. 특이사항: {order.note}</p>}
              </div>
            </div>

            {/* 하단 정보 */}
            <div className="mt-8 pt-4 border-t-2 border-gray-400 text-xs text-gray-600 text-center">
              <p className="font-medium mb-2">위 금액을 (  영수  /  청구  ) 합니다.</p>
              <p>본 거래명세표는 {formatDate(order.orderDate)}에 작성되었습니다.</p>
              <p className="mt-2">
                <span className="font-medium">공급자:</span> 동호기업 | 
                <span className="font-medium ml-4">전화:</span> 031-983-5130 | 
                <span className="font-medium ml-4">팩스:</span> 02-6911-6315
              </p>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
