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

import { api, type Skill, type Proposal, type Project, type Agent } from '../api';
import { Card, CardContent, CardHeader, CardTitle } from '../components/ui/card';
import { Badge } from '../components/ui/badge';

/**
 * At-a-glance home page. Counts come from the `/api/v1/<resource>`
 * lists; pending proposals are highlighted with an amber badge to draw
 * the reviewer in.
 */
export function DashboardPage(): React.JSX.Element {
  const [counts, setCounts] = React.useState<{
    skills: number;
    proposals: { pending: number; approved: number; rejected: number };
    projects: number;
    agents: number;
    prompts: number;
  } | null>(null);
  const [error, setError] = React.useState<string | null>(null);

  React.useEffect(() => {
    let cancelled = false;
    async function load(): Promise<void> {
      try {
        const [skills, proposals, projects, agents, prompts] = await Promise.all([
          api.get<Skill[]>('/api/v1/skills'),
          api.get<Proposal[]>('/api/v1/proposals'),
          api.get<Project[]>('/api/v1/projects'),
          api.get<Agent[]>('/api/v1/agents'),
          api.get<unknown[]>('/api/v1/prompts'),
        ]);
        if (cancelled) return;
        setCounts({
          skills: skills.length,
          proposals: {
            pending: proposals.filter((p) => p.status === 'pending').length,
            approved: proposals.filter((p) => p.status === 'approved').length,
            rejected: proposals.filter((p) => p.status === 'rejected').length,
          },
          projects: projects.length,
          agents: agents.length,
          prompts: prompts.length,
        });
      } catch (err) {
        if (!cancelled) setError((err as Error).message);
      }
    }
    void load();
    return () => { cancelled = true; };
  }, []);

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

  return (
    <div className="space-y-6">
      <header className="space-y-1">
        <h1 className="text-2xl font-semibold tracking-tight">Dashboard</h1>
        <p className="text-sm text-(--color-fg-muted)">
          A glance at what's in mcpd. Numbers update on page load.
        </p>
      </header>

      {counts.proposals.pending > 0 && (
        <Link to="/proposals">
          <Card className="border-(--color-warning)/40 bg-(--color-warning-bg)/30 transition-colors hover:bg-(--color-warning-bg)/50">
            <CardContent className="flex items-center gap-4 p-5 pt-5">
              <Inbox className="size-6 text-(--color-warning)" />
              <div className="flex-1">
                <div className="font-medium text-(--color-fg)">
                  {counts.proposals.pending}{' '}
                  pending {counts.proposals.pending === 1 ? 'proposal' : 'proposals'}
                </div>
                <div className="text-sm text-(--color-fg-muted)">
                  Review the queue to approve or reject incoming changes.
                </div>
              </div>
              <Badge variant="warning">Review</Badge>
            </CardContent>
          </Card>
        </Link>
      )}

      <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
        <CountCard to="/skills" icon={Sparkles} label="Skills" value={counts.skills} />
        <CountCard to="/projects" icon={FolderKanban} label="Projects" value={counts.projects} />
        <CountCard to="/agents" icon={Bot} label="Agents" value={counts.agents} />
        <CountCard to="/projects" icon={ScrollText} label="Prompts" value={counts.prompts} />
        <CountCard
          to="/proposals"
          icon={Inbox}
          label="Proposals"
          value={counts.proposals.pending + counts.proposals.approved + counts.proposals.rejected}
          subtitle={`${counts.proposals.pending} pending · ${counts.proposals.approved} approved · ${counts.proposals.rejected} rejected`}
        />
      </div>
    </div>
  );
}

function CountCard({
  to,
  icon: Icon,
  label,
  value,
  subtitle,
}: {
  to: string;
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  value: number;
  subtitle?: string;
}): React.JSX.Element {
  return (
    <Link to={to} className="block">
      <Card className="transition-colors hover:bg-(--color-surface-hi)">
        <CardHeader className="flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium text-(--color-fg-muted)">{label}</CardTitle>
          <Icon className="size-4 text-(--color-fg-muted)" />
        </CardHeader>
        <CardContent>
          <div className="font-mono text-3xl font-semibold tabular-nums">{value}</div>
          {subtitle !== undefined && (
            <p className="mt-1 text-xs text-(--color-fg-muted)">{subtitle}</p>
          )}
        </CardContent>
      </Card>
    </Link>
  );
}
