import { useEffect } from 'react';
import { X, Download } from 'lucide-react';

interface OrderItem {
  id: number;
  menu_item_name: string;
  price: number;
  quantity: number;
}

interface Order {
  id: number;
  table_number: string;
  customer_phone: string | null;
  status: string;
  total: number;
  kot_number: number;
  created_at: string;
  items: OrderItem[];
}

interface ReceiptModalProps {
  isOpen: boolean;
  onClose: () => void;
  order: Order | null;
}

export default function ReceiptModal({ isOpen, onClose, order }: ReceiptModalProps) {
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    
    if (isOpen) {
      document.addEventListener('keydown', handleEscape);
      document.body.style.overflow = 'hidden';
    }
    
    return () => {
      document.removeEventListener('keydown', handleEscape);
      document.body.style.overflow = 'unset';
    };
  }, [isOpen, onClose]);

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

  if (!isOpen || !order) return null;

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl max-w-md w-full max-h-[90vh] overflow-auto">
        {/* Header - Hidden when printing */}
        <div className="sticky top-0 bg-white border-b border-gray-200 p-4 flex justify-between items-center print:hidden">
          <h2 className="text-xl font-bold text-gray-900">Invoice</h2>
          <div className="flex gap-2">
            <button
              onClick={handlePrint}
              className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              title="Print / Save as PDF"
            >
              <Download className="w-5 h-5 text-gray-700" />
            </button>
            <button
              onClick={onClose}
              className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
            >
              <X className="w-5 h-5 text-gray-700" />
            </button>
          </div>
        </div>

        {/* Receipt Content - Optimized for printing */}
        <div className="p-6 print:p-4" style={{ fontFamily: 'Inter, Roboto, sans-serif' }}>
          {/* Restaurant Name */}
          <div className="text-center mb-6 print:mb-4">
            <h1 className="font-bold text-gray-900" style={{ fontSize: '18px' }}>
              TABLETOP BILLING
            </h1>
            <p className="text-gray-600 text-sm mt-1">Restaurant Invoice</p>
          </div>

          {/* Divider */}
          <div className="border-t border-dashed border-gray-300 mb-4 print:mb-3"></div>

          {/* Invoice Details */}
          <div className="space-y-1 mb-4 print:mb-3" style={{ fontSize: '11px' }}>
            <div className="flex justify-between">
              <span className="text-gray-600">Invoice No:</span>
              <span className="font-medium text-gray-900">#{order.id}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">KOT No:</span>
              <span className="font-medium text-gray-900">#{order.kot_number}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Table:</span>
              <span className="font-medium text-gray-900">{order.table_number}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Date:</span>
              <span className="font-medium text-gray-900">
                {new Date(order.created_at).toLocaleDateString('en-IN')}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Time:</span>
              <span className="font-medium text-gray-900">
                {new Date(order.created_at).toLocaleTimeString('en-IN', {
                  hour: '2-digit',
                  minute: '2-digit'
                })}
              </span>
            </div>
          </div>

          {/* Divider */}
          <div className="border-t border-dashed border-gray-300 mb-4 print:mb-3"></div>

          {/* Items List */}
          <div className="mb-4 print:mb-3">
            <div className="flex justify-between mb-2 print:mb-1 text-gray-600 font-medium" style={{ fontSize: '10px' }}>
              <span>ITEM</span>
              <span>QTY × RATE</span>
            </div>
            {order.items.map((item) => (
              <div key={item.id} className="mb-3 print:mb-2">
                <div className="flex justify-between items-start" style={{ fontSize: '11px' }}>
                  <span className="font-medium text-gray-900 flex-1 pr-2">
                    {item.menu_item_name}
                  </span>
                  <span className="text-gray-600 text-right whitespace-nowrap">
                    {item.quantity} × ₹{item.price}
                  </span>
                </div>
                <div className="flex justify-end mt-0.5">
                  <span className="font-medium text-gray-900" style={{ fontSize: '11px' }}>
                    ₹{item.quantity * item.price}
                  </span>
                </div>
              </div>
            ))}
          </div>

          {/* Divider */}
          <div className="border-t border-gray-300 mb-4 print:mb-3"></div>

          {/* Total */}
          <div className="mb-6 print:mb-4">
            <div className="flex justify-between items-center">
              <span className="font-bold text-gray-900" style={{ fontSize: '16px' }}>
                GRAND TOTAL
              </span>
              <span className="font-bold text-gray-900" style={{ fontSize: '16px' }}>
                ₹{order.total}
              </span>
            </div>
          </div>

          {/* Divider */}
          <div className="border-t border-dashed border-gray-300 mb-4 print:mb-3"></div>

          {/* Thank You Message */}
          <div className="text-center mb-4 print:mb-3">
            <p className="text-gray-900 font-medium" style={{ fontSize: '12px' }}>
              Thank you for dining with us!
            </p>
            <p className="text-gray-600 mt-1" style={{ fontSize: '10px' }}>
              We hope to see you again soon
            </p>
          </div>

          {/* Eco Message */}
          <div className="text-center pt-3 print:pt-2 border-t border-gray-200">
            <p className="text-gray-500" style={{ fontSize: '9px' }}>
              This is a paperless eco bill. Thank you for saving paper 🌱
            </p>
          </div>
        </div>
      </div>

      {/* Print Styles */}
      <style>{`
        @media print {
          body * {
            visibility: hidden;
          }
          .fixed.inset-0 * {
            visibility: visible;
          }
          .fixed.inset-0 {
            position: static;
            background: white;
          }
          .bg-white.rounded-2xl {
            box-shadow: none;
            max-width: 100%;
            width: 100%;
          }
          .print\\:hidden {
            display: none !important;
          }
          .print\\:p-4 {
            padding: 1rem;
          }
          .print\\:mb-1 {
            margin-bottom: 0.25rem;
          }
          .print\\:mb-2 {
            margin-bottom: 0.5rem;
          }
          .print\\:mb-3 {
            margin-bottom: 0.75rem;
          }
          .print\\:mb-4 {
            margin-bottom: 1rem;
          }
          .print\\:pt-2 {
            padding-top: 0.5rem;
          }
          @page {
            size: 80mm auto;
            margin: 5mm;
          }
        }
      `}</style>
    </div>
  );
}
