import * as React from 'react';
import { Link } from 'react-router-dom';
import { Inbox, ScrollText, Sparkles } from 'lucide-react';

import { api, type Proposal } from '../api';
import { Card, CardContent } from '../components/ui/card';
import { Badge } from '../components/ui/badge';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '../components/ui/tabs';

export function ProposalsPage(): React.JSX.Element {
  const [proposals, setProposals] = React.useState<Proposal[] | null>(null);
  const [error, setError] = React.useState<string | null>(null);
  const [tab, setTab] = React.useState<'pending' | 'approved' | 'rejected'>('pending');

  React.useEffect(() => {
    let cancelled = false;
    async function load(): Promise<void> {
      try {
        const data = await api.get<Proposal[]>('/api/v1/proposals');
        if (!cancelled) setProposals(data);
      } catch (err) {
        if (!cancelled) setError((err as Error).message);
      }
    }
    void load();
    const id = setInterval(load, 30_000);
    return () => { cancelled = true; clearInterval(id); };
  }, []);

  if (error !== null) return <div className="text-(--color-danger)">Error: {error}</div>;
  if (proposals === null) return <div className="text-(--color-fg-muted)">Loading proposals…</div>;

  const pending = proposals.filter((p) => p.status === 'pending');
  const approved = proposals.filter((p) => p.status === 'approved');
  const rejected = proposals.filter((p) => p.status === 'rejected');

  return (
    <div className="space-y-6">
      <header className="space-y-1">
        <h1 className="text-2xl font-semibold tracking-tight">Proposals</h1>
        <p className="text-sm text-(--color-fg-muted)">
          Prompts and skills proposed by Claude sessions or human authors. Approve to materialise; reject to dismiss.
        </p>
      </header>

      <Tabs value={tab} onValueChange={(v) => setTab(v as typeof tab)}>
        <TabsList>
          <TabsTrigger value="pending">
            Pending {pending.length > 0 && <span className="ml-1 text-(--color-warning)">({pending.length})</span>}
          </TabsTrigger>
          <TabsTrigger value="approved">Approved ({approved.length})</TabsTrigger>
          <TabsTrigger value="rejected">Rejected ({rejected.length})</TabsTrigger>
        </TabsList>

        <TabsContent value="pending">
          <ProposalList list={pending} emptyText="No pending proposals." />
        </TabsContent>
        <TabsContent value="approved">
          <ProposalList list={approved} emptyText="No approved proposals yet." />
        </TabsContent>
        <TabsContent value="rejected">
          <ProposalList list={rejected} emptyText="No rejected proposals." />
        </TabsContent>
      </Tabs>
    </div>
  );
}

function ProposalList({ list, emptyText }: { list: Proposal[]; emptyText: string }): React.JSX.Element {
  if (list.length === 0) {
    return (
      <Card>
        <CardContent className="flex items-center justify-center gap-2 p-8 text-(--color-fg-muted)">
          <Inbox className="size-4" /> {emptyText}
        </CardContent>
      </Card>
    );
  }
  return (
    <div className="space-y-2">
      {list.map((p) => <ProposalRow key={p.id} proposal={p} />)}
    </div>
  );
}

function ProposalRow({ proposal }: { proposal: Proposal }): React.JSX.Element {
  const Icon = proposal.resourceType === 'skill' ? Sparkles : ScrollText;
  const scope =
    proposal.project?.name
      ? `project: ${proposal.project.name}`
      : proposal.agent?.name
        ? `agent: ${proposal.agent.name}`
        : 'global';
  const statusVariant =
    proposal.status === 'pending' ? 'warning' : proposal.status === 'approved' ? 'success' : 'danger';

  return (
    <Link to={`/proposals/${proposal.id}`}>
      <Card className="transition-colors hover:bg-(--color-surface-hi)">
        <CardContent className="flex items-center justify-between gap-4 p-4">
          <div className="flex items-center gap-3 min-w-0">
            <Icon className="size-4 shrink-0 text-(--color-fg-muted)" />
            <div className="min-w-0">
              <div className="flex items-center gap-2">
                <span className="font-mono text-sm font-medium truncate">{proposal.name}</span>
                <Badge variant="outline">{proposal.resourceType}</Badge>
              </div>
              <div className="text-xs text-(--color-fg-subtle)">
                {scope} · session{' '}
                <code className="font-mono">{(proposal.createdBySession ?? '—').slice(0, 8)}</code>
              </div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-xs text-(--color-fg-subtle)">
              {ageOf(proposal.createdAt)}
            </span>
            <Badge variant={statusVariant}>{proposal.status}</Badge>
          </div>
        </CardContent>
      </Card>
    </Link>
  );
}

function ageOf(iso: string): string {
  const t = Date.parse(iso);
  if (Number.isNaN(t)) return '?';
  const sec = Math.floor((Date.now() - t) / 1000);
  if (sec < 60) return `${String(sec)}s`;
  const min = Math.floor(sec / 60);
  if (min < 60) return `${String(min)}m`;
  const hr = Math.floor(min / 60);
  if (hr < 24) return `${String(hr)}h`;
  return `${String(Math.floor(hr / 24))}d`;
}
