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

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

export function SkillsPage(): React.JSX.Element {
  const [skills, setSkills] = React.useState<Skill[] | null>(null);
  const [error, setError] = React.useState<string | null>(null);

  React.useEffect(() => {
    let cancelled = false;
    async function load(): Promise<void> {
      try {
        const data = await api.get<Skill[]>('/api/v1/skills');
        if (!cancelled) setSkills(data);
      } 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 (skills === null) return <div className="text-(--color-fg-muted)">Loading skills…</div>;

  const sorted = [...skills].sort((a, b) => a.name.localeCompare(b.name));
  const globals = sorted.filter((s) => s.projectId === null && s.agentId === null);
  const scoped = sorted.filter((s) => s.projectId !== null || s.agentId !== null);

  return (
    <div className="space-y-6">
      <header className="flex items-end justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Skills</h1>
          <p className="text-sm text-(--color-fg-muted)">
            Materialised onto every dev box by <code className="font-mono text-xs">mcpctl skills sync</code>.
          </p>
        </div>
        <span className="text-sm text-(--color-fg-muted)">
          {sorted.length} {sorted.length === 1 ? 'skill' : 'skills'}
        </span>
      </header>

      {sorted.length === 0 && (
        <Card>
          <CardContent className="p-8 text-center text-(--color-fg-muted)">
            No skills defined yet. Create one with{' '}
            <code className="rounded bg-(--color-surface-hi) px-1 py-0.5 font-mono text-xs">
              mcpctl create skill {'<name>'}
            </code>
            .
          </CardContent>
        </Card>
      )}

      {globals.length > 0 && (
        <section className="space-y-3">
          <h2 className="text-xs font-semibold uppercase tracking-wider text-(--color-fg-muted)">
            Global
          </h2>
          <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
            {globals.map((s) => <SkillCard key={s.id} skill={s} />)}
          </div>
        </section>
      )}

      {scoped.length > 0 && (
        <section className="space-y-3">
          <h2 className="text-xs font-semibold uppercase tracking-wider text-(--color-fg-muted)">
            Project- and agent-scoped
          </h2>
          <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
            {scoped.map((s) => <SkillCard key={s.id} skill={s} />)}
          </div>
        </section>
      )}
    </div>
  );
}

function SkillCard({ skill }: { skill: Skill }): React.JSX.Element {
  const ScopeIcon =
    skill.projectId !== null ? FolderKanban : skill.agentId !== null ? Bot : Globe;
  const scopeLabel =
    skill.project?.name
      ? `project: ${skill.project.name}`
      : skill.agent?.name
        ? `agent: ${skill.agent.name}`
        : 'global';

  return (
    <Link to={`/skills/${encodeURIComponent(skill.name)}`}>
      <Card className="h-full transition-colors hover:bg-(--color-surface-hi)">
        <CardHeader className="space-y-2">
          <div className="flex items-start justify-between gap-2">
            <CardTitle className="font-mono text-sm">
              <Sparkles className="mr-1.5 inline size-3.5 text-(--color-primary)" />
              {skill.name}
            </CardTitle>
            <Badge variant="info">v{skill.semver}</Badge>
          </div>
          {skill.description && (
            <p className="text-sm text-(--color-fg-muted) line-clamp-2">{skill.description}</p>
          )}
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-1.5 text-xs text-(--color-fg-subtle)">
            <ScopeIcon className="size-3" />
            <span>{scopeLabel}</span>
          </div>
        </CardContent>
      </Card>
    </Link>
  );
}
