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

type AlertState = NonNullable<AlertDto['state']>;

const STATE_FILTERS: Array<{ label: string; values: AlertState[] }> = [
  { label: 'Open',  values: ['PENDING', 'FIRING', 'ACKNOWLEDGED'] },
  { label: 'Firing', values: ['FIRING'] },
  { label: 'Acked',  values: ['ACKNOWLEDGED'] },
  { label: 'All',    values: ['PENDING', 'FIRING', 'ACKNOWLEDGED', 'RESOLVED'] },
];

export default function AllAlertsPage() {
  const [filterIdx, setFilterIdx] = useState(0);
  const filter = STATE_FILTERS[filterIdx];
  const { data, isLoading, error } = useAlerts({ state: filter.values, limit: 200 });

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

  const rows = data ?? [];

  return (
    <div className={css.page}>
      <div className={css.toolbar}>
        <SectionHeader>All alerts</SectionHeader>
        <div style={{ display: 'flex', gap: 4 }}>
          {STATE_FILTERS.map((f, i) => (
            <Button
              key={f.label}
              size="sm"
              variant={i === filterIdx ? 'primary' : 'secondary'}
              onClick={() => setFilterIdx(i)}
            >
              {f.label}
            </Button>
          ))}
        </div>
      </div>
      {rows.length === 0 ? (
        <div className={css.empty}>No alerts match this filter.</div>
      ) : (
        rows.map((a) => <AlertRow key={a.id} alert={a} unread={false} />)
      )}
    </div>
  );
}
