'use client';

import { useEffect, useState, useCallback } from 'react';
import { Loader2, Inbox, RefreshCw, Eye, X } from 'lucide-react';
import { toast } from 'sonner';

interface OutboxRow {
  id: string;
  restaurant_id: string | null;
  recipient: string;
  template_key: string;
  status: 'queued' | 'sending' | 'sent' | 'failed' | 'throttled';
  channel: 'immediate' | 'digest';
  kind: string | null;
  attempts: number;
  scheduled_for: string;
  sent_at: string | null;
  last_error: string | null;
  created_at: string;
  payload: unknown;
}

const STATUSES = ['', 'queued', 'sending', 'sent', 'failed', 'throttled'] as const;

const TEMPLATE_KEYS = [
  '',
  'signup_otp',
  'password_reset',
  'order_new_customer',
  'order_new_restaurant',
  'booking_confirmation_customer',
  'booking_reminder_customer',
  'booking_new_restaurant',
];

export default function AdminEmailLogPage() {
  const [rows, setRows] = useState<OutboxRow[]>([]);
  const [status, setStatus] = useState<string>('');
  const [search, setSearch] = useState<string>('');
  const [restaurantId, setRestaurantId] = useState<string>('');
  const [templateKey, setTemplateKey] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [payloadView, setPayloadView] = useState<OutboxRow | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    const qs = new URLSearchParams();
    if (status) qs.set('status', status);
    if (search) qs.set('search', search);
    if (restaurantId) qs.set('restaurant_id', restaurantId);
    if (templateKey) qs.set('template_key', templateKey);
    const r = await fetch(`/api/admin/email/outbox?${qs}`, { credentials: 'include' });
    const d = await r.json();
    setRows(d.items || []);
    setLoading(false);
  }, [status, search, restaurantId, templateKey]);

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

  const retry = async (id: string) => {
    const r = await fetch(`/api/admin/email/outbox/${id}/retry`, { method: 'POST', credentials: 'include' });
    if (r.ok) { toast.success('Re-queued for delivery'); load(); }
    else toast.error('Retry failed');
  };

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <div className="flex items-center justify-between mb-6 flex-wrap gap-3">
        <div className="flex items-center gap-3">
          <Inbox className="text-orange-500" />
          <h1 className="text-2xl font-semibold">Email Outbox</h1>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="recipient or template…"
                 className="border rounded-md px-2 py-1 text-sm" />
          <input value={restaurantId} onChange={(e) => setRestaurantId(e.target.value)} placeholder="restaurant id"
                 className="border rounded-md px-2 py-1 text-sm w-40" />
          <select value={templateKey} onChange={(e) => setTemplateKey(e.target.value)} className="border rounded-md px-2 py-1 text-sm">
            {TEMPLATE_KEYS.map((k) => <option key={k} value={k}>{k || 'all templates'}</option>)}
          </select>
          <select value={status} onChange={(e) => setStatus(e.target.value)} className="border rounded-md px-2 py-1 text-sm">
            {STATUSES.map((s) => <option key={s} value={s}>{s || 'all statuses'}</option>)}
          </select>
          <button onClick={load} className="inline-flex items-center gap-1 text-sm border rounded-md px-3 py-1.5 hover:bg-gray-50">
            <RefreshCw size={14} /> Refresh
          </button>
        </div>
      </div>

      {loading ? (
        <div className="flex justify-center p-8"><Loader2 className="animate-spin" /></div>
      ) : (
        <div className="bg-white border rounded-lg overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 text-xs uppercase text-gray-500">
              <tr>
                <th className="px-3 py-2 text-left">When</th>
                <th className="px-3 py-2 text-left">To</th>
                <th className="px-3 py-2 text-left">Template</th>
                <th className="px-3 py-2 text-left">Channel</th>
                <th className="px-3 py-2 text-left">Status</th>
                <th className="px-3 py-2 text-left">Sent</th>
                <th className="px-3 py-2 text-left">Attempts</th>
                <th className="px-3 py-2"></th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {rows.length === 0 && <tr><td colSpan={8} className="px-3 py-6 text-center text-gray-500">No emails</td></tr>}
              {rows.map((r) => (
                <tr key={r.id} className="hover:bg-gray-50">
                  <td className="px-3 py-2 whitespace-nowrap text-xs text-gray-500">{new Date(r.created_at).toLocaleString()}</td>
                  <td className="px-3 py-2">{r.recipient}</td>
                  <td className="px-3 py-2 text-xs">
                    <code>{r.template_key}</code>
                    {r.kind && <div className="text-gray-400">{r.kind}</div>}
                  </td>
                  <td className="px-3 py-2 text-xs">{r.channel}</td>
                  <td className="px-3 py-2">
                    <span className={`inline-block px-2 py-0.5 rounded text-xs ${
                      r.status === 'sent' ? 'bg-green-100 text-green-700' :
                      r.status === 'failed' ? 'bg-red-100 text-red-700' :
                      r.status === 'sending' ? 'bg-blue-100 text-blue-700' :
                      r.status === 'throttled' ? 'bg-orange-100 text-orange-700' :
                      'bg-yellow-100 text-yellow-700'
                    }`}>{r.status}</span>
                    {r.last_error && <div className="text-xs text-red-600 mt-1 truncate max-w-xs" title={r.last_error}>{r.last_error}</div>}
                  </td>
                  <td className="px-3 py-2 text-xs text-gray-500">{r.sent_at ? new Date(r.sent_at).toLocaleString() : '—'}</td>
                  <td className="px-3 py-2 text-xs">{r.attempts}</td>
                  <td className="px-3 py-2 text-right whitespace-nowrap">
                    <button onClick={() => setPayloadView(r)} className="text-xs text-gray-600 hover:underline inline-flex items-center gap-1 mr-3">
                      <Eye size={12} /> Payload
                    </button>
                    {(r.status === 'failed' || r.status === 'throttled') && (
                      <button onClick={() => retry(r.id)} className="text-xs text-orange-600 hover:underline">Retry</button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {payloadView && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4" onClick={() => setPayloadView(null)}>
          <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[80vh] overflow-hidden flex flex-col" onClick={(e) => e.stopPropagation()}>
            <div className="px-4 py-3 border-b flex items-center justify-between">
              <div>
                <div className="font-semibold text-sm">Payload · {payloadView.template_key}</div>
                <div className="text-xs text-gray-500">to {payloadView.recipient}</div>
              </div>
              <button onClick={() => setPayloadView(null)} className="text-gray-500 hover:text-gray-900"><X size={18} /></button>
            </div>
            <pre className="p-4 text-xs overflow-auto bg-gray-50 flex-1">{JSON.stringify(payloadView.payload, null, 2)}</pre>
          </div>
        </div>
      )}
    </div>
  );
}
