import { Link } from 'react-router';
import { Button, useToast } from '@cameleer/design-system';
import { AlertStateChip } from '../../components/AlertStateChip';
import { SeverityBadge } from '../../components/SeverityBadge';
import type { AlertDto } from '../../api/queries/alerts';
import { useAckAlert, useMarkAlertRead } from '../../api/queries/alerts';
import css from './alerts-page.module.css';

export function AlertRow({ alert, unread }: { alert: AlertDto; unread: boolean }) {
  const ack = useAckAlert();
  const markRead = useMarkAlertRead();
  const { toast } = useToast();

  const onAck = async () => {
    try {
      await ack.mutateAsync(alert.id);
      toast({ title: 'Acknowledged', description: alert.title, variant: 'success' });
    } catch (e) {
      toast({ title: 'Ack failed', description: String(e), variant: 'error' });
    }
  };

  return (
    <div
      className={`${css.row} ${unread ? css.rowUnread : ''}`}
      data-testid={`alert-row-${alert.id}`}
    >
      <SeverityBadge severity={alert.severity} />
      <div className={css.body}>
        <Link to={`/alerts/inbox/${alert.id}`} onClick={() => markRead.mutate(alert.id)}>
          <strong>{alert.title}</strong>
        </Link>
        <div className={css.meta}>
          <AlertStateChip state={alert.state} silenced={alert.silenced} />
          <span className={css.time}>{alert.firedAt}</span>
        </div>
        <p className={css.message}>{alert.message}</p>
      </div>
      <div className={css.actions}>
        {alert.state === 'FIRING' && (
          <Button size="sm" variant="secondary" onClick={onAck} disabled={ack.isPending}>
            Ack
          </Button>
        )}
      </div>
    </div>
  );
}
