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

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

export function OrderContractReport({ order, onClose }: OrderContractReportProps) {
  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()}년 ${date.getMonth() + 1}월 ${date.getDate()}일`;
  };

  return (
    <>
      <style>{`
        @media print {
          @page {
            size: A4;
            margin: 15mm;
          }
          
          body {
            background: white !important;
          }
          
          .print\\\\:hidden {
            display: none !important;
          }
          
          #contract-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="contract-content" className="p-8 print:p-4">
            {/* 상단 타이틀 */}
            <div className="text-center mb-8">
              <h1 className="text-3xl font-bold mb-2">수 주 계 약 서</h1>
              <p className="text-sm text-gray-600">CONTRACT AGREEMENT</p>
            </div>

            {/* 계약 정보 */}
            <div className="mb-6 border border-gray-400">
              <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">로트번호</td>
                    <td className="border border-gray-400 px-3 py-2 font-bold text-blue-600" colSpan={3}>
                      {order.orderNumber}
                    </td>
                    <td className="border border-gray-400 bg-gray-100 px-3 py-2 w-32">계약일자</td>
                    <td className="border border-gray-400 px-3 py-2" colSpan={3}>
                      {formatDate(order.orderDate)}
                    </td>
                  </tr>
                  <tr>
                    <td className="border border-gray-400 bg-gray-100 px-3 py-2">현장명</td>
                    <td className="border border-gray-400 px-3 py-2 font-medium" colSpan={3}>
                      {order.siteName || order.projectName}
                    </td>
                    <td className="border border-gray-400 bg-gray-100 px-3 py-2">납품예정일</td>
                    <td className="border border-gray-400 px-3 py-2" colSpan={3}>
                      {formatDate(order.deliveryDate)}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            {/* 계약 당사자 */}
            <div className="grid grid-cols-2 gap-4 mb-6">
              {/* 공급자 (을) */}
              <div className="border border-gray-400">
                <div className="bg-gray-100 px-3 py-2 border-b border-gray-400">
                  <h3 className="font-semibold text-center">공급자 (을)</h3>
                </div>
                <div className="p-3 text-sm space-y-2">
                  <div className="grid grid-cols-3 gap-2">
                    <span className="text-gray-600">상호:</span>
                    <span className="col-span-2 font-medium">동호기업</span>
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    <span className="text-gray-600">대표자:</span>
                    <span className="col-span-2 font-medium">이 광 호</span>
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    <span className="text-gray-600">사업자번호:</span>
                    <span className="col-span-2 font-medium">139-87-00333</span>
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    <span className="text-gray-600">주소:</span>
                    <span className="col-span-2">경기도 안성시 공업용지 오성길 45-22</span>
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    <span className="text-gray-600">전화:</span>
                    <span className="col-span-2">031-983-5130</span>
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    <span className="text-gray-600">팩스:</span>
                    <span className="col-span-2">02-6911-6315</span>
                  </div>
                </div>
              </div>

              {/* 수요자 (갑) */}
              <div className="border border-gray-400">
                <div className="bg-gray-100 px-3 py-2 border-b border-gray-400">
                  <h3 className="font-semibold text-center">수요자 (갑)</h3>
                </div>
                <div className="p-3 text-sm space-y-2">
                  <div className="grid grid-cols-3 gap-2">
                    <span className="text-gray-600">상호:</span>
                    <span className="col-span-2 font-medium">{order.customerName}</span>
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    <span className="text-gray-600">프로젝트:</span>
                    <span className="col-span-2 font-medium">{order.projectName}</span>
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    <span className="text-gray-600">배송지:</span>
                    <span className="col-span-2">{order.shippingAddress}</span>
                  </div>
                  {order.shippingAddressDetail && (
                    <div className="grid grid-cols-3 gap-2">
                      <span className="text-gray-600"></span>
                      <span className="col-span-2">{order.shippingAddressDetail}</span>
                    </div>
                  )}
                  <div className="grid grid-cols-3 gap-2">
                    <span className="text-gray-600">수령인:</span>
                    <span className="col-span-2">{order.receiverName}</span>
                  </div>
                  <div className="grid grid-cols-3 gap-2">
                    <span className="text-gray-600">연락처:</span>
                    <span className="col-span-2">{order.receiverPhone}</span>
                  </div>
                </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">
                <tbody>
                  <tr>
                    <td className="border border-gray-400 bg-gray-50 px-3 py-2 w-32">견적 금액</td>
                    <td className="border border-gray-400 px-3 py-2 text-right">
                      ₩ {formatAmount(order.originalAmount)}
                    </td>
                    <td className="border border-gray-400 bg-gray-50 px-3 py-2 w-32">할인율</td>
                    <td className="border border-gray-400 px-3 py-2 text-right text-red-600">
                      {order.discountRate}%
                    </td>
                  </tr>
                  <tr>
                    <td className="border border-gray-400 bg-gray-50 px-3 py-2">할인 금액</td>
                    <td className="border border-gray-400 px-3 py-2 text-right text-red-600">
                      - ₩ {formatAmount(order.discountAmount)}
                    </td>
                    <td className="border border-gray-400 bg-gray-50 px-3 py-2">부가세</td>
                    <td className="border border-gray-400 px-3 py-2 text-right">
                      별도
                    </td>
                  </tr>
                  <tr className="bg-blue-50">
                    <td className="border border-gray-400 bg-blue-100 px-3 py-3 font-bold" colSpan={3}>
                      최종 계약 금액 (부가세 별도)
                    </td>
                    <td className="border border-gray-400 px-3 py-3 text-right text-xl font-bold text-blue-600">
                      ₩ {formatAmount(order.totalAmount)}
                    </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>
              <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">번호</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>
                  </tr>
                </thead>
                <tbody>
                  {order.items && order.items.length > 0 ? (
                    <>
                      {order.items.map((item, index) => (
                        <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}
                          </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>
                        </tr>
                      ))}
                      <tr className="bg-gray-50 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.items.reduce((sum, item) => sum + item.totalPrice, 0))}
                        </td>
                      </tr>
                    </>
                  ) : (
                    <tr>
                      <td colSpan={7} 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-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-16">차수</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">
                          {lot.scheduleNumber}차
                        </td>
                        <td className="border border-gray-400 px-2 py-2">{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">
                          {lot.note || '-'}
                        </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 space-y-2">
                <p>1. 납품 장소: {order.shippingAddress}</p>
                <p>2. 납품 기한: {formatDate(order.deliveryDate)}</p>
                <p>3. 배송 방식: {order.shippingMethod === 'direct' ? '직송' : order.shippingMethod === 'cargo' ? '화물' : '택배'}</p>
                <p>4. 대금 지급 조건: 별도 협의</p>
                <p>5. 부가가치세: 별도</p>
                <p>6. 품질 보증: 제조사 기준에 따름</p>
                <p>7. 특이사항: {order.note || '없음'}</p>
              </div>
            </div>

            {/* 서명란 */}
            <div className="grid grid-cols-2 gap-8 mt-12">
              <div className="text-center">
                <p className="mb-12">공급자 (을)</p>
                <div className="border-t-2 border-gray-400 pt-2 mx-8">
                  <p className="font-bold">동호기업 대표 이 광 호</p>
                  <p className="text-sm text-gray-600 mt-1">(인)</p>
                </div>
              </div>
              <div className="text-center">
                <p className="mb-12">수요자 (갑)</p>
                <div className="border-t-2 border-gray-400 pt-2 mx-8">
                  <p className="font-bold">{order.customerName}</p>
                  <p className="text-sm text-gray-600 mt-1">(인)</p>
                </div>
              </div>
            </div>

            {/* 하단 정보 */}
            <div className="mt-12 pt-6 border-t text-xs text-gray-600 text-center print:block">
              <p>본 계약서는 {formatDate(order.orderDate)}에 작성되었습니다.</p>
              <p className="mt-1">문의: 동호기업 영업팀 | 전화: 031-983-5130 | 팩스: 02-6911-6315</p>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
