'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { useAuth } from '@/lib/auth-context';
import { useDialog } from '@/components/dialog';
import { pushSupported, enablePush } from '@/lib/push';

const SEEN_KEY = 'qtrial-login-alerts-seen';
const HIDE_KEY = 'qtrial-login-alerts-hide';

/**
 * Login-time attention feed for employees & stakeholders (and staff):
 * - In-app banner listing overdue + upcoming deviations / CAPAs / samples / testing.
 * - Chrome system notification (Notification API / service-worker) when permission
 *   is already granted, fired once per login session.
 * - One-tap "Enable Chrome notifications" (Web Push subscription) otherwise.
 */
export function LoginAlerts() {
  const { user } = useAuth();
  const { notify } = useDialog();
  const [dismissed, setDismissed] = useState(false);
  const [perm, setPerm] = useState<string>('unknown');
  const q = useQuery({
    queryKey: ['login-upcoming'],
    queryFn: () => api.get('/api/v1/dashboard/upcoming?days=7'),
    enabled: !!user,
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  useEffect(() => {
    try {
      if (sessionStorage.getItem(HIDE_KEY)) setDismissed(true);
    } catch { /* ignore */ }
    if (typeof window !== 'undefined' && 'Notification' in window) {
      setPerm(Notification.permission);
    } else {
      setPerm('unsupported');
    }
    // Ensure the push service worker is registered so background pushes can arrive.
    if (pushSupported()) {
      navigator.serviceWorker.register('/sw.js').catch(() => {});
    }
  }, []);

  const data = q.data;
  const counts = data?.counts;

  // Fire a Chrome system notification once per session when there is work due.
  useEffect(() => {
    if (!data || !counts) return;
    if (typeof window === 'undefined' || !('Notification' in window)) return;
    if (Notification.permission !== 'granted') return;
    let seen = '';
    try { seen = sessionStorage.getItem(SEEN_KEY) ?? ''; } catch { /* ignore */ }
    const stamp = `${data.today}-${counts.deviations}-${counts.capas}-${counts.samples}-${counts.schedules}`;
    if (seen === stamp) return;
    const total = counts.deviations + counts.capas + counts.samples + counts.schedules;
    if (total === 0) return;
    const title = counts.overdue > 0
      ? `${counts.overdue} overdue — ${total} need attention`
      : `${total} upcoming in ${data.days} days`;
    const lines = [
      counts.deviations ? `${counts.deviations} deviations` : '',
      counts.capas ? `${counts.capas} CAPAs` : '',
      counts.samples ? `${counts.samples} samples` : '',
      counts.schedules ? `${counts.schedules} lab tests` : '',
    ].filter(Boolean).join(' · ');
    const show = async () => {
      try {
        const reg = await navigator.serviceWorker.getRegistration();
        if (reg?.showNotification) {
          await reg.showNotification(title, { body: lines, tag: 'qtrial-login', data: { url: '/dashboard' } } as any);
        } else {
          new Notification(title, { body: lines, tag: 'qtrial-login' });
        }
      } catch { /* ignore */ }
    };
    void show();
    try { sessionStorage.setItem(SEEN_KEY, stamp); } catch { /* ignore */ }
  }, [data, counts]);

  if (!user || dismissed || q.isLoading || q.isError || !counts) return null;
  const total = counts.deviations + counts.capas + counts.samples + counts.schedules;
  if (total === 0) return null;

  const itemLink = (r: any) => {
    if (r.kind === 'deviation') return `/actions/${r.id}`;
    if (r.kind === 'capa') return `/actions/${r.parent_id}`;
    if (r.kind === 'sample') return `/samples`;
    return `/calendar`;
  };
  const preview = [...(data.deviations ?? []), ...(data.capas ?? []), ...(data.samples ?? []), ...(data.schedules ?? [])].slice(0, 5);
  const canPush = pushSupported() && perm !== 'unsupported';
  const needsEnable = canPush && perm !== 'granted';

  return (
    <div className="card border-l-4 !border-l-amber-500 space-y-2 mb-4" role="alert" aria-label="Upcoming work reminders">
      <div className="flex flex-wrap items-center gap-2">
        <p className="font-medium mr-auto">
          {counts.overdue > 0 ? `⚠ ${counts.overdue} overdue` : '🔔 Upcoming work'}
          <span className="font-normal text-slate-500 text-sm">
            {' '}— {counts.deviations} deviations · {counts.capas} CAPAs · {counts.samples} samples · {counts.schedules} lab tests (7 days)
          </span>
        </p>
        <button className="btn-ghost btn-sm" onClick={() => {
          setDismissed(true);
          try { sessionStorage.setItem(HIDE_KEY, '1'); } catch { /* ignore */ }
        }}>Dismiss</button>
      </div>
      <ul className="text-sm divide-y">
        {preview.map((r: any, i: number) => (
          <li key={`${r.kind}-${r.id}-${i}`} className="py-1 flex gap-2 items-center">
            <span className="badge bg-slate-100 shrink-0">{r.kind}</span>
            <Link href={itemLink(r)} className="font-mono text-xs no-underline hover:underline shrink-0">{r.ref ?? `#${r.id}`}</Link>
            <span className="truncate">{r.title}</span>
            <span className="ml-auto text-xs whitespace-nowrap text-slate-500">{String(r.date ?? '').slice(0, 10)}</span>
          </li>
        ))}
      </ul>
      <div className="flex flex-wrap gap-2 items-center">
        <Link href="/calendar" className="btn-ghost btn-sm">View calendar</Link>
        <Link href="/notifications" className="btn-ghost btn-sm">All notifications</Link>
        {needsEnable && (
          <button className="btn-primary btn-sm" onClick={async () => {
            try {
              await enablePush();
              setPerm('granted');
              notify('Chrome notifications enabled on this device.', { tone: 'success' });
            } catch (e: any) { notify(e.message, { tone: 'error' }); }
          }}>
            Enable Chrome notifications
          </button>
        )}
        {perm === 'granted' && <span className="text-xs text-green-700">Chrome notifications on — reminders pop up here.</span>}
        {perm === 'denied' && <span className="text-xs text-slate-500">Browser notifications are blocked — allow them in Chrome site settings to get pop-ups.</span>}
      </div>
    </div>
  );
}
