'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Package, Phone, Bot, Edit2, ChevronRight, Loader2, Gift, Star } from 'lucide-react';
import { getOrder, updateOrder, type Order } from '@client/api/orders';
import { toast } from 'sonner';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

const orderStatuses = ['placed', 'confirmed', 'preparing', 'ready', 'delivered'];

const statusMap: Record<string, string> = {
  pending: 'placed',
  confirmed: 'confirmed',
  kitchen: 'preparing',
  ready: 'ready',
  completed: 'delivered',
  cancelled: 'cancelled',
};

const reverseStatusMap: Record<string, string> = {
  placed: 'pending',
  confirmed: 'confirmed',
  preparing: 'kitchen',
  ready: 'ready',
  delivered: 'completed',
};

export default function OrderDetailPage() {
  const { t } = useLanguage();
  usePageHeader(t('orderManagement.details_title', "Order Details"), t('orderManagement.loading', "Loading..."));
  const params = useParams();
  const id = params?.id as string;
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);
  const [status, setStatus] = useState('');

  useEffect(() => {
    if (!id) return;
    setLoading(true);
    getOrder(id)
      .then(res => {
        setOrder(res.order);
        setStatus(statusMap[res.order.status] ?? res.order.status);
      })
      .catch(() => toast.error(t('orderManagement.load_error', 'Failed to load order')))
      .finally(() => setLoading(false));
  }, [id]);

  const handleStatusChange = async (newDisplayStatus: string) => {
    setStatus(newDisplayStatus);
    const dbStatus = reverseStatusMap[newDisplayStatus];
    if (dbStatus && order) {
      try {
        const res = await updateOrder(order.id, { status: dbStatus });
        setOrder(res.order);
        setStatus(statusMap[res.order.status] ?? res.order.status);
        toast.success(t('orderManagement.status_updated', `Order status updated to ${newDisplayStatus}`));
      } catch {
        toast.error(t('orderManagement.update_status_error', 'Failed to update status'));
      }
    }
  };

  if (loading) {
    return (
      <>
        <div className="flex items-center justify-center py-20">
          <Loader2 className="animate-spin" size={24} style={{ color: 'hsl(var(--primary))' }} />
        </div>
      </>
    );
  }

  if (!order) {
    return (
      <>
        <div className="text-center py-20">
          <p className="text-lg font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('orderManagement.not_found', 'Order not found')}</p>
          <Link href="/order-management" className="btn-primary mt-4 inline-flex">{t('orderManagement.back_to_list', 'Back to Orders')}</Link>
        </div>
      </>
    );
  }

  const currentIdx = orderStatuses.indexOf(status);
  const items = order.items ?? [];
  const subtotal = items.reduce((sum, it) => sum + (it.price * it.quantity), 0);
  const tax = subtotal * 0.1;
  const discount = Number(order.discountAmount ?? 0);
  const loyaltyDiscount = Number(order.loyaltyDiscount ?? 0);
  const loyaltyPointsRedeemed = Number(order.loyaltyPointsRedeemed ?? 0);
  const loyaltyPointsEarned = Number(order.loyaltyPointsEarned ?? 0);
  const giftCardApplied = Number(order.giftCardApplied ?? 0);
  const giftCardRemaining = order.giftCardRemainingBalance;
  const total = order.total ?? Math.max(0, subtotal - discount - loyaltyDiscount - giftCardApplied) + tax;
  const isCommittedStatus = order.status === 'completed' || order.status === 'delivered';
  const isCancelled = order.status === 'cancelled';
  const placedAt = new Date(order.createdAt).toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' });

  return (
    <>
      <div className="flex items-center gap-3 mb-6">
        <Link href="/order-management" className="btn-ghost p-1.5"><ArrowLeft size={16} /></Link>
        <div className="flex items-center gap-2">
          <span className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>{order.id}</span>
          <span className="badge badge-warning capitalize">{status}</span>
        </div>
        <div className="ml-auto flex gap-2">
          <button className="btn-secondary"><Edit2 size={14} /> {t('orderManagement.edit_order', 'Edit Order')}</button>
        </div>
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <div className="lg:col-span-2 space-y-5">
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('orderManagement.order_status', 'Order Status')}</h3>
            <div className="flex items-center gap-0">
              {orderStatuses.map((s, idx) => {
                const isDone = idx <= currentIdx;
                const isActive = idx === currentIdx;
                return (
                  <div key={s} className="flex items-center flex-1">
                    <div className="flex flex-col items-center">
                      <div
                        className="w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition-all"
                        style={{
                          backgroundColor: isDone ? 'hsl(var(--primary))' : 'hsl(var(--muted))',
                          color: isDone ? 'white' : 'hsl(var(--muted-foreground))',
                          transform: isActive ? 'scale(1.15)' : 'scale(1)',
                          boxShadow: isActive ? '0 0 0 3px hsl(var(--primary) / 0.2)' : 'none',
                        }}
                      >
                        {idx + 1}
                      </div>
                      <span className="text-xs mt-1 capitalize text-center" style={{ color: isDone ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))' }}>{s}</span>
                    </div>
                    {idx < orderStatuses.length - 1 && (
                      <div className="flex-1 h-0.5 mx-1 mb-4" style={{ backgroundColor: idx < currentIdx ? 'hsl(var(--primary))' : 'hsl(var(--border))' }} />
                    )}
                  </div>
                );
              })}
            </div>
            <div className="flex gap-2 mt-4 flex-wrap">
              {orderStatuses.map(s => (
                <button
                  key={s}
                  onClick={() => handleStatusChange(s)}
                  className={`text-xs px-3 py-1.5 rounded-lg border capitalize transition-all ${status === s ? 'btn-primary' : 'btn-secondary'}`}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>

          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('orderManagement.order_items', 'Order Items')}</h3>
            {items.length === 0 ? (
              <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('orderManagement.no_items', 'No items in this order')}</p>
            ) : (
              <div className="space-y-3">
                {items.map((item, idx) => (
                  <div key={idx} className="flex items-center justify-between py-2" style={{ borderBottom: idx < items.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 rounded-lg flex items-center justify-center font-bold text-sm" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
                        {item.quantity}x
                      </div>
                      <div>
                        <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{item.name}</p>
                        {item.notes && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{item.notes}</p>}
                      </div>
                    </div>
                    <span className="font-semibold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>${(item.price * item.quantity).toFixed(2)}</span>
                  </div>
                ))}
              </div>
            )}
            <div className="mt-4 pt-4 space-y-1.5" style={{ borderTop: '1px solid hsl(var(--border))' }}>
              <div className="flex justify-between text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
                <span>{t('orderManagement.subtotal', 'Subtotal')}</span><span>${subtotal.toFixed(2)}</span>
              </div>
              <div className="flex justify-between text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
                <span>{t('orderManagement.tax', 'Tax (10%)')}</span><span>${tax.toFixed(2)}</span>
              </div>
              {order.couponCode && discount > 0 && (
                <div className="flex justify-between text-sm" style={{ color: 'hsl(var(--success, 142 71% 35%))' }}>
                  <span>{t('orderManagement.coupon', 'Coupon')} ({order.couponCode})</span>
                  <span>-${discount.toFixed(2)}</span>
                </div>
              )}
              {loyaltyDiscount > 0 && (
                <div className="flex justify-between text-sm" style={{ color: 'hsl(var(--success, 142 71% 35%))' }}>
                  <span className="inline-flex items-center gap-1">
                    <Gift size={12} />
                    {t('orderManagement.loyaltyPoints', 'Loyalty points')}
                    {loyaltyPointsRedeemed > 0 && ` (${loyaltyPointsRedeemed} pts)`}
                  </span>
                  <span>-${loyaltyDiscount.toFixed(2)}</span>
                </div>
              )}
              {giftCardApplied > 0 && (
                <div className="flex justify-between text-sm" style={{ color: 'hsl(217 91% 50%)' }}>
                  <span>{t('orderManagement.giftCard', 'Gift card')}</span>
                  <span>-${giftCardApplied.toFixed(2)}</span>
                </div>
              )}
              <div className="flex justify-between font-bold text-base pt-1" style={{ color: 'hsl(var(--foreground))' }}>
                <span>{giftCardApplied > 0 ? t('orderManagement.totalPaid', 'Total paid') : t('orderManagement.total', 'Total')}</span>
                <span>${total.toFixed(2)}</span>
              </div>
              {giftCardApplied > 0 && giftCardRemaining != null && (
                <div className="flex justify-between text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <span>{t('orderManagement.giftCardBalance', 'Gift card balance')}</span>
                  <span>${Number(giftCardRemaining).toFixed(2)}</span>
                </div>
              )}
              {(loyaltyPointsEarned > 0 || (loyaltyPointsRedeemed > 0 && !isCancelled)) && (
                <div
                  className="mt-3 p-3 rounded-lg flex items-start gap-2"
                  style={{ backgroundColor: 'hsl(var(--primary-light))', border: '1px solid hsl(var(--primary) / 0.25)' }}
                >
                  <Star size={14} className="shrink-0 mt-0.5" style={{ color: 'hsl(var(--primary))' }} />
                  <div className="text-xs space-y-0.5" style={{ color: 'hsl(var(--primary))' }}>
                    {loyaltyPointsEarned > 0 ? (
                      <p className="font-semibold">
                        {isCommittedStatus
                          ? t('orderManagement.pointsEarned', `+${loyaltyPointsEarned} points earned`, { points: loyaltyPointsEarned })
                          : t('orderManagement.pointsProjected', `+${loyaltyPointsEarned} points (credited on completion)`, { points: loyaltyPointsEarned })}
                      </p>
                    ) : !isCancelled && !isCommittedStatus ? (
                      <p className="font-semibold">{t('orderManagement.pointsAfterCompletion', 'Points will be credited once the order is completed.')}</p>
                    ) : null}
                    {loyaltyPointsRedeemed > 0 && (
                      <p>{t('orderManagement.pointsRedeemed', `${loyaltyPointsRedeemed} points redeemed on this order`, { points: loyaltyPointsRedeemed })}</p>
                    )}
                  </div>
                </div>
              )}
            </div>
            {order.modificationNote && (
              <div className="mt-4 p-3 rounded-lg" style={{ backgroundColor: 'hsl(var(--warning-bg))', border: '1px solid hsl(var(--warning-border))' }}>
                <p className="text-xs font-semibold mb-0.5" style={{ color: 'hsl(var(--warning))' }}>{t('orderManagement.special_note', 'Special Note')}</p>
                <p className="text-xs" style={{ color: 'hsl(var(--foreground))' }}>{order.modificationNote}</p>
              </div>
            )}
          </div>
        </div>

        <div className="space-y-5">
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('orderManagement.customer', 'Customer')}</h3>
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-full flex items-center justify-center text-white font-bold" style={{ background: 'linear-gradient(135deg, hsl(var(--primary)), hsl(22, 89%, 36%))' }}>
                {order.customerName?.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase()}
              </div>
              <div>
                <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{order.customerName}</p>
              </div>
            </div>
            <div className="space-y-2 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {order.customerPhone && (
                <div className="flex items-center gap-2"><Phone size={12} /> {order.customerPhone}</div>
              )}
              <div className="flex items-center gap-2"><Package size={12} /> {order.channel}</div>
            </div>
            {order.customerId && (
              <Link href={`/customers/${order.customerId}`} className="btn-secondary w-full justify-center mt-3 text-xs py-1.5">
                {t('orderManagement.view_full_profile', 'View Full Profile')} <ChevronRight size={12} />
              </Link>
            )}
          </div>

          <div className="card p-5">
            <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('orderManagement.order_info', 'Order Info')}</h3>
            <div className="space-y-2 text-xs">
              {[
                { label: t('orderManagement.order_id', 'Order ID'), value: order.id },
                { label: t('orderManagement.placed', 'Placed'), value: placedAt },
                { label: t('orderManagement.channel', 'Channel'), value: order.channel },
                { label: t('orderManagement.branch', 'Branch'), value: order.branchId ?? t('orderManagement.branch_default', 'Default') },
              ].map(item => (
                <div key={item.label} className="flex justify-between">
                  <span style={{ color: 'hsl(var(--muted-foreground))' }}>{item.label}</span>
                  <span className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{item.value}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
