"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Plus, Edit, Pin, Trash2 } from "lucide-react";

interface NewsItem {
  id: string;
  title: string;
  slug: string;
  isPinned: boolean;
  isActive: boolean;
  createdAt: string;
}

export default function AdminNews() {
  const router = useRouter();
  const [news, setNews] = useState<NewsItem[]>([]);

  const load = () => {
    fetch("/api/news", {
      headers: { Authorization: `Bearer ${localStorage.getItem("auth_token")}` },
    })
      .then((r) => r.json())
      .then((data) => { if (Array.isArray(data)) setNews(data); })
      .catch(() => {});
  };

  useEffect(load, []);

  const handleDelete = async (slug: string) => {
    if (!confirm("حذف شود؟")) return;
    const token = localStorage.getItem("auth_token");
    const res = await fetch(`/api/news/${slug}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.ok) load();
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">مدیریت اخبار</h1>
        <Button className="bg-[#2563EB] hover:bg-[#1D4ED8]" onClick={() => router.push("/dashboard/admin/news/new")}>
          <Plus className="h-4 w-4 ml-1" />
          خبر جدید
        </Button>
      </div>

      <div className="rounded-xl border bg-white overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-gray-600">
            <tr>
              <th className="text-right p-3 font-medium">عنوان</th>
              <th className="text-right p-3 font-medium">وضعیت</th>
              <th className="text-right p-3 font-medium">تاریخ</th>
              <th className="text-left p-3 font-medium">عملیات</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {news.map((item) => (
              <tr key={item.id}>
                <td className="p-3 font-medium text-gray-900">
                  <div className="flex items-center gap-2">
                    {item.isPinned && <Pin className="h-3.5 w-3.5 text-red-500" />}
                    {item.title}
                  </div>
                </td>
                <td className="p-3">
                  <span className={`text-xs ${item.isActive ? "text-green-600" : "text-red-600"}`}>
                    {item.isActive ? "منتشر شده" : "پیش‌نویس"}
                  </span>
                </td>
                <td className="p-3 text-gray-500">{new Date(item.createdAt).toLocaleDateString("fa-IR")}</td>
                <td className="p-3 text-left">
                  <div className="flex items-center justify-end gap-1">
                    <Button variant="ghost" size="icon-xs" onClick={() => router.push(`/dashboard/admin/news/${item.slug}`)}>
                      <Edit className="h-3.5 w-3.5" />
                    </Button>
                    <Button variant="ghost" size="icon-xs" onClick={() => handleDelete(item.slug)}>
                      <Trash2 className="h-3.5 w-3.5 text-red-500" />
                    </Button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
