'use client';

import Link from 'next/link';
import { useCallback, useEffect, useRef, useState } from 'react';
import { ordersApi, type StaleOrderNotification } from '@/lib/api-client';

const POLL_INTERVAL_MS = 5 * 60 * 1000;

function ageLabel(hours: number): string {
  if (hours < 48) return `${hours} h sin cambiar`;
  const days = Math.floor(hours / 24);
  return `${days} ${days === 1 ? 'día' : 'días'} sin cambiar`;
}

function money(cents: number): string {
  return new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR' }).format(cents / 100);
}

type AwaitingPaymentItem = { id: string; totalCents: number; customerEmail: string | null; createdAt: string };

export function OrderNotifications() {
  const [open, setOpen] = useState(false);
  const [staleItems, setStaleItems] = useState<StaleOrderNotification[]>([]);
  const [staleTotal, setStaleTotal] = useState(0);
  const [awaitingItems, setAwaitingItems] = useState<AwaitingPaymentItem[]>([]);
  const [awaitingTotal, setAwaitingTotal] = useState(0);
  const [tab, setTab] = useState<'pending' | 'awaiting'>('pending');
  const [loading, setLoading] = useState(true);
  const rootRef = useRef<HTMLDivElement>(null);

  const load = useCallback(async () => {
    try {
      const [staleData, awaitingData] = await Promise.all([
        ordersApi.staleNotifications(24, 20),
        ordersApi.awaitingPaymentNotifications(),
      ]);
      setStaleItems(staleData.items);
      setStaleTotal(staleData.total);
      setAwaitingItems(awaitingData.items);
      setAwaitingTotal(awaitingData.total);
    } catch { /* silent */ }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { void load(); void setInterval(load, POLL_INTERVAL_MS); }, [load]);

  useEffect(() => {
    if (!open) return;
    void load();
    const close = (event: MouseEvent) => { if (!rootRef.current?.contains(event.target as Node)) setOpen(false); };
    const key = (event: KeyboardEvent) => { if (event.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', close);
    document.addEventListener('keydown', key);
    return () => { document.removeEventListener('mousedown', close); document.removeEventListener('keydown', key); };
  }, [open, load]);

  const grandTotal = staleTotal + awaitingTotal;
  const pendingItems = staleItems.filter(i => i.state === 'PENDING');
  const shippedItems = staleItems.filter(i => i.state === 'SHIPPED');

  const TabPending = () => (
    <div>
      {loading ? (
        <p className="p-6 text-center text-sm text-gray-500">Cargando…</p>
      ) : pendingItems.length === 0 && shippedItems.length === 0 ? (
        <p className="p-6 text-center text-sm text-gray-500">No hay pedidos pendientes o atrasados.</p>
      ) : (
        <>
          {pendingItems.length > 0 && (
            <div>
              <p className="px-4 py-2 text-xs font-semibold text-amber-600 bg-amber-50 border-b border-amber-100">
                📦 {pendingItems.length} pendientes de procesar
              </p>
              {pendingItems.map((item) => (
                <Link key={item.id} href={`/orders/${item.id}`} onClick={() => setOpen(false)}
                  className="block border-b border-gray-100 px-4 py-3 last:border-0 hover:bg-gray-50">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="truncate text-sm font-semibold text-gray-900">Pedido #{item.id.slice(0, 8)}</p>
                      <p className="truncate text-xs text-gray-500">{item.customerEmail || 'Sin email'}</p>
                    </div>
                    <span className="shrink-0 rounded-full bg-amber-100 px-2 py-1 text-[11px] font-semibold text-amber-800">Pendiente</span>
                  </div>
                  <div className="mt-2 flex justify-between text-xs">
                    <span className="font-medium text-[#E76F51]">{ageLabel(item.ageHours)}</span>
                    <span className="text-gray-600">{money(item.totalCents)}</span>
                  </div>
                </Link>
              ))}
            </div>
          )}
          {shippedItems.length > 0 && (
            <div>
              <p className="px-4 py-2 text-xs font-semibold text-blue-600 bg-blue-50 border-b border-blue-100">
                🚚 {shippedItems.length} en tránsito sin actualizar
              </p>
              {shippedItems.map((item) => (
                <Link key={item.id} href={`/orders/${item.id}`} onClick={() => setOpen(false)}
                  className="block border-b border-gray-100 px-4 py-3 last:border-0 hover:bg-gray-50">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="truncate text-sm font-semibold text-gray-900">Pedido #{item.id.slice(0, 8)}</p>
                      <p className="truncate text-xs text-gray-500">{item.customerEmail || 'Sin email'}</p>
                    </div>
                    <span className="shrink-0 rounded-full bg-blue-100 px-2 py-1 text-[11px] font-semibold text-blue-800">Enviado</span>
                  </div>
                  <div className="mt-2 flex justify-between text-xs">
                    <span className="font-medium text-[#E76F51]">{ageLabel(item.ageHours)}</span>
                    <span className="text-gray-600">{money(item.totalCents)}</span>
                  </div>
                </Link>
              ))}
            </div>
          )}
        </>
      )}
    </div>
  );

  const TabAwaiting = () => (
    <div>
      {loading ? (
        <p className="p-6 text-center text-sm text-gray-500">Cargando…</p>
      ) : awaitingItems.length === 0 ? (
        <p className="p-6 text-center text-sm text-gray-500">No hay pagos pendientes.</p>
      ) : (
        <>
          <p className="px-4 py-2 text-xs font-semibold text-purple-600 bg-purple-50 border-b border-purple-100">
            💳 {awaitingItems.length} esperando confirmación de pago
          </p>
          {awaitingItems.map((item) => (
            <Link key={item.id} href={`/orders/${item.id}`} onClick={() => setOpen(false)}
              className="block border-b border-gray-100 px-4 py-3 last:border-0 hover:bg-gray-50">
              <div className="flex items-start justify-between gap-3">
                <div className="min-w-0">
                  <p className="truncate text-sm font-semibold text-gray-900">Pedido #{item.id.slice(0, 8)}</p>
                  <p className="truncate text-xs text-gray-500">{item.customerEmail || 'Sin email'}</p>
                </div>
                <span className="shrink-0 rounded-full bg-purple-100 px-2 py-1 text-[11px] font-semibold text-purple-800">Esperando pago</span>
              </div>
              <div className="mt-2 text-xs text-gray-600">{money(item.totalCents)}</div>
            </Link>
          ))}
        </>
      )}
    </div>
  );

  return (
    <div ref={rootRef} className="relative ml-auto">
      <button
        type="button"
        onClick={() => setOpen((value) => !value)}
        aria-label={`Notificaciones${grandTotal ? `: ${grandTotal} pendientes` : ''}`}
        aria-expanded={open}
        className="relative inline-flex h-10 w-10 items-center justify-center rounded-xl border border-gray-200 bg-white text-gray-600 shadow-sm hover:bg-gray-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#2D6A4F]"
      >
        <svg aria-hidden="true" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M14.857 17.082a23.85 23.85 0 0 0 5.454-1.31A8.97 8.97 0 0 1 18 9.75V9A6 6 0 0 0 6 9v.75a8.97 8.97 0 0 1-2.312 6.022 23.85 23.85 0 0 0 5.455 1.31m5.714 0a24.26 24.26 0 0 1-5.714 0m5.714 0a3 3 0 1 1-5.714 0" />
        </svg>
        {grandTotal > 0 && (
          <span className="absolute -right-1.5 -top-1.5 min-w-5 rounded-full bg-[#E76F51] px-1 text-center text-[11px] font-bold leading-5 text-white">
            {grandTotal > 99 ? '99+' : grandTotal}
          </span>
        )}
      </button>

      {open && (
        <section aria-label="Notificaciones de pedidos" className="absolute right-0 top-12 z-50 w-[min(24rem,calc(100vw-2rem))] overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-xl">
          <div className="flex items-center justify-between border-b border-gray-100 px-4 py-3">
            <h2 className="font-semibold text-gray-900">Notificaciones</h2>
            <button type="button" onClick={() => void load()} className="text-xs font-medium text-[#2D6A4F] hover:underline">Actualizar</button>
          </div>
          {/* Tabs */}
          <div className="flex border-b border-gray-100">
            <button type="button" onClick={() => setTab('pending')}
              className={`flex-1 px-3 py-2 text-xs font-medium border-b-2 transition-colors ${
                tab === 'pending' ? 'border-[#2D6A4F] text-[#2D6A4F]' : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}>
              📦 Pendientes {staleTotal > 0 && <span className="ml-1 rounded-full bg-amber-100 text-amber-700 px-1.5 py-0.5 text-[10px] font-bold">{staleTotal}</span>}
            </button>
            <button type="button" onClick={() => setTab('awaiting')}
              className={`flex-1 px-3 py-2 text-xs font-medium border-b-2 transition-colors ${
                tab === 'awaiting' ? 'border-[#2D6A4F] text-[#2D6A4F]' : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}>
              💳 Esperando pago {awaitingTotal > 0 && <span className="ml-1 rounded-full bg-purple-100 text-purple-700 px-1.5 py-0.5 text-[10px] font-bold">{awaitingTotal}</span>}
            </button>
          </div>
          <div className="max-h-80 overflow-y-auto">
            {tab === 'pending' ? <TabPending /> : <TabAwaiting />}
          </div>
          {grandTotal > 0 && (
            <Link href="/orders" onClick={() => setOpen(false)}
              className="block border-t border-gray-100 px-4 py-3 text-center text-sm font-medium text-[#2D6A4F] hover:bg-gray-50">
              Ver todos los pedidos →
            </Link>
          )}
        </section>
      )}
    </div>
  );
}
