import { createSignal, createMemo, Show, For } from 'solid-js';

const API = '/api/gateway';

type NotificationRow = {
  id: string;
  title: string;
  message: string;
  read_at: string | null;
  event_type: string;
  created_at: string;
};

function eventTypeBadgeStyle(eventType: string): string {
  if (eventType.includes('APPROVED')) return 'background:#dcfce7;color:#15803d';
  if (eventType.includes('REJECTED')) return 'background:#fee2e2;color:#b91c1c';
  if (eventType.includes('CHANGES_REQUESTED')) return 'background:#ffedd5;color:#c2410c';
  return 'background:#f1f5f9;color:#475569';
}

const BADGE_STYLE = 'display:inline-block;padding:2px 8px;border-radius:999px;font-size:11px;font-weight:600';

export default function NotificationsPage() {
  const [activeTab, setActiveTab] = createSignal<'all' | 'unread'>('all');
  const [rows, setRows] = createSignal<NotificationRow[]>([]);
  const [cursor, setCursor] = createSignal<string | null>(null);
  const [loading, setLoading] = createSignal(false);
  const [markingAllRead, setMarkingAllRead] = createSignal(false);
  const [markingId, setMarkingId] = createSignal('');

  const unreadCount = createMemo(() => rows().filter((r) => r.read_at === null).length);

  const unreadRows = createMemo(() => rows().filter((r) => r.read_at === null));

  const visibleRows = createMemo(() => (activeTab() === 'unread' ? unreadRows() : rows()));

  const load = async (nextCursor?: string | null, reset?: boolean) => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (nextCursor) params.set('cursor', nextCursor);
      const res = await fetch(`${API}/api/me/notifications${params.toString() ? `?${params}` : ''}`);
      if (!res.ok) throw new Error('Failed to load notifications');
      const data = await res.json();
      const list: NotificationRow[] = Array.isArray(data.notifications) ? data.notifications : Array.isArray(data) ? data : [];
      setRows((prev) => (reset ? list : [...prev, ...list]));
      setCursor(data.nextCursor || null);
    } catch {
      if (reset) setRows([]);
    } finally {
      setLoading(false);
    }
  };

  // Initial load
  load(null, true);

  const refetch = () => load(null, true);

  const handleMarkRead = async (id: string) => {
    setMarkingId(id);
    try {
      await fetch(`${API}/api/me/notifications/${id}/read`, { method: 'POST' });
      setRows((prev) => prev.map((r) => (r.id === id ? { ...r, read_at: new Date().toISOString() } : r)));
    } finally {
      setMarkingId('');
    }
  };

  const handleMarkAllRead = async () => {
    setMarkingAllRead(true);
    try {
      await fetch(`${API}/api/me/notifications/read-all`, { method: 'POST' });
      refetch();
    } finally {
      setMarkingAllRead(false);
    }
  };

  const truncate = (str: string, max: number) =>
    str && str.length > max ? str.substring(0, max) + '…' : (str || '');

  return (
      <div class="flex flex-col -mx-6 -mt-6 min-h-full">
        <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
          <div>
            <h1 class="text-xl font-semibold text-gray-900">Notifications</h1>
            <p class="text-sm text-gray-500 mt-0.5">Approval outcomes and action-required updates</p>
          </div>
          <button
            class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
            onClick={handleMarkAllRead}
            disabled={markingAllRead()}
          >
            {markingAllRead() ? 'Marking...' : 'Mark All Read'}
          </button>
        </div>

        {/* Tabs */}
        <div class="bg-white border-b border-gray-200 px-6 flex items-center gap-8 sticky top-0 z-10">
          <button
            type="button"
            class={activeTab() === 'all'
              ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium'
              : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'}
            onClick={() => setActiveTab('all')}
          >
            All
          </button>
          <button
            type="button"
            class={activeTab() === 'unread'
              ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium'
              : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'}
            onClick={() => setActiveTab('unread')}
          >
            Unread ({unreadCount()})
          </button>
        </div>

        <div class="flex-1 p-6">
          <div class="table-card">
            <div class="overflow-x-auto">
              <table class="data-table w-full text-sm">
                <thead>
                  <tr>
                    <th>Title</th>
                    <th>Message</th>
                    <th>Event Type</th>
                    <th>Created At</th>
                    <th class="text-right">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <Show when={loading() && rows().length === 0}>
                    <tr><td colspan="5" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
                  </Show>
                  <Show when={!loading() && visibleRows().length === 0}>
                    <tr><td colspan="5" style="text-align:center;padding:32px;color:#94a3b8">No notifications.</td></tr>
                  </Show>
                  <For each={visibleRows()}>
                    {(item) => (
                      <tr class="hover:bg-slate-50" style={item.read_at === null ? 'background:#eff6ff' : ''}>
                        <td class="font-semibold text-slate-900" style="min-width:160px">{item.title}</td>
                        <td class="text-slate-500" style="max-width:320px">{truncate(item.message, 80)}</td>
                        <td>
                          <span style={`${BADGE_STYLE};${eventTypeBadgeStyle(item.event_type)}`}>
                            {item.event_type}
                          </span>
                        </td>
                        <td class="text-slate-500" style="font-size:12px;white-space:nowrap">
                          {item.created_at ? new Date(item.created_at).toLocaleString() : '—'}
                        </td>
                        <td>
                          <div class="flex items-center justify-end gap-1">
                            <Show when={item.read_at === null}>
                              <button
                                class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                                disabled={markingId() === item.id}
                                onClick={() => handleMarkRead(item.id)}
                              >
                                {markingId() === item.id ? '...' : 'Mark Read'}
                              </button>
                            </Show>
                          </div>
                        </td>
                      </tr>
                    )}
                  </For>
                </tbody>
              </table>
            </div>
          </div>

          <Show when={loading() && rows().length > 0}>
            <p style="text-align:center;padding:12px;font-size:13px;color:#64748b">Loading...</p>
          </Show>

          <Show when={cursor() && !loading()}>
            <div style="margin-top:12px">
              <button
                class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                onClick={() => load(cursor(), false)}
              >
                Load More
              </button>
            </div>
          </Show>
        </div>
      </div>
  );
}
