'use client';

import { AlertTriangle, Bell, Check, ExternalLink, Info, ShieldAlert, X } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { formatDistanceToNow } from 'date-fns';

import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import type { AlertRow } from './types';
import { useAlertActions } from './use-alerts';

interface AlertCardProps {
  alert: AlertRow;
  /** Hide the side action buttons in compact contexts (e.g. resolved/dismissed history). */
  readOnly?: boolean;
}

const SEVERITY_STYLES: Record<string, { stripe: string; icon: typeof Info }> = {
  info: { stripe: 'bg-[hsl(var(--chart-1))]', icon: Info },
  warning: { stripe: 'bg-amber-500', icon: AlertTriangle },
  critical: { stripe: 'bg-destructive', icon: ShieldAlert },
};

export function AlertCard({ alert, readOnly = false }: AlertCardProps) {
  const router = useRouter();
  const { acknowledge, dismiss } = useAlertActions();
  const sev = SEVERITY_STYLES[alert.severity] ?? SEVERITY_STYLES.info!;
  const Icon = sev.icon;
  const acknowledged = Boolean(alert.acknowledgedAt);
  const fired = formatDistanceToNow(new Date(alert.firedAt), { addSuffix: true });

  return (
    <div
      data-testid="alert-card"
      data-severity={alert.severity}
      className={cn(
        'group relative flex gap-3 overflow-hidden rounded-lg border border-border bg-card p-3 shadow-xs transition-shadow duration-base ease-spring hover:shadow-sm',
        acknowledged && 'opacity-70',
      )}
    >
      <span className={cn('absolute inset-y-0 left-0 w-1', sev.stripe)} aria-hidden />
      <Icon
        className={cn(
          'mt-0.5 h-4 w-4 shrink-0',
          alert.severity === 'critical' && 'text-destructive',
          alert.severity === 'warning' && 'text-amber-600',
          alert.severity === 'info' && 'text-foreground',
        )}
      />
      <div className="min-w-0 flex-1">
        <div className="flex items-baseline gap-2">
          <p className="truncate text-sm font-medium text-foreground">{alert.title}</p>
          {acknowledged ? (
            <span className="text-xs uppercase tracking-wide text-muted-foreground">ack</span>
          ) : null}
        </div>
        {alert.body ? (
          <p className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">{alert.body}</p>
        ) : null}
        <div className="mt-1 flex items-center gap-2 text-xs text-muted-foreground">
          <span>{fired}</span>
        </div>
      </div>
      {!readOnly ? (
        <div className="flex shrink-0 items-start gap-1 text-muted-foreground">
          {!acknowledged ? (
            <Button
              variant="ghost"
              size="icon"
              className="h-7 w-7"
              aria-label="Acknowledge"
              disabled={acknowledge.isPending}
              onClick={() => acknowledge.mutate(alert.id)}
            >
              <Check className="h-3.5 w-3.5" />
            </Button>
          ) : null}
          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7"
            aria-label="Dismiss"
            disabled={dismiss.isPending}
            onClick={() => dismiss.mutate(alert.id)}
          >
            <X className="h-3.5 w-3.5" />
          </Button>
          {alert.link ? (
            <Button
              variant="ghost"
              size="icon"
              className="h-7 w-7"
              aria-label="Open"
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              onClick={() => router.push(alert.link as any)}
            >
              <ExternalLink className="h-3.5 w-3.5" />
            </Button>
          ) : null}
        </div>
      ) : null}
    </div>
  );
}

export function AlertCardEmpty() {
  return (
    <div className="flex flex-col items-center justify-center rounded-lg border border-dashed border-border py-10 text-center">
      <Bell className="mb-2 h-8 w-8 text-muted-foreground/40" aria-hidden />
      <p className="text-sm font-medium">All clear</p>
      <p className="mt-1 text-xs text-muted-foreground">No active alerts right now.</p>
    </div>
  );
}
