import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import { PageHeader } from "@/components/common/PageHeader";
import { AdminDataTable, type Column } from "@/components/common/AdminDataTable";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { news } from "@/features/_mock/data";
import type { NewsArticle } from "@/types";
import { Plus } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/admin/news")({
  head: () => ({ meta: [{ title: "News — Admin" }, { name: "description", content: "Publish and manage news articles." }] }),
  component: AdminNewsPage,
});

type Row = NewsArticle & { published: boolean };
const rows: Row[] = news.map((n, i) => ({ ...n, published: i !== 3 }));

function AdminNewsPage() {
  const [q, setQ] = useState("");
  const [items, setItems] = useState<Row[]>(rows);
  const filtered = useMemo(() => items.filter((r) => q === "" || r.title.toLowerCase().includes(q.toLowerCase()) || r.category.toLowerCase().includes(q.toLowerCase())), [q, items]);

  const cols: Column<Row>[] = [
    { key: "cov", header: "", cell: (r) => <div className="grid h-10 w-10 place-items-center rounded-md bg-surface-elevated text-lg">{r.cover}</div> },
    { key: "t", header: "Article", cell: (r) => <div><div className="font-medium">{r.title}</div><div className="text-xs text-muted-foreground line-clamp-1">{r.excerpt}</div></div> },
    { key: "cat", header: "Category", cell: (r) => <Badge variant="outline">{r.category}</Badge> },
    { key: "a", header: "Author", cell: (r) => r.author },
    { key: "d", header: "Date", cell: (r) => <span className="text-muted-foreground">{r.date}</span> },
    { key: "v", header: "Views", cell: (r) => <span className="font-mono">{r.views.toLocaleString()}</span> },
    { key: "on", header: "Published", cell: (r) => <Switch checked={r.published} onCheckedChange={(v) => setItems((xs) => xs.map((x) => x.id === r.id ? { ...x, published: v } : x))} /> },
  ];

  return (
    <div>
      <PageHeader title="News" description="Publish and manage news articles." actions={<Button className="gradient-primary text-primary-foreground"><Plus className="mr-1 h-4 w-4" /> New article</Button>} />
      <AdminDataTable
        rows={filtered} columns={cols} search={q} onSearchChange={setQ}
        rowActions={(r) => (
          <div className="flex justify-end gap-1">
            <Button size="sm" variant="outline">Edit</Button>
            <Button size="sm" variant="ghost" onClick={() => toast.success(`Duplicated ${r.title}`)}>Duplicate</Button>
            <Button size="sm" variant="ghost" className="text-destructive">Delete</Button>
          </div>
        )}
      />
    </div>
  );
}
