import { useState } from 'react';
import { Link } from 'react-router';
import { Bell } from 'lucide-react';
import {
  ButtonGroup, DataTable, EmptyState,
} from '@cameleer/design-system';
import type { ButtonGroupItem, Column } from '@cameleer/design-system';
import { PageLoader } from '../../components/PageLoader';
import { SeverityBadge } from '../../components/SeverityBadge';
import { AlertStateChip } from '../../components/AlertStateChip';
import {
  useAlerts, useMarkAlertRead,
  type AlertDto,
} from '../../api/queries/alerts';
import { severityToAccent } from './severity-utils';
import { formatRelativeTime } from './time-utils';
import { renderAlertExpanded } from './alert-expanded';
import css from './alerts-page.module.css';
import tableStyles from '../../styles/table-section.module.css';

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

const STATE_ITEMS: ButtonGroupItem[] = [
  { value: 'FIRING',       label: 'Firing',       color: 'var(--error)' },
  { value: 'ACKNOWLEDGED', label: 'Acknowledged', color: 'var(--warning)' },
  { value: 'PENDING',      label: 'Pending',      color: 'var(--text-muted)' },
  { value: 'RESOLVED',     label: 'Resolved',     color: 'var(--success)' },
];

const DEFAULT_OPEN_STATES = new Set<string>(['PENDING', 'FIRING', 'ACKNOWLEDGED']);

export default function AllAlertsPage() {
  const [stateSel, setStateSel] = useState<Set<string>>(() => new Set(DEFAULT_OPEN_STATES));
  const stateValues: AlertState[] | undefined = stateSel.size === 0
    ? undefined
    : [...stateSel] as AlertState[];

  const { data, isLoading, error } = useAlerts({ state: stateValues, limit: 200 });
  const markRead = useMarkAlertRead();

  const rows = data ?? [];

  const columns: Column<AlertDto>[] = [
    {
      key: 'severity', header: 'Severity', width: '110px',
      render: (_, row) => row.severity ? <SeverityBadge severity={row.severity} /> : null,
    },
    {
      key: 'state', header: 'Status', width: '140px',
      render: (_, row) => row.state ? <AlertStateChip state={row.state} silenced={row.silenced} /> : null,
    },
    {
      key: 'title', header: 'Title',
      render: (_, row) => (
        <div className={css.titleCell}>
          <Link to={`/alerts/inbox/${row.id}`} onClick={() => row.id && markRead.mutate(row.id)}>
            {row.title ?? '(untitled)'}
          </Link>
          {row.message && <span className={css.titlePreview}>{row.message}</span>}
        </div>
      ),
    },
    {
      key: 'firedAt', header: 'Fired at', width: '140px', sortable: true,
      render: (_, row) =>
        row.firedAt ? (
          <span title={row.firedAt} style={{ fontVariantNumeric: 'tabular-nums' }}>
            {formatRelativeTime(row.firedAt)}
          </span>
        ) : '—',
    },
  ];

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

  return (
    <div className={css.page}>
      <header className={css.pageHeader}>
        <div className={css.pageTitleGroup}>
          <h2 className={css.pageTitle}>All alerts</h2>
          <span className={css.pageSubtitle}>{rows.length} matching your filter</span>
        </div>
        <div className={css.pageActions}>
          <ButtonGroup
            items={STATE_ITEMS}
            value={stateSel}
            onChange={setStateSel}
          />
        </div>
      </header>

      {rows.length === 0 ? (
        <EmptyState
          icon={<Bell size={32} />}
          title="No alerts match this filter"
          description="Try switching to a different state or widening your criteria."
        />
      ) : (
        <div className={`${tableStyles.tableSection} ${css.tableWrap}`}>
          <DataTable<AlertDto & { id: string }>
            columns={columns as Column<AlertDto & { id: string }>[]}
            data={rows as Array<AlertDto & { id: string }>}
            sortable
            flush
            fillHeight
            pageSize={200}
            rowAccent={(row) => row.severity ? severityToAccent(row.severity) : undefined}
            expandedContent={renderAlertExpanded}
          />
        </div>
      )}
    </div>
  );
}
