import { useMemo } from 'react';
import { Button, SectionHeader, useToast } from '@cameleer/design-system';
import { PageLoader } from '../../components/PageLoader';
import { useAlerts, useBulkReadAlerts } from '../../api/queries/alerts';
import { AlertRow } from './AlertRow';
import css from './alerts-page.module.css';

export default function InboxPage() {
  const { data, isLoading, error } = useAlerts({ state: ['FIRING', 'ACKNOWLEDGED'], limit: 100 });
  const bulkRead = useBulkReadAlerts();
  const { toast } = useToast();

  const unreadIds = useMemo(
    () => (data ?? []).filter((a) => a.state === 'FIRING').map((a) => a.id),
    [data],
  );

  if (isLoading) return <PageLoader />;
  if (error) return <div className={css.page}>Failed to load alerts: {String(error)}</div>;

  const rows = data ?? [];

  const onMarkAllRead = async () => {
    if (unreadIds.length === 0) return;
    try {
      await bulkRead.mutateAsync(unreadIds);
      toast({ title: `Marked ${unreadIds.length} as read`, variant: 'success' });
    } catch (e) {
      toast({ title: 'Bulk read failed', description: String(e), variant: 'error' });
    }
  };

  return (
    <div className={css.page}>
      <div className={css.toolbar}>
        <SectionHeader>Inbox</SectionHeader>
        <Button variant="secondary" onClick={onMarkAllRead} disabled={bulkRead.isPending || unreadIds.length === 0}>
          Mark all read
        </Button>
      </div>
      {rows.length === 0 ? (
        <div className={css.empty}>No open alerts for you in this environment.</div>
      ) : (
        rows.map((a) => <AlertRow key={a.id} alert={a} unread={a.state === 'FIRING'} />)
      )}
    </div>
  );
}
