import { useState } from 'react';
import { Link, useNavigate } from 'react-router';
import { FilePlus } from 'lucide-react';
import {
  Button, Toggle, useToast, Badge, DataTable,
  EmptyState, Dropdown, ConfirmDialog,
} from '@cameleer/design-system';
import type { Column } from '@cameleer/design-system';
import { PageLoader } from '../../components/PageLoader';
import { SeverityBadge } from '../../components/SeverityBadge';
import {
  useAlertRules,
  useDeleteAlertRule,
  useSetAlertRuleEnabled,
  type AlertRuleResponse,
} from '../../api/queries/alertRules';
import { useEnvironments } from '../../api/queries/admin/environments';
import { useSelectedEnv } from '../../api/queries/alertMeta';
import { describeApiError } from '../../api/errors';
import tableStyles from '../../styles/table-section.module.css';
import css from './alerts-page.module.css';

export default function RulesListPage() {
  const navigate = useNavigate();
  const env = useSelectedEnv();
  const { data: rules, isLoading, error } = useAlertRules();
  const { data: envs } = useEnvironments();
  const setEnabled = useSetAlertRuleEnabled();
  const deleteRule = useDeleteAlertRule();
  const { toast } = useToast();

  const [pendingDelete, setPendingDelete] = useState<AlertRuleResponse | null>(null);

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

  const rows = rules ?? [];
  const otherEnvs = (envs ?? []).filter((e) => e.slug !== env);

  const onToggle = async (r: AlertRuleResponse) => {
    try {
      await setEnabled.mutateAsync({ id: r.id!, enabled: !r.enabled });
      toast({ title: r.enabled ? 'Disabled' : 'Enabled', description: r.name, variant: 'success' });
    } catch (e) {
      toast({ title: 'Toggle failed', description: describeApiError(e), variant: 'error' });
    }
  };

  const confirmDelete = async () => {
    if (!pendingDelete) return;
    try {
      await deleteRule.mutateAsync(pendingDelete.id!);
      toast({ title: 'Deleted', description: pendingDelete.name, variant: 'success' });
    } catch (e) {
      toast({ title: 'Delete failed', description: describeApiError(e), variant: 'error' });
    } finally {
      setPendingDelete(null);
    }
  };

  const onPromote = (r: AlertRuleResponse, targetEnvSlug: string) => {
    navigate(`/alerts/rules/new?promoteFrom=${env}&ruleId=${r.id}&targetEnv=${targetEnvSlug}`);
  };

  const columns: Column<AlertRuleResponse & { id: string }>[] = [
    {
      key: 'name', header: 'Name',
      render: (_, r) => <Link to={`/alerts/rules/${r.id}`}>{r.name}</Link>,
    },
    {
      key: 'conditionKind', header: 'Type', width: '160px',
      render: (_, r) => <Badge label={r.conditionKind ?? ''} color="auto" variant="outlined" />,
    },
    {
      key: 'severity', header: 'Severity', width: '110px',
      render: (_, r) => <SeverityBadge severity={r.severity!} />,
    },
    {
      key: 'enabled', header: 'Enabled', width: '90px',
      render: (_, r) => (
        <Toggle
          checked={!!r.enabled}
          onChange={() => onToggle(r)}
          disabled={setEnabled.isPending}
        />
      ),
    },
    {
      key: 'targets', header: 'Notifies', width: '90px',
      render: (_, r) => String(r.targets?.length ?? 0),
    },
    {
      key: 'actions', header: '', width: '220px',
      render: (_, r) => (
        <div style={{ display: 'flex', gap: 'var(--space-sm)', justifyContent: 'flex-end' }}>
          {otherEnvs.length > 0 && (
            <Dropdown
              trigger={<Button variant="ghost" size="sm">Promote to ▾</Button>}
              items={otherEnvs.map((e) => ({
                label: e.slug,
                onClick: () => onPromote(r, e.slug),
              }))}
            />
          )}
          <Button variant="ghost" size="sm" onClick={() => setPendingDelete(r)} disabled={deleteRule.isPending}>
            Delete
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className={css.page}>
      <header className={css.pageHeader}>
        <div className={css.pageTitleGroup}>
          <h2 className={css.pageTitle}>Alert rules</h2>
          <span className={css.pageSubtitle}>
            {rows.length === 0 ? 'No rules yet' : `${rows.length} rule${rows.length === 1 ? '' : 's'} configured`}
          </span>
        </div>
        <div className={css.pageActions}>
          <Link to="/alerts/rules/new">
            <Button variant="primary">New rule</Button>
          </Link>
        </div>
      </header>

      {rows.length === 0 ? (
        <EmptyState
          icon={<FilePlus size={32} />}
          title="No alert rules"
          description="Create one to start evaluating alerts for this environment."
          action={
            <Link to="/alerts/rules/new">
              <Button variant="primary">Create rule</Button>
            </Link>
          }
        />
      ) : (
        <div className={`${tableStyles.tableSection} ${css.tableWrap}`}>
          <DataTable<AlertRuleResponse & { id: string }>
            columns={columns}
            data={rows as (AlertRuleResponse & { id: string })[]}
            flush
            fillHeight
          />
        </div>
      )}

      <ConfirmDialog
        open={!!pendingDelete}
        onClose={() => setPendingDelete(null)}
        onConfirm={confirmDelete}
        title="Delete alert rule?"
        message={
          pendingDelete
            ? `Delete rule "${pendingDelete.name}"? Fired alerts are preserved via rule_snapshot.`
            : ''
        }
        confirmText="Delete"
        variant="danger"
        loading={deleteRule.isPending}
      />
    </div>
  );
}
