"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { Eye, EyeOff } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { DataTable, type Column } from "@/components/admin/DataTable";
import { PageHeader } from "@/components/admin/PageHeader";
import type { NewsArticle } from "@/lib/news";
import { fetchAllNews, deleteNews } from "@/lib/news";
import { toast } from "sonner";

function formatDate(dateStr: string) {
  return new Date(dateStr).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });
}

const columns: Column<NewsArticle>[] = [
  {
    key: "image_url",
    label: "Image",
    render: (item) =>
      item.image_url ? (
        <img
          src={item.image_url}
          alt={item.title}
          className="h-10 w-16 object-cover rounded"
        />
      ) : (
        <div className="h-10 w-16 rounded bg-muted flex items-center justify-center text-[10px] text-muted-foreground">
          No image
        </div>
      ),
  },
  {
    key: "title",
    label: "Title",
    render: (item) => (
      <div className="max-w-xs">
        <p className="font-medium text-foreground truncate">{item.title}</p>
        <p className="text-xs text-muted-foreground truncate mt-0.5">{item.excerpt}</p>
      </div>
    ),
  },
  {
    key: "category",
    label: "Category",
    render: (item) => item.category ? <Badge variant="secondary">{item.category.name}</Badge> : null,
  },
  {
    key: "author",
    label: "Author",
    render: (item) => <span className="text-sm text-muted-foreground">{item.author}</span>,
  },
  {
    key: "published_at",
    label: "Date",
    render: (item) => <span className="text-sm text-muted-foreground">{formatDate(item.published_at)}</span>,
  },
  {
    key: "is_published",
    label: "Status",
    render: (item) => (
      <Badge
        variant={item.is_published ? "default" : "outline"}
        className={item.is_published ? "bg-green-500/10 text-green-600 border-green-500/20" : ""}
      >
        {item.is_published ? <><Eye size={11} className="mr-1" />Published</> : <><EyeOff size={11} className="mr-1" />Draft</>}
      </Badge>
    ),
  },
];

export default function AdminNewsPage() {
  const router = useRouter();
  const [articles, setArticles] = useState<NewsArticle[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const loadArticles = (query?: string) => {
    setLoading(true);
    fetchAllNews(query)
      .then(setArticles)
      .catch(() => toast.error("Failed to load articles."))
      .finally(() => setLoading(false));
  };

  useEffect(() => { loadArticles(); }, []);

  const handleSearchChange = (value: string) => {
    setSearch(value);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => loadArticles(value || undefined), 400);
  };

  const handleDelete = async (item: NewsArticle) => {
    try {
      await deleteNews(item.id);
      setArticles((prev) => prev.filter((a) => a.id !== item.id));
      toast.success("Article deleted.");
    } catch {
      toast.error("Failed to delete article.");
    }
  };

  return (
    <div className="p-6 lg:p-8 max-w-7xl mx-auto space-y-6">
      <PageHeader
        title="News"
        description="Publish and manage news articles and company updates."
        onAdd={() => router.push("/admin/news/create")}
        addLabel="New Article"
      />

      <DataTable<NewsArticle>
        data={articles}
        columns={columns}
        searchPlaceholder="Search articles…"
        searchValue={search}
        onSearchChange={handleSearchChange}
        loading={loading}
        onEdit={(item) => router.push(`/admin/news/${item.id}/edit`)}
        onDelete={handleDelete}
      />
    </div>
  );
}
