
import * as ActionIcons from './Icons';
import { api } from '@/lib/api';
import { date } from '@/lib/format';
import { markAllNotificationsRead, openNotification, saveNotificationPreferences } from '@/app/actions';
import { Card, Empty, Pager } from './ui';
import { SubmitButton } from './Actions';
import { BellIcon, CheckIcon, SaveIcon } from './Icons';

type N = { id: number; category: string; title: string; body: string | null; actionUrl: string | null; readAt: string | null; createdAt: string };
type Pref = { category: string; label: string; inApp: boolean; email: boolean };

/** The bell's full view plus per-category preferences — shared by the staff console and the portal */
export async function NotificationsPanel({ basePath, page, fallbackUrl }: { basePath: string; page: number; fallbackUrl: string }) {
  const [d, prefs] = await Promise.all([api<{ items: N[]; total: number; unread: number; page: number; pageCount: number }>(`/me/notifications?page=${page}`), api<Pref[]>('/me/notifications/preferences')]);
  return (
    <div className="grid gap-6 xl:grid-cols-[1.6fr_1fr]">
      <Card
        title={`Notifications${d.unread ? ` · ${d.unread} unread` : ''}`}
        icon={<BellIcon className="h-4 w-4" />}
        actions={
          d.unread > 0 && (
            <form action={markAllNotificationsRead}>
              <input type="hidden" name="back" value={basePath} />
              <SubmitButton className="btn btn-quiet btn-xs">
                <CheckIcon className="h-3.5 w-3.5" /> Mark all read
              </SubmitButton>
            </form>
          )
        }
      >
        {d.items.length ? (
          <ul className="divide-y divide-rule">
            {d.items.map((n) => (
              <li key={n.id} className={n.readAt ? '' : 'bg-ledger-tint/50'}>
                <form action={openNotification}>
                  <input type="hidden" name="id" value={n.id} />
                  <input type="hidden" name="back" value={n.actionUrl ?? fallbackUrl} />
                  <button className="flex w-full items-start gap-3 px-4 py-3 text-left text-sm hover:bg-sunken">
                    <span aria-hidden className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${n.readAt ? 'bg-transparent' : 'bg-ledger'}`} />
                    <span className="min-w-0 flex-1">
                      <span className={`block ${n.readAt ? 'text-ink-2' : 'font-semibold text-ink'}`}>{n.title}</span>
                      {n.body && <span className="mt-0.5 block text-xs leading-relaxed text-muted">{n.body}</span>}
                    </span>
                    <span className="whitespace-nowrap text-xs text-muted">{date(n.createdAt, true)}</span>
                  </button>
                </form>
              </li>
            ))}
          </ul>
        ) : (
          <Empty icon={<BellIcon className="h-6 w-6" />}>No notifications yet.</Empty>
        )}
        <Pager page={d.page} pageCount={d.pageCount} total={d.total} href={(p) => `${basePath}?page=${p}`} />
      </Card>

      <Card title="What to tell me about" icon={<SaveIcon className="h-4 w-4" />}>
        <form action={saveNotificationPreferences}>
          <input type="hidden" name="back" value={basePath} />
          <table className="tbl">
            <thead>
              <tr>
                <th>Topic</th>
                <th className="text-center">In app</th>
                <th className="text-center">Email</th>
              </tr>
            </thead>
            <tbody>
              {prefs.map((p) => (
                <tr key={p.category}>
                  <td className="text-sm">
                    <input type="hidden" name="category" value={p.category} />
                    {p.label}
                  </td>
                  <td className="text-center">
                    <input type="checkbox" name={`inApp:${p.category}`} defaultChecked={p.inApp} aria-label={`${p.label} in app`} />
                  </td>
                  <td className="text-center">
                    <input type="checkbox" name={`email:${p.category}`} defaultChecked={p.email} aria-label={`${p.label} by email`} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="border-t border-rule p-4">
            <SubmitButton pendingLabel="Saving…"><ActionIcons.SaveIcon />Save preferences</SubmitButton>
            <p className="mt-2 text-xs text-muted">Security emails (password, two-factor, sign-in changes) are always sent.</p>
          </div>
        </form>
      </Card>
    </div>
  );
}
