"use client"

import { useState, useEffect } from "react"
import Link from "next/link"
import { Plus, Edit, Trash2, FileText, Loader2, Search, ExternalLink } from "lucide-react"
import Swal from "sweetalert2";

type Page = {
  id: string
  title: string
  slug: string
  published: boolean
  updatedAt: string
}

export default async function AdminPagesList() {
  const [pages, setPages] = useState<Page[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState("")

  useEffect(() => {
    fetchPages()
  }, [])

  const fetchPages = async () => {
    try {
      const res = await fetch("/api/admin/pages", { cache: "no-store" })
      const data = await res.json()
      if (res.ok && Array.isArray(data)) {
        setPages(data)
      } else {
        console.error("API returned non-array:", data)
        setPages([])
      }
    } catch (err) {
      console.error(err)
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (id: string) => {
    if (!(await Swal.fire({ title: "Are you sure?", text: "Are you sure you want to delete this page?", icon: "warning", showCancelButton: true, confirmButtonColor: "#18181b", cancelButtonColor: "#ef4444", confirmButtonText: "Yes" })).isConfirmed) return
    try {
      const res = await fetch(`/api/admin/pages/${id}`, { method: "DELETE" })
      if (!res.ok) throw new Error("Failed to delete")
      setPages(pages.filter(p => p.id !== id))
    } catch (err: any) {
      Swal.fire({ text: err.message, confirmButtonColor: "#18181b" })
    }
  }

  const filteredPages = pages.filter(p => 
    p.title.toLowerCase().includes(search.toLowerCase()) || 
    p.slug.toLowerCase().includes(search.toLowerCase())
  )

  if (loading) return <div className="flex h-64 items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-zinc-400" /></div>

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-black uppercase tracking-tight text-zinc-950">Dynamic Pages</h1>
          <p className="text-sm text-zinc-500 mt-1">Manage custom pages like Privacy Policy, Terms of Use, etc.</p>
        </div>
        <Link 
          href="/admin/pages/new" 
          className="flex items-center gap-2 rounded-sm bg-zinc-950 px-5 py-2.5 text-xs font-bold uppercase tracking-widest text-white hover:bg-zinc-800 transition-colors"
        >
          <Plus className="h-4 w-4" /> Add New Page
        </Link>
      </div>

      <div className="flex items-center gap-4 bg-white border border-zinc-200 rounded-lg p-3">
        <Search className="w-5 h-5 text-zinc-400 ml-2" />
        <input 
          type="text" 
          placeholder="Search pages by title or slug..." 
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="flex-1 bg-transparent border-none focus:outline-none text-sm"
        />
      </div>

      <div className="bg-white border border-zinc-200 rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm whitespace-nowrap">
            <thead className="bg-zinc-50 border-b border-zinc-200">
              <tr>
                <th className="px-6 py-4 font-bold uppercase tracking-widest text-[10px] text-zinc-500">Title</th>
                <th className="px-6 py-4 font-bold uppercase tracking-widest text-[10px] text-zinc-500">Slug / URL</th>
                <th className="px-6 py-4 font-bold uppercase tracking-widest text-[10px] text-zinc-500">Status</th>
                <th className="px-6 py-4 font-bold uppercase tracking-widest text-[10px] text-zinc-500">Last Updated</th>
                <th className="px-6 py-4 font-bold uppercase tracking-widest text-[10px] text-zinc-500 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-100">
              {filteredPages.length === 0 ? (
                <tr>
                  <td colSpan={5} className="px-6 py-12 text-center text-zinc-500">
                    <div className="flex flex-col items-center justify-center">
                      <FileText className="w-12 h-12 text-zinc-300 mb-4" />
                      <p>No pages found.</p>
                    </div>
                  </td>
                </tr>
              ) : (
                filteredPages.map(page => (
                  <tr key={page.id} className="hover:bg-zinc-50/50 transition-colors">
                    <td className="px-6 py-4 font-medium text-zinc-900">{page.title}</td>
                    <td className="px-6 py-4 text-zinc-500 font-mono text-xs">/pages/{page.slug}</td>
                    <td className="px-6 py-4">
                      <span className={`inline-flex items-center px-2 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest ${page.published ? 'bg-emerald-100 text-emerald-700' : 'bg-zinc-100 text-zinc-600'}`}>
                        {page.published ? 'Published' : 'Draft'}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-zinc-500">{new Date(page.updatedAt).toLocaleDateString()}</td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Link 
                          href={`/pages/${page.slug}`} 
                          target="_blank"
                          className="p-2 text-zinc-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors"
                          title="View Page"
                        >
                          <ExternalLink className="w-4 h-4" />
                        </Link>
                        <Link 
                          href={`/admin/pages/${page.id}`} 
                          className="p-2 text-zinc-400 hover:text-zinc-900 hover:bg-zinc-100 rounded transition-colors"
                        >
                          <Edit className="w-4 h-4" />
                        </Link>
                        <button 
                          onClick={() => handleDelete(page.id)}
                          className="p-2 text-zinc-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
