'use client';

import { useState } from 'react';
import { ShieldAlert } from 'lucide-react';

import { PageHeader } from '@/components/shared/page-header';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { Skeleton } from '@/components/ui/skeleton';
import { AlertCard, AlertCardEmpty } from './alert-card';
import { useAlertCount, useAlertList, useAlertRealtime } from './use-alerts';
import type { AlertStatus } from './types';

export function AlertsPageShell() {
  const [tab, setTab] = useState<AlertStatus>('open');
  const { data: count } = useAlertCount();
  const { data, isLoading } = useAlertList(tab);
  useAlertRealtime();

  const total = count?.total ?? 0;
  const alerts = data?.data ?? [];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Alerts"
        eyebrow="Operational"
        description="Rules-based signals about pipeline, agreements, expenses, and access"
        kpiLine={
          <span>
            <ShieldAlert className="mr-1 inline h-3 w-3" aria-hidden />
            {total} active
          </span>
        }
        variant="gradient"
      />

      <Tabs value={tab} onValueChange={(v) => setTab(v as AlertStatus)}>
        <TabsList>
          <TabsTrigger value="open" data-testid="tab-open">
            Active{total > 0 ? ` · ${total}` : ''}
          </TabsTrigger>
          <TabsTrigger value="dismissed" data-testid="tab-dismissed">
            Dismissed
          </TabsTrigger>
          <TabsTrigger value="resolved" data-testid="tab-resolved">
            Resolved
          </TabsTrigger>
        </TabsList>

        <TabsContent value={tab} className="mt-4 space-y-2">
          {isLoading ? (
            <div className="space-y-2">
              <Skeleton className="h-20 w-full" />
              <Skeleton className="h-20 w-full" />
              <Skeleton className="h-20 w-full" />
            </div>
          ) : alerts.length === 0 ? (
            <AlertCardEmpty />
          ) : (
            alerts.map((a) => <AlertCard key={a.id} alert={a} readOnly={tab !== 'open'} />)
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}
