'use client';

import { AlertTriangle, PackageCheck, Tag, Wallet, type LucideIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

import { PageTitle } from '@/components/layout/page-header';
import { SectionCard } from '@/components/settings/section-card';
import { StickySaveBar } from '@/components/settings/sticky-save-bar';
import { Switch } from '@/components/ui/switch';
import { ErrorState, ForbiddenState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { ApiError, api } from '@/lib/api-client';
import { usePermission } from '@/hooks/use-permission';

interface Prefs {
  labelCreated: boolean;
  delivered: boolean;
  exception: boolean;
  lowBalance: boolean;
}

const defaults: Prefs = { labelCreated: true, delivered: true, exception: true, lowBalance: true };

const rows: Array<{ key: keyof Prefs; title: string; description: string; icon: LucideIcon; chip: string }> = [
  { key: 'labelCreated', title: 'Label created', description: 'Emails the shipment creator when a label is ready.', icon: Tag, chip: 'bg-primary-soft text-primary' },
  { key: 'delivered', title: 'Delivered', description: 'Emails the shipment creator when a parcel is delivered.', icon: PackageCheck, chip: 'bg-success-soft text-success' },
  { key: 'exception', title: 'Exception', description: 'Emails the shipment creator when tracking reports a problem.', icon: AlertTriangle, chip: 'bg-danger-soft text-danger' },
  { key: 'lowBalance', title: 'Low balance', description: 'Emails owners and admins when the wallet drops below the threshold.', icon: Wallet, chip: 'bg-warning-soft text-warning' },
];

export default function NotificationsSettingsPage() {
  const allowed = usePermission('tenant:settings');
  const [saved, setSaved] = useState<Prefs | null>(null);
  const [draft, setDraft] = useState<Prefs | null>(null);
  const [error, setError] = useState<ApiError | null>(null);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!allowed) return;
    void api<{ notificationPrefs?: Partial<Prefs> }>('/tenant')
      .then((tenant) => {
        const prefs = { ...defaults, ...tenant.notificationPrefs };
        setSaved(prefs);
        setDraft(prefs);
      })
      .catch((reason: unknown) => setError(reason instanceof ApiError ? reason : null));
  }, [allowed]);

  if (!allowed) return <ForbiddenState />;
  if (error !== null) return <ErrorState message={error.message} requestId={error.requestId} />;
  if (draft === null || saved === null) return <Skeleton className="h-80 rounded-xl" />;

  const dirty = JSON.stringify(draft) !== JSON.stringify(saved);

  return (
    <div className="grid gap-6">
      <PageTitle title="Notifications" breadcrumb="Settings" />
      <SectionCard title="Email notifications" description="Choose which shipment and wallet emails your workspace sends.">
        <ul className="-mx-2 grid gap-1">
          {rows.map((row) => {
            const Icon = row.icon;
            const titleId = `notification-${row.key}`;
            return (
              <li key={row.key} className="flex items-center gap-4 rounded-lg px-2 py-3 hover:bg-surface-muted/60">
                <span className={`grid h-10 w-10 shrink-0 place-items-center rounded-lg ${row.chip}`}>
                  <Icon className="h-5 w-5" aria-hidden="true" />
                </span>
                <span className="min-w-0 flex-1">
                  <span id={titleId} className="block text-small font-semibold">
                    {row.title}
                  </span>
                  <span className="block text-caption text-muted-foreground">{row.description}</span>
                </span>
                <Switch checked={draft[row.key]} onCheckedChange={(checked) => setDraft({ ...draft, [row.key]: checked })} labelledBy={titleId} />
              </li>
            );
          })}
        </ul>
      </SectionCard>
      <StickySaveBar
        dirty={dirty}
        saving={saving}
        onDiscard={() => setDraft(saved)}
        onSave={() => {
          setSaving(true);
          void api('/tenant', { method: 'PATCH', json: { notificationPrefs: draft } })
            .then(() => {
              setSaved(draft);
              toast.success('Notification preferences saved.');
            })
            .catch((reason: unknown) => toast.error(reason instanceof ApiError ? reason.message : 'Could not save notifications.'))
            .finally(() => setSaving(false));
        }}
      />
    </div>
  );
}
