import { useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  AlertCircle,
  ArrowLeft,
  Braces,
  Clipboard,
  Code2,
  FileJson,
  FileSpreadsheet,
  FileText,
  RefreshCw,
} from "lucide-react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { useExportJson } from "@/hooks/usePlatform";
import { useProject } from "@/hooks/useProjects";
import { platformApi } from "@/lib/api/platform";
import { formatDateTime, formatPercent, humanizeValue } from "@/lib/display";
import { cn } from "@/lib/utils";

const statusOptions = [
  { value: "validated_claim", label: "Validated claims" },
  { value: "active", label: "Active claims" },
  { value: "candidate_claim", label: "Candidate claims" },
  { value: "rule_candidate", label: "Rule candidates" },
  { value: "rejected", label: "Rejected claims" },
  { value: "all", label: "All statuses" },
];

function valueFrom(row: Record<string, unknown>, key: string): string {
  return humanizeValue(row[key]);
}

export default function ExportApiPage() {
  const navigate = useNavigate();
  const { projectId } = useParams<{ projectId: string }>();
  const projectName = projectId ?? "";
  const { data: project } = useProject(projectName);
  const [status, setStatus] = useState("validated_claim");
  const [includeEvidence, setIncludeEvidence] = useState(true);
  const [limit, setLimit] = useState(1000);
  const [copied, setCopied] = useState<string | null>(null);
  const exportData = useExportJson(projectName, {
    status,
    includeEvidence,
    limit,
  });

  const urls = useMemo(
    () => ({
      json: platformApi.exportUrl(
        projectName,
        "json",
        status,
        includeEvidence,
        limit,
      ),
      csv: platformApi.exportUrl(
        projectName,
        "csv",
        status,
        includeEvidence,
        limit,
      ),
      turtle: platformApi.exportUrl(
        projectName,
        "turtle",
        status,
        includeEvidence,
        limit,
      ),
    }),
    [includeEvidence, limit, projectName, status],
  );
  const origin =
    typeof window !== "undefined" && window.location?.origin
      ? window.location.origin
      : "";
  const absoluteJsonUrl = `${origin}${urls.json}`;
  const curlSnippet = `curl -L "${absoluteJsonUrl}"`;
  const fetchSnippet = `const response = await fetch("${urls.json}");\nconst ontology = await response.json();`;
  const previewRows = exportData.data?.claims.slice(0, 8) ?? [];
  const avgConfidence = exportData.data?.claims.length
    ? exportData.data.claims.reduce((sum, row) => {
        const confidence = row.confidence;
        return sum + (typeof confidence === "number" ? confidence : 0);
      }, 0) / exportData.data.claims.length
    : 0;

  async function copy(text: string, key: string) {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(key);
      window.setTimeout(() => setCopied(null), 1600);
    } catch {
      setCopied("failed");
    }
  }

  return (
    <div className="mx-auto max-w-7xl px-6 py-8">
      <div className="mb-6 flex items-center gap-3">
        <Button
          variant="ghost"
          size="icon"
          onClick={() => navigate(`/graph/${projectName}`)}
          aria-label="Back"
        >
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div className="flex-1">
          <h1 className="flex items-center gap-2 text-2xl font-bold tracking-tight">
            <Code2 className="h-6 w-6 text-primary" />
            Export / API Center
          </h1>
          <p className="text-sm text-muted-foreground">
            {project?.name ?? projectName} exports, endpoint settings, and integration snippets.
          </p>
        </div>
        <Button variant="outline" onClick={() => exportData.refetch()}>
          <RefreshCw className="h-4 w-4" />
          Refresh
        </Button>
      </div>

      {exportData.isError && (
        <Card className="mb-6 border-destructive">
          <CardContent className="flex items-center gap-2 py-4 text-sm text-destructive">
            <AlertCircle className="h-4 w-4" />
            {(exportData.error as Error).message}
          </CardContent>
        </Card>
      )}

      <div className="mb-6 grid gap-3 lg:grid-cols-[220px_180px_1fr_180px]">
        <Select value={status} onChange={(event) => setStatus(event.target.value)}>
          {statusOptions.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </Select>
        <Input
          type="number"
          min={1}
          max={5000}
          value={limit}
          onChange={(event) =>
            setLimit(Math.max(1, Math.min(5000, Number(event.target.value) || 1)))
          }
          aria-label="Export row limit"
        />
        <label className="flex items-center gap-2 rounded-md border px-3 text-sm">
          <input
            type="checkbox"
            checked={includeEvidence}
            onChange={(event) => setIncludeEvidence(event.target.checked)}
          />
          Include evidence text
        </label>
        <Badge variant="outline" className="justify-center py-2">
          {exportData.data?.count ?? 0} rows
        </Badge>
      </div>

      <div className="mb-6 grid gap-4 md:grid-cols-3">
        <Card>
          <CardContent className="py-4">
            <div className="text-xs text-muted-foreground">Export rows</div>
            <div className="mt-1 text-3xl font-semibold">
              {(exportData.data?.count ?? 0).toLocaleString()}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <div className="text-xs text-muted-foreground">Status scope</div>
            <div className="mt-1 text-lg font-semibold">
              {statusOptions.find((option) => option.value === status)?.label}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <div className="text-xs text-muted-foreground">Avg confidence</div>
            <div className="mt-1 text-3xl font-semibold">
              {formatPercent(avgConfidence)}
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-6 xl:grid-cols-[1fr_380px]">
        <Card>
          <CardHeader>
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div>
                <CardTitle>Export Preview</CardTitle>
                <CardDescription>
                  First rows from the JSON export endpoint.
                </CardDescription>
              </div>
              <div className="flex flex-wrap gap-2">
                <DownloadLink href={urls.json} icon={FileJson} label="JSON" />
                <DownloadLink href={urls.csv} icon={FileSpreadsheet} label="CSV" />
                <DownloadLink href={urls.turtle} icon={FileText} label="Turtle" />
              </div>
            </div>
          </CardHeader>
          <CardContent>
            {exportData.isLoading ? (
              <div className="space-y-3">
                {Array.from({ length: 5 }).map((_, index) => (
                  <Skeleton key={index} className="h-16" />
                ))}
              </div>
            ) : previewRows.length === 0 ? (
              <div className="py-12 text-center text-sm text-muted-foreground">
                No export rows match the current settings.
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-left text-sm">
                  <thead className="border-b text-xs text-muted-foreground">
                    <tr>
                      <th className="py-2 pr-3">Claim</th>
                      <th className="py-2 pr-3">Subject</th>
                      <th className="py-2 pr-3">Predicate</th>
                      <th className="py-2 pr-3">Object</th>
                      <th className="py-2 pr-3">Confidence</th>
                      <th className="py-2 pr-3">Last seen</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {previewRows.map((row, index) => (
                      <tr key={`${valueFrom(row, "claim_id")}-${index}`}>
                        <td className="py-3 pr-3 font-medium">
                          #{valueFrom(row, "claim_id")}
                        </td>
                        <td className="max-w-[180px] truncate py-3 pr-3">
                          {valueFrom(row, "subject")}
                        </td>
                        <td className="py-3 pr-3">
                          <Badge variant="secondary">
                            {valueFrom(row, "predicate")}
                          </Badge>
                        </td>
                        <td className="max-w-[220px] truncate py-3 pr-3">
                          {valueFrom(row, "object")}
                        </td>
                        <td className="py-3 pr-3">
                          {typeof row.confidence === "number"
                            ? formatPercent(row.confidence)
                            : "-"}
                        </td>
                        <td className="py-3 pr-3">
                          {formatDateTime(
                            typeof row.last_seen_at === "string"
                              ? row.last_seen_at
                              : undefined,
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>

        <aside className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Braces className="h-5 w-5" />
                API Endpoint
              </CardTitle>
              <CardDescription>Same settings as the preview.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              <CodeBlock value={absoluteJsonUrl} />
              <Button
                variant="outline"
                className="w-full"
                onClick={() => copy(absoluteJsonUrl, "endpoint")}
              >
                <Clipboard className="h-4 w-4" />
                {copied === "endpoint" ? "Copied" : "Copy endpoint"}
              </Button>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Integration Snippets</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <Snippet
                title="cURL"
                value={curlSnippet}
                copied={copied === "curl"}
                onCopy={() => copy(curlSnippet, "curl")}
              />
              <Snippet
                title="JavaScript"
                value={fetchSnippet}
                copied={copied === "fetch"}
                onCopy={() => copy(fetchSnippet, "fetch")}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Formats</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2 text-sm">
              <FormatRow label="JSON" detail="API-first claim objects with evidence." />
              <FormatRow label="CSV" detail="Spreadsheet-friendly rows for review." />
              <FormatRow label="Turtle" detail="RDF triples for semantic graph tools." />
            </CardContent>
          </Card>
        </aside>
      </div>
    </div>
  );
}

function DownloadLink({
  href,
  icon: Icon,
  label,
}: {
  href: string;
  icon: React.ComponentType<{ className?: string }>;
  label: string;
}) {
  return (
    <a
      href={href}
      className={cn(buttonVariants({ variant: "outline", size: "sm" }))}
    >
      <Icon className="h-4 w-4" />
      {label}
    </a>
  );
}

function CodeBlock({ value }: { value: string }) {
  return (
    <pre className="max-h-40 overflow-auto rounded-md bg-secondary/40 p-3 text-xs">
      <code>{value}</code>
    </pre>
  );
}

function Snippet({
  title,
  value,
  copied,
  onCopy,
}: {
  title: string;
  value: string;
  copied: boolean;
  onCopy: () => void;
}) {
  return (
    <div className="rounded-md border p-3">
      <div className="mb-2 flex items-center justify-between gap-2">
        <span className="text-sm font-medium">{title}</span>
        <Button variant="ghost" size="sm" onClick={onCopy}>
          <Clipboard className="h-4 w-4" />
          {copied ? "Copied" : "Copy"}
        </Button>
      </div>
      <CodeBlock value={value} />
    </div>
  );
}

function FormatRow({ label, detail }: { label: string; detail: string }) {
  return (
    <div className="rounded-md border px-3 py-2">
      <div className="font-medium">{label}</div>
      <div className="text-xs text-muted-foreground">{detail}</div>
    </div>
  );
}
