'use client';

import { useEffect, useRef } from 'react';
import { X, Phone, MessageSquare, User, Zap, FileText, ChevronRight, MapPin, AlertCircle, Edit3, Printer } from 'lucide-react';
import StatusBadge from '@client/components/ui/StatusBadge';
import { useCurrency } from '@client/hooks/useCurrency';
import { toast } from 'sonner';
import { formatOid } from '@client/utils/formatOid';
import { useLanguage } from '@client/contexts/LanguageContext';

export interface OrderItem {
  name: string;
  qty: number;
  price: number;
  modifiers?: string[];
  note?: string;
}

export interface Order {
  id: string;
  orderNumber?: number;
  restaurantId?: string;
  customerName: string;
  customerPhone?: string;
  channel: 'voice' | 'chat';
  status: string;
  items: OrderItem[];
  subtotal: number;
  tax: number;
  total: number;
  aiConfidence?: number | null;
  placedAt: string;
  agentId: string;
  conversationId: string;
  isModified: boolean;
  modificationNote?: string;
  specialInstructions?: string;
  deliveryType: 'dine-in' | 'takeaway' | 'delivery';
  tableNumber?: string;
  deliveryAddress?: string;
  transcriptSummary?: string;
  createdAt?: string;
}

interface OrderDetailModalProps {
  order: Order | null;
  isOpen: boolean;
  onClose: () => void;
  onStatusChange: (orderId: string, status: string) => void;
  onEdit?: (order: Order) => void;
}

const statusOptions = [
  { value: 'processing', label: 'AI Processing', deliveryOnly: false },
  { value: 'confirmed', label: 'Confirmed', deliveryOnly: false },
  { value: 'kitchen', label: 'Sent to Kitchen', deliveryOnly: false },
  { value: 'ready', label: 'Ready', deliveryOnly: false },
  { value: 'rider', label: 'Handover to Rider', deliveryOnly: true },
  { value: 'delivered', label: 'Delivered', deliveryOnly: false },
  { value: 'completed', label: 'Completed', deliveryOnly: false },
  { value: 'cancelled', label: 'Cancelled', deliveryOnly: false },
];

const getConfidenceColor = (score: number) => {
  if (score >= 90) return { color: 'hsl(var(--success))', bg: 'hsl(var(--success-bg))', border: 'hsl(var(--success-border))' };
  if (score >= 70) return { color: 'hsl(var(--warning))', bg: 'hsl(var(--warning-bg))', border: 'hsl(var(--warning-border))' };
  return { color: 'hsl(var(--danger))', bg: 'hsl(var(--danger-bg))', border: 'hsl(var(--danger-border))' };
};

function escapeHtml(str: string): string {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}

function printOrder(order: Order, t: (key: string, fallback: string) => string, fc?: (n: number) => string) {
  const orderId = formatOid(order.orderNumber, order.id, order.restaurantId);
  const printWindow = window.open('', '_blank', 'width=440,height=720,scrollbars=yes');
  if (!printWindow) { toast.error(t('orderManagement.allowPopupsToPrint', 'Please allow pop-ups to print')); return; }

  const fmt = fc || ((n: number) => `$${n.toFixed(2)}`);
  const deliveryLabel = order.deliveryType === 'dine-in' ? t('orderManagement.dineIn', 'Dine-In') : order.deliveryType === 'takeaway' ? t('orderManagement.takeaway', 'Takeaway') : t('orderManagement.delivery', 'Delivery');
  const itemsHtml = order.items.map(i =>
    `<div class="item-row">
      <span class="item-name">${escapeHtml(i.name)}</span>
      <span class="item-qty">×${i.qty}</span>
      <span class="item-price">${fmt(i.price * i.qty)}</span>
    </div>`
  ).join('');

  const html = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>${t('orderManagement.order', 'Order')} #${orderId}</title>
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: 'Courier New', Courier, monospace; font-size: 13px; color: #111; background: #fff; padding: 28px 24px; max-width: 380px; margin: 0 auto; }
    .header { text-align: center; margin-bottom: 18px; }
    .restaurant-name { font-size: 22px; font-weight: bold; letter-spacing: -0.5px; }
    .tagline { font-size: 11px; color: #777; margin-top: 2px; }
    .order-badge { display: inline-block; margin-top: 10px; background: #111; color: #fff; padding: 4px 14px; border-radius: 20px; font-size: 13px; font-weight: bold; letter-spacing: 1px; }
    .meta { font-size: 11px; color: #666; margin-top: 6px; }
    .divider { border: none; border-top: 1px dashed #bbb; margin: 14px 0; }
    .solid-divider { border: none; border-top: 2px solid #111; margin: 14px 0; }
    .section-label { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.12em; color: #888; margin-bottom: 6px; }
    .info-pair { display: flex; justify-content: space-between; margin-bottom: 3px; font-size: 12px; }
    .info-value { font-weight: 600; text-align: right; max-width: 60%; }
    .address { font-size: 12px; color: #444; margin-top: 4px; line-height: 1.5; }
    .item-row { display: flex; align-items: baseline; margin-bottom: 7px; font-size: 13px; }
    .item-name { flex: 1; }
    .item-qty { color: #666; margin: 0 10px; font-size: 11px; }
    .item-price { font-weight: 600; white-space: nowrap; }
    .totals { margin-top: 4px; }
    .totals-row { display: flex; justify-content: space-between; margin-bottom: 4px; font-size: 13px; }
    .totals-row.grand { font-weight: bold; font-size: 16px; border-top: 2px solid #111; padding-top: 8px; margin-top: 4px; }
    .instructions { font-size: 12px; color: #444; line-height: 1.5; background: #f5f5f5; border-left: 3px solid #ddd; padding: 8px 10px; border-radius: 4px; }
    .footer { text-align: center; margin-top: 24px; font-size: 11px; color: #999; line-height: 1.6; }
    @media print {
      body { padding: 12px; }
      .no-print { display: none; }
    }
  </style>
</head>
<body>
  <div class="header">
    <div class="restaurant-name">🍽️ ${t('orderManagement.restaurant', 'Restaurant')}</div>
    <div class="tagline">${t('orderManagement.poweredByRestroAgent', 'Powered by RestroAgent')}</div>
    <div class="order-badge">#${orderId}</div>
    <div class="meta">${t('orderManagement.placed', 'Placed')}: ${escapeHtml(order.placedAt)}</div>
    <div class="meta">${t('orderManagement.printed', 'Printed')}: ${new Date().toLocaleString()}</div>
  </div>

  <hr class="solid-divider">

  <div class="section-label">${t('orderManagement.customer', 'Customer')}</div>
  <div class="info-pair"><span>${escapeHtml(order.customerName)}</span>${order.customerPhone ? `<span class="info-value">${escapeHtml(order.customerPhone)}</span>` : ''}</div>

  <hr class="divider">

  <div class="section-label">${t('orderManagement.orderType', 'Order Type')}</div>
  <div class="info-pair"><span>${escapeHtml(deliveryLabel)}</span>${order.tableNumber ? `<span class="info-value">${t('orderManagement.table', 'Table')} ${escapeHtml(order.tableNumber)}</span>` : ''}</div>
  ${order.deliveryAddress ? `<div class="address">📍 ${escapeHtml(order.deliveryAddress)}</div>` : ''}

  <hr class="divider">

  <div class="section-label">${t('orderManagement.items', 'Items')}</div>
  ${itemsHtml}

  <hr class="divider">

  <div class="totals">
    <div class="totals-row"><span>${t('orderManagement.subtotal', 'Subtotal')}</span><span>${fmt(order.subtotal)}</span></div>
    <div class="totals-row"><span>${t('orderManagement.tax', 'Tax')} (8%)</span><span>${fmt(order.tax)}</span></div>
    <div class="totals-row grand"><span>${t('orderManagement.total', 'TOTAL')}</span><span>${fmt(order.total)}</span></div>
  </div>

  ${order.specialInstructions ? `
  <hr class="divider">
  <div class="section-label">${t('orderManagement.specialInstructions', 'Special Instructions')}</div>
  <div class="instructions">${escapeHtml(order.specialInstructions)}</div>` : ''}

  <div class="footer">
    ${t('orderManagement.thankYouForOrder', 'Thank you for your order!')}<br>
    ${t('orderManagement.haveGreatMeal', 'Have a great meal 🙏')}
  </div>

  <script>window.addEventListener('load', function() { setTimeout(function() { window.print(); }, 300); });<\/script>
</body>
</html>`;

  printWindow.document.write(html);
  printWindow.document.close();
}

export default function OrderDetailModal({ order, isOpen, onClose, onStatusChange, onEdit }: OrderDetailModalProps) {
  const overlayRef = useRef<HTMLDivElement>(null);
  const { format: fc } = useCurrency();
  const { t } = useLanguage();

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [isOpen]);

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

  const hasConfidence = order.aiConfidence != null && order.aiConfidence > 0;
  const confScore = order.aiConfidence ?? 0;
  const confColors = getConfidenceColor(hasConfidence ? confScore : 100);

  const shortId = (id: string) => id ? id.slice(0, 8).toUpperCase() : '—';
  const orderId = formatOid(order.orderNumber, order.id, order.restaurantId);
  const handlePrint = () => printOrder(order, t, fc);
  const handleEdit = () => {
    if (onEdit) {
      onEdit(order);
      onClose();
    }
  };

  return (
    <div
      ref={overlayRef}
      className="fixed inset-0 z-50 flex items-start justify-end"
      style={{ backgroundColor: 'rgba(0,0,0,0.4)' }}
      onClick={(e) => { if (e.target === overlayRef.current) onClose(); }}
    >
      <div
        className="h-full w-full max-w-lg overflow-y-auto scrollbar-thin slide-in-right"
        style={{
          backgroundColor: 'hsl(var(--surface))',
          borderLeft: '1px solid hsl(var(--border))',
          boxShadow: 'var(--shadow-xl)',
        }}
      >
        {/* Header */}
        <div
          className="sticky top-0 z-10 flex items-center justify-between px-6 py-4"
          style={{
            backgroundColor: 'hsl(var(--surface))',
            borderBottom: '1px solid hsl(var(--border))',
          }}
        >
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-base font-bold" style={{ color: 'hsl(var(--foreground))' }}>
                {orderId}
              </h2>
              <StatusBadge status={order.status} />
            </div>
            <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('orderManagement.placed', 'Placed')} {order.placedAt}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <button onClick={handlePrint} className="btn-ghost p-2" title={t('orderManagement.printOrder', 'Print order')}>
              <Printer size={16} />
            </button>
            <button onClick={handleEdit} className="btn-ghost p-2" title={t('orderManagement.editOrder', 'Edit order')}>
              <Edit3 size={16} />
            </button>
            <button onClick={onClose} className="btn-ghost p-2" title={t('orderManagement.close', 'Close')}>
              <X size={16} />
            </button>
          </div>
        </div>

        <div className="px-6 py-5 space-y-5">
          {/* AI Confidence banner */}
          <div
            className="flex items-center justify-between p-3 rounded-xl"
            style={{
              backgroundColor: confColors.bg,
              border: `1px solid ${confColors.border}`,
            }}
          >
            <div className="flex items-center gap-2">
              <Zap size={15} style={{ color: confColors.color }} />
              <span className="text-sm font-semibold" style={{ color: confColors.color }}>
                {t('orderManagement.aiConfidenceScore', 'AI Confidence Score')}
              </span>
            </div>
            {hasConfidence ? (
              <div className="flex items-center gap-3">
                <div className="w-24 h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: 'hsl(var(--border))' }}>
                  <div
                    className="h-full rounded-full"
                    style={{ width: `${confScore}%`, backgroundColor: confColors.color }}
                  />
                </div>
                <span className="font-mono font-bold tabular-nums text-sm" style={{ color: confColors.color }}>
                  {confScore}%
                </span>
              </div>
            ) : (
              <span className="text-xs font-semibold px-2.5 py-1 rounded-full" style={{ backgroundColor: confColors.color + '22', color: confColors.color }}>
                {order.channel === 'voice' ? t('orderManagement.voiceOrder', 'Voice Order') : t('orderManagement.na', 'N/A')}
              </span>
            )}
          </div>

          {/* Modification warning */}
          {order.isModified && (
            <div
              className="flex items-start gap-2 p-3 rounded-xl"
              style={{ backgroundColor: 'hsl(var(--warning-bg))', border: '1px solid hsl(var(--warning-border))' }}
            >
              <AlertCircle size={15} className="shrink-0 mt-0.5" style={{ color: 'hsl(var(--warning))' }} />
              <div>
                <p className="text-xs font-semibold" style={{ color: 'hsl(var(--warning))' }}>
                  {t('orderManagement.orderModifiedAfterAI', 'Order was modified after AI confirmation')}
                </p>
                {order.modificationNote && (
                  <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                    {order.modificationNote}
                  </p>
                )}
              </div>
            </div>
          )}

          {/* Customer & channel */}
          <div className="grid grid-cols-2 gap-3">
            <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
              <p className="text-xs mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('orderManagement.customer', 'Customer')}</p>
              <div className="flex items-center gap-2">
                <User size={14} style={{ color: 'hsl(var(--foreground-secondary))' }} />
                <p className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{order.customerName}</p>
              </div>
              {order.customerPhone && (
                <p className="text-xs font-mono mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{order.customerPhone}</p>
              )}
            </div>
            <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
              <p className="text-xs mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('orderManagement.channel', 'Channel')}</p>
              <div className="flex items-center gap-2">
                {order.channel === 'voice'
                  ? <Phone size={14} style={{ color: 'hsl(var(--primary))' }} />
                  : <MessageSquare size={14} style={{ color: 'hsl(var(--info))' }} />
                }
                <p className="text-sm font-semibold capitalize" style={{ color: 'hsl(var(--foreground))' }}>
                  {order.channel === 'voice' ? t('orderManagement.voice', 'voice') : t('orderManagement.chat', 'chat')}
                </p>
              </div>
              <p className="text-xs font-mono mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {t('orderManagement.session', 'Session')}: {order.conversationId ? shortId(order.conversationId) : '—'}
              </p>
            </div>
          </div>

          {/* Delivery type */}
          <div className="flex items-center gap-2">
            <MapPin size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
            <span className="text-sm font-medium capitalize" style={{ color: 'hsl(var(--foreground))' }}>
              {order.deliveryType === 'dine-in' ? t('orderManagement.dineIn', 'dine-in') : order.deliveryType === 'takeaway' ? t('orderManagement.takeaway', 'takeaway') : t('orderManagement.delivery', 'delivery')}
            </span>
            {order.tableNumber && (
              <span className="badge badge-neutral">{t('orderManagement.table', 'Table')} {order.tableNumber}</span>
            )}
          </div>
          {order.deliveryAddress && (
            <div className="flex items-start gap-2">
              <MapPin size={14} style={{ color: 'hsl(var(--muted-foreground))', marginTop: 2 }} />
              <div>
                <p className="text-xs font-semibold mb-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('orderManagement.deliveryAddress', 'Delivery Address')}</p>
                <p className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>{order.deliveryAddress}</p>
              </div>
            </div>
          )}

          {/* Order items */}
          <div>
            <p className="section-label mb-3">{t('orderManagement.orderItems', 'Order Items')}</p>
            <div
              className="rounded-xl overflow-hidden"
              style={{ border: '1px solid hsl(var(--border))' }}
            >
              {order.items.map((item, idx) => (
                <div
                  key={idx}
                  className={`flex items-start justify-between px-4 py-3 ${idx < order.items.length - 1 ? 'border-b' : ''}`}
                  style={{ borderColor: 'hsl(var(--border))' }}
                >
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span
                        className="w-5 h-5 rounded-full flex items-center justify-center text-xs font-bold shrink-0"
                        style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}
                      >
                        {item.qty}
                      </span>
                      <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>
                        {item.name}
                      </p>
                    </div>
                    {item.modifiers && item.modifiers.length > 0 && (
                      <p className="text-xs mt-0.5 ml-7" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {item.modifiers.join(' · ')}
                      </p>
                    )}
                    {item.note && (
                      <p className="text-xs mt-0.5 ml-7 italic" style={{ color: 'hsl(var(--warning))' }}>
                        {t('orderManagement.note', 'Note')}: {item.note}
                      </p>
                    )}
                  </div>
                  <span className="text-sm font-semibold font-mono tabular-nums ml-4 shrink-0" style={{ color: 'hsl(var(--foreground))' }}>
                    {fc(item.price * item.qty)}
                  </span>
                </div>
              ))}

              {/* Totals */}
              <div className="px-4 py-3 space-y-1.5" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                <div className="flex justify-between text-sm">
                  <span style={{ color: 'hsl(var(--muted-foreground))' }}>{t('orderManagement.subtotal', 'Subtotal')}</span>
                  <span className="font-mono tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{fc(order.subtotal)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span style={{ color: 'hsl(var(--muted-foreground))' }}>{t('orderManagement.tax', 'Tax')} (8%)</span>
                  <span className="font-mono tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{fc(order.tax)}</span>
                </div>
                <div
                  className="flex justify-between text-sm font-bold pt-1.5"
                  style={{ borderTop: '1px solid hsl(var(--border))' }}
                >
                  <span style={{ color: 'hsl(var(--foreground))' }}>{t('orderManagement.total', 'Total')}</span>
                  <span className="font-mono tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{fc(order.total)}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Special instructions */}
          {order.specialInstructions && (
            <div
              className="p-3 rounded-xl"
              style={{ backgroundColor: 'hsl(var(--warning-bg))', border: '1px solid hsl(var(--warning-border))' }}
            >
              <p className="text-xs font-semibold mb-1" style={{ color: 'hsl(var(--warning))' }}>
                {t('orderManagement.specialInstructions', 'Special Instructions')}
              </p>
              <p className="text-sm" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                {order.specialInstructions}
              </p>
            </div>
          )}

          {/* AI transcript summary */}
          {order.transcriptSummary && (
            <div>
              <p className="section-label mb-2">{t('orderManagement.aiConversationSummary', 'AI Conversation Summary')}</p>
              <div
                className="p-3 rounded-xl"
                style={{ backgroundColor: 'hsl(var(--info-bg))', border: '1px solid hsl(var(--info-border))' }}
              >
                <div className="flex items-center gap-2 mb-1.5">
                  <FileText size={13} style={{ color: 'hsl(var(--info))' }} />
                  <span className="text-xs font-semibold" style={{ color: 'hsl(var(--info))' }}>
                    {t('orderManagement.session', 'Session')} {order.conversationId ? shortId(order.conversationId) : '—'}
                  </span>
                </div>
                <p className="text-xs leading-relaxed" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                  {order.transcriptSummary}
                </p>
                <button
                  className="mt-2 text-xs font-semibold flex items-center gap-1"
                  style={{ color: 'hsl(var(--info))' }}
                  onClick={() => toast.info(t('orderManagement.openingFullTranscript', 'Opening full transcript viewer'))}
                >
                  {t('orderManagement.viewFullTranscript', 'View full transcript')} <ChevronRight size={11} />
                </button>
              </div>
            </div>
          )}

          {/* Update status */}
          <div>
            <p className="section-label mb-2">{t('orderManagement.updateStatus', 'Update Status')}</p>
            <div className="grid grid-cols-2 gap-2">
              {statusOptions
                .filter(s => s.deliveryOnly ? order.deliveryType === 'delivery' : true)
                .map((s) => (
                <button
                  key={s.value}
                  onClick={() => {
                    onStatusChange(order.id, s.value);
                    toast.success(t('orderManagement.orderStatusUpdated', 'Order {orderId} status updated to {status}').replace('{orderId}', orderId).replace('{status}', t(`orderManagement.status.${s.value}`, s.label)));
                    onClose();
                  }}
                  className={`px-3 py-2 rounded-lg text-xs font-semibold text-left transition-all duration-150 hover:scale-[1.02] active:scale-[0.98] ${
                    order.status === s.value ? 'ring-2 ring-primary' : ''
                  }`}
                  style={{
                    backgroundColor: order.status === s.value ? 'hsl(var(--primary-light))' : 'hsl(var(--muted))',
                    color: order.status === s.value ? 'hsl(var(--primary))' : 'hsl(var(--foreground-secondary))',
                    border: `1px solid ${order.status === s.value ? 'hsl(var(--primary))' : 'hsl(var(--border))'}`,
                  }}
                >
                  {t(`orderManagement.status.${s.value}`, s.label)}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
