import { useState, useEffect } from 'react';
import { useSearchParams } from 'react-router';
import { BellOff } from 'lucide-react';
import {
  Button, FormField, Input, useToast, DataTable,
  EmptyState, ConfirmDialog, MonoText, Modal,
} from '@cameleer/design-system';
import type { Column } from '@cameleer/design-system';
import { PageLoader } from '../../components/PageLoader';
import {
  useAlertSilences,
  useCreateSilence,
  useDeleteSilence,
  type AlertSilenceResponse,
} from '../../api/queries/alertSilences';
import { describeApiError } from '../../api/errors';
import tableStyles from '../../styles/table-section.module.css';
import css from './alerts-page.module.css';

export default function SilencesPage() {
  const { data, isLoading, error } = useAlertSilences();
  const create = useCreateSilence();
  const remove = useDeleteSilence();
  const { toast } = useToast();

  const [reason, setReason] = useState('');
  const [matcherRuleId, setMatcherRuleId] = useState('');
  const [matcherAppSlug, setMatcherAppSlug] = useState('');
  const [hours, setHours] = useState(1);
  const [pendingEnd, setPendingEnd] = useState<AlertSilenceResponse | null>(null);
  const [createOpen, setCreateOpen] = useState(false);

  const [searchParams] = useSearchParams();
  useEffect(() => {
    const r = searchParams.get('ruleId');
    if (r) {
      setMatcherRuleId(r);
      setCreateOpen(true);
    }
  }, [searchParams]);

  const resetForm = () => {
    setReason('');
    setMatcherRuleId('');
    setMatcherAppSlug('');
    setHours(1);
  };

  const closeModal = () => {
    setCreateOpen(false);
    resetForm();
  };

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

  const rows = data ?? [];

  const onCreate = async () => {
    const now = new Date();
    const endsAt = new Date(now.getTime() + hours * 3600_000);
    const matcher: Record<string, string> = {};
    if (matcherRuleId) matcher.ruleId = matcherRuleId;
    if (matcherAppSlug) matcher.appSlug = matcherAppSlug;
    if (Object.keys(matcher).length === 0) {
      toast({ title: 'Silence needs at least one matcher field', variant: 'error' });
      return;
    }
    try {
      await create.mutateAsync({
        matcher,
        reason: reason || undefined,
        startsAt: now.toISOString(),
        endsAt: endsAt.toISOString(),
      });
      closeModal();
      toast({ title: 'Silence created', variant: 'success' });
    } catch (e) {
      toast({ title: 'Create failed', description: describeApiError(e), variant: 'error' });
    }
  };

  const confirmEnd = async () => {
    if (!pendingEnd) return;
    try {
      await remove.mutateAsync(pendingEnd.id!);
      toast({ title: 'Silence removed', variant: 'success' });
    } catch (e) {
      toast({ title: 'Remove failed', description: describeApiError(e), variant: 'error' });
    } finally {
      setPendingEnd(null);
    }
  };

  const columns: Column<AlertSilenceResponse & { id: string }>[] = [
    {
      key: 'matcher', header: 'Matcher',
      render: (_, s) => <MonoText size="xs">{JSON.stringify(s.matcher)}</MonoText>,
    },
    { key: 'reason', header: 'Reason', render: (_, s) => s.reason ?? '—' },
    { key: 'startsAt', header: 'Starts', width: '200px' },
    { key: 'endsAt', header: 'Ends', width: '200px' },
    {
      key: 'actions', header: '', width: '90px',
      render: (_, s) => (
        <Button variant="ghost" size="sm" onClick={() => setPendingEnd(s)}>
          End early
        </Button>
      ),
    },
  ];

  return (
    <div className={css.page}>
      <header className={css.pageHeader}>
        <div className={css.pageTitleGroup}>
          <h2 className={css.pageTitle}>Alert silences</h2>
          <span className={css.pageSubtitle}>
            {rows.length === 0
              ? 'Nothing silenced right now'
              : `${rows.length} active silence${rows.length === 1 ? '' : 's'}`}
          </span>
        </div>
        <div className={css.pageActions}>
          <Button variant="primary" onClick={() => setCreateOpen(true)}>New silence</Button>
        </div>
      </header>

      {rows.length === 0 ? (
        <EmptyState
          icon={<BellOff size={32} />}
          title="No silences"
          description="Nothing is currently silenced in this environment."
          action={
            <Button variant="primary" onClick={() => setCreateOpen(true)}>Create silence</Button>
          }
        />
      ) : (
        <div className={`${tableStyles.tableSection} ${css.tableWrap}`}>
          <DataTable<AlertSilenceResponse & { id: string }>
            columns={columns}
            data={rows.map((s) => ({ ...s, id: s.id ?? '' }))}
            flush
            fillHeight
          />
        </div>
      )}

      <Modal
        open={createOpen}
        onClose={closeModal}
        title="New silence"
        size="md"
      >
        <div style={{ display: 'grid', gap: 'var(--space-md)' }}>
          <FormField label="Rule ID" hint="Exact rule id (optional)">
            <Input value={matcherRuleId} onChange={(e) => setMatcherRuleId(e.target.value)} />
          </FormField>
          <FormField label="App slug" hint="App slug (optional)">
            <Input value={matcherAppSlug} onChange={(e) => setMatcherAppSlug(e.target.value)} />
          </FormField>
          <FormField label="Duration" hint="Hours">
            <Input
              type="number"
              min={1}
              value={hours}
              onChange={(e) => setHours(Number(e.target.value))}
            />
          </FormField>
          <FormField label="Reason" hint="Context for operators">
            <Input
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              placeholder="Maintenance window"
            />
          </FormField>
          <div style={{ display: 'flex', gap: 'var(--space-sm)', justifyContent: 'flex-end' }}>
            <Button variant="ghost" onClick={closeModal} disabled={create.isPending}>Cancel</Button>
            <Button variant="primary" onClick={onCreate} disabled={create.isPending}>
              Create silence
            </Button>
          </div>
        </div>
      </Modal>

      <ConfirmDialog
        open={!!pendingEnd}
        onClose={() => setPendingEnd(null)}
        onConfirm={confirmEnd}
        title="End silence?"
        message="End this silence early? Affected rules will resume firing."
        confirmText="End silence"
        variant="warning"
        loading={remove.isPending}
      />
    </div>
  );
}
