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

const API = '';

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 [search, setSearch] = 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 filteredRows = createMemo(() => {
    const q = search().toLowerCase().trim();
    const list = visibleRows();
    if (!q) return list;
    return list.filter((r) =>
      String(r.title || '').toLowerCase().includes(q)
      || String(r.message || '').toLowerCase().includes(q)
      || String(r.event_type || '').toLowerCase().includes(q)
    );
  });

  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 || '');

  const exportCsv = () => {
    const headers = ['Title', 'Message', 'Event Type', 'Created At', 'Read'];
    const body = filteredRows().map((item) => [
      item.title,
      truncate(item.message, 120),
      item.event_type,
      item.created_at ? new Date(item.created_at).toLocaleString() : '—',
      item.read_at ? 'Read' : 'Unread',
    ]);
    const csv = [headers, ...body].map((line) => line.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'notifications.csv';
    link.click();
    URL.revokeObjectURL(url);
  };

  return (
      <div class="w-full space-y-6 pb-8">
        <div style="display:flex;align-items:center;justify-content:space-between;gap:12px">
          <div>
            <h1 class="text-[28px] font-bold leading-tight text-[#111827]">Notifications</h1>
            <p class="mt-1 text-[14px] text-[#6B7280]">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 style="margin-top:24px;display:flex;align-items:center;gap:24px;border-bottom:1px solid #E5E7EB">
          <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>
          <div style="position:relative;margin-top:1.5rem;margin-left:-24px;margin-right:-24px;border-radius:0;border-left:none;border-right:none;overflow:visible;border-top:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
            <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6">
              <input
                type="text"
                placeholder="Search notifications..."
                value={search()}
                onInput={(e) => setSearch(e.currentTarget.value)}
                style="height:34px;flex:1;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none"
              />
              <button type="button" onClick={exportCsv} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                Export
              </button>
            </div>

          <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() && filteredRows().length === 0}>
                    <tr><td colspan="5" style="text-align:center;padding:32px;color:#94a3b8">No notifications.</td></tr>
                  </Show>
                  <For each={filteredRows()}>
                    {(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>
          <Show when={!loading() && filteredRows().length > 0}>
            <div style="display:flex;align-items:center;justify-content:space-between;border-top:1px solid #F3F4F6;padding:12px 20px">
              <p style="font-size:13px;color:#6B7280">
                Showing <strong style="font-weight:600;color:#111827">1–{filteredRows().length}</strong> of <strong style="font-weight:600;color:#111827">{filteredRows().length}</strong> notifications
              </p>
            </div>
          </Show>
          </div>
        </div>
      </div>
  );
}
