'use client';

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';

interface Preference {
  channel: 'email' | 'push';
  category: 'orders' | 'shipping' | 'payouts' | 'promotions' | 'price_drops' | 'account';
  enabled: boolean;
  is_transactional: boolean;
}

const ROWS: { key: Preference['category']; label: string }[] = [
  { key: 'orders',      label: 'Orders' },
  { key: 'shipping',    label: 'Shipping' },
  { key: 'payouts',     label: 'Payouts' },
  { key: 'account',     label: 'Account' },
  { key: 'promotions',  label: 'Marketing & tips' },
  { key: 'price_drops', label: 'Price drops' },
];

const CHANNELS: { key: Preference['channel']; label: string }[] = [
  { key: 'email', label: 'Email' },
];

export default function NotificationsPage() {
  const qc = useQueryClient();

  const prefsQ = useQuery({
    queryKey: ['notification-preferences'],
    queryFn: () => api.notifications.listPreferences(),
  });

  const prefs: Preference[] = prefsQ.data?.data ?? [];

  const mut = useMutation({
    mutationFn: (next: Array<Pick<Preference, 'channel' | 'category' | 'enabled'>>) =>
      api.notifications.updatePreferences({ preferences: next }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['notification-preferences'] }),
  });

  const get = (channel: Preference['channel'], category: Preference['category']) =>
    prefs.find((p) => p.channel === channel && p.category === category);

  const toggle = (channel: Preference['channel'], category: Preference['category'], enabled: boolean) => {
    mut.mutate([{ channel, category, enabled }]);
  };

  if (prefsQ.isLoading) return <div className="text-sm text-ink/60">Loading…</div>;

  return (
    <section className="max-w-2xl rounded-md border border-forest/20 bg-white p-6">
      <h2 className="text-lg font-semibold text-ink">Notifications</h2>
      <p className="mt-1 text-sm text-ink/60">
        Transactional messages (orders, shipping) are always on.
      </p>
      <table className="mt-4 w-full text-sm">
        <thead className="bg-bone/60">
          <tr>
            <th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-ink/60">Category</th>
            {CHANNELS.map((c) => (
              <th key={c.key} className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-ink/60">
                {c.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {ROWS.map((r) => (
            <tr key={r.key} className="border-t border-forest/10">
              <td className="px-3 py-2 text-ink">{r.label}</td>
              {CHANNELS.map((c) => {
                const p = get(c.key, r.key);
                const locked = p?.is_transactional ?? false;
                return (
                  <td key={c.key} className="px-3 py-2">
                    <label className="inline-flex items-center gap-2">
                      <input
                        type="checkbox"
                        checked={p?.enabled ?? false}
                        disabled={locked || mut.isPending}
                        onChange={(e) => toggle(c.key, r.key, e.target.checked)}
                      />
                      {locked && <span className="text-xs text-ink/40">(locked)</span>}
                    </label>
                  </td>
                );
              })}
            </tr>
          ))}
        </tbody>
      </table>
      {mut.isError && <p className="mt-3 text-sm text-terracotta">Failed to update preferences.</p>}
    </section>
  );
}
