import React, { useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useFiestaOrderDetails } from '../services/fiestaQueries';
import { num as fnum, str as fstr, type Row } from '../services/fiestaApi';
import { X, Calendar, MapPin, Loader2, CreditCard } from 'lucide-react';
import './OrderDetailsModal.css';

interface OrderDetailsModalProps {
  order: Row;
  onClose: () => void;
}

function formatDate(dateStr: string): string {
  if (!dateStr) return '';
  const d = new Date(dateStr);
  if (isNaN(d.getTime())) return dateStr;
  return new Intl.DateTimeFormat('en-IN', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
    hour12: true
  }).format(d);
}

function getStatusClass(status: string): string {
  switch (status.toLowerCase()) {
    case 'created': return 'odm-status-created';
    case 'pending': return 'odm-status-pending';
    case 'delivered': return 'odm-status-delivered';
    case 'cancelled': return 'odm-status-cancelled';
    default: return 'odm-status-created';
  }
}

export default function OrderDetailsModal({ order, onClose }: OrderDetailsModalProps) {
  // Prevent background scroll
  useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  const orderId = fstr(order.orderid) || String(fnum(order.orderheaderid));
  const orderDate = formatDate(fstr(order.createddate) || fstr(order.orderdate) || '');
  const statusStr = fstr(order.orderstatus) || 'CREATED';
  const statusBadgeClass = getStatusClass(statusStr);
  
  const paymentMode = fstr(order.paymentmode) || 'Not specified';
  const grandTotal = fnum(order.totalamount) || fnum(order.payableamount) || 0;
  
  const subtotal = fnum(order.subtotal) || grandTotal;
  const tax = fnum(order.tax) || 0;
  const discount = fnum(order.discount) || 0;
  const deliveryFee = fnum(order.deliveryfee) || fnum(order.deliverycharge) || 0;
  const address = fstr(order.shippingaddress) || fstr(order.address) || 'No address provided';

  const { data: details, isLoading } = useFiestaOrderDetails(order.orderheaderid);

  return createPortal(
    <div className="odm-overlay">
      <div className="odm-backdrop" onClick={onClose} />
      
      <div className="odm-card">
        {/* Header */}
        <div className="odm-header">
          <div className="odm-header-top">
            <div className="odm-title-area">
              <span className="odm-eyebrow">Order Details</span>
              <div className="odm-title">{orderId}</div>
              <div className="odm-date">
                <Calendar size={14} />
                {orderDate}
              </div>
            </div>
            <button className="odm-close-btn" onClick={onClose}>
              <X size={18} />
            </button>
          </div>
          
          <div className="odm-status-row">
            <div className={`odm-status-badge ${statusBadgeClass}`}>
              {statusStr}
            </div>
          </div>
        </div>

        {/* Body */}
        <div className="odm-body">
          {isLoading ? (
            <div className="odm-loading">
              <Loader2 size={32} className="animate-spin" />
              <span>Fetching order details...</span>
            </div>
          ) : (
            <>
              <div className="odm-section-title">Order Items</div>
              <table className="odm-items-table">
                <thead>
                  <tr>
                    <th>Item</th>
                    <th className="text-right">Price</th>
                    <th className="text-right">Qty</th>
                    <th className="text-right">Total</th>
                  </tr>
                </thead>
                <tbody>
                  {details && details.length > 0 ? (
                    details.map((item, i) => {
                      const name = fstr(item.productname) || fstr(item.itemname) || 'Item';
                      const qty = fnum(item.quantity) || fnum(item.qty) || 1;
                      const price = fnum(item.price) || fnum(item.unitprice) || fnum(item.retailprice) || 0;
                      const lineTotal = fnum(item.amount) || fnum(item.productsumprice) || (qty * price);
                      return (
                        <tr key={i}>
                          <td>
                            <div className="odm-item-name">{name}</div>
                          </td>
                          <td className="text-right text-slate-500">₹{price.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</td>
                          <td className="text-right text-slate-500">x{qty}</td>
                          <td className="text-right font-bold text-slate-800">₹{lineTotal.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</td>
                        </tr>
                      );
                    })
                  ) : (
                    <tr>
                      <td colSpan={4} className="text-center text-slate-400 py-4">No line items found.</td>
                    </tr>
                  )}
                </tbody>
              </table>

              <div className="odm-totals-section">
                <div className="odm-total-row">
                  <span>Subtotal</span>
                  <span>₹{subtotal.toLocaleString('en-IN')}</span>
                </div>
                {(tax > 0) && (
                  <div className="odm-total-row">
                    <span>Tax</span>
                    <span>₹{tax.toLocaleString('en-IN')}</span>
                  </div>
                )}
                {(deliveryFee > 0) && (
                  <div className="odm-total-row">
                    <span>Delivery Fee</span>
                    <span>₹{deliveryFee.toLocaleString('en-IN')}</span>
                  </div>
                )}
                {(discount > 0) && (
                  <div className="odm-total-row text-emerald-600">
                    <span>Discount</span>
                    <span>-₹{discount.toLocaleString('en-IN')}</span>
                  </div>
                )}
                <div className="odm-total-row grand-total">
                  <span>Grand Total</span>
                  <span>₹{grandTotal.toLocaleString('en-IN')}</span>
                </div>
              </div>

              <div className="odm-info-grid">
                <div className="odm-info-card">
                  <div className="odm-info-icon"><CreditCard size={16} /></div>
                  <div className="odm-info-label">Payment Method</div>
                  <div className="odm-info-value capitalize">{paymentMode}</div>
                </div>
                <div className="odm-info-card">
                  <div className="odm-info-icon"><MapPin size={16} /></div>
                  <div className="odm-info-label">Delivery Address</div>
                  <div className="odm-info-value leading-tight">{address}</div>
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </div>,
    document.body
  );
}
