"use client";

import { useState, useCallback } from "react";
import Link from "next/link";
import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ALL_PAGES_ADMIN } from "@/lib/strings";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { TableSkeleton } from "@/roles/admin/components/table-skeleton";
import { AllPagesTable } from "./all-pages-table";
import type { AdminPageItem } from "./all-pages-table";
import {
  getStaticPagesListAction,
  deleteStaticPageAction,
} from "@/features/static-pages/actions/static-pages-actions";
import type {
  StaticPageListItem,
  StaticPageDetail,
} from "@/core/api/services/static-pages";
import { DeleteStaticPageDialog } from "./delete-static-page-dialog";

const LEGAL_PAGES_EDIT_BASE = "/admin/legal-pages";

function mapApiPageToAdminItem(p: StaticPageListItem): AdminPageItem {
  return {
    id: String(p.id ?? p.slug),
    name: p.title,
    href: `${LEGAL_PAGES_EDIT_BASE}/${p.slug}`,
    slug: p.slug,
    status: p.status ?? "",
    show_in_header: Number(p.show_in_header) === 1 ? 1 : 0,
    show_in_footer: Number(p.show_in_footer) === 1 ? 1 : 0,
    raw: p as StaticPageDetail,
  };
}

export interface AllPagesClientProps {
  /** When provided, list is not fetched on mount (avoids duplicate ADMIN_STATIC_PAGES call). */
  initialPages?: AdminPageItem[];
}

export function AllPagesClient({ initialPages = [] }: AllPagesClientProps) {
  const toast = useToastEnhanced();
  const [searchQuery, setSearchQuery] = useState("");
  const [pages, setPages] = useState<AdminPageItem[]>(initialPages);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deletingPage, setDeletingPage] = useState<AdminPageItem | null>(null);

  const loadPages = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    const result = await getStaticPagesListAction();
    if (result.success && Array.isArray(result.data)) {
      setPages(result.data.map(mapApiPageToAdminItem));
      setError(null);
    } else {
      setError(result.error ?? "Failed to load pages.");
      setPages([]);
    }
    setIsLoading(false);
  }, []);

  const handleDeletePage = useCallback(async () => {
    if (!deletingPage) return;
    try {
      const result = await deleteStaticPageAction(deletingPage.id);
      if (result.success) {
        toast.success({
          title: ALL_PAGES_ADMIN.PAGE_DELETED,
          description: ALL_PAGES_ADMIN.PAGE_DELETED_DESCRIPTION,
        });
        await loadPages();
      } else {
        toast.error({
          title: ALL_PAGES_ADMIN.ERROR_LOADING_PAGES,
          description: result.error ?? ALL_PAGES_ADMIN.FAILED_TO_DELETE,
        });
      }
    } catch {
      toast.error({
        title: ALL_PAGES_ADMIN.ERROR_LOADING_PAGES,
        description: ALL_PAGES_ADMIN.FAILED_TO_DELETE,
      });
    } finally {
      setDeletingPage(null);
    }
  }, [deletingPage, toast, loadPages]);

  return (
    <>
      <header className="admin-page-header flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 id="all-pages-heading" className="admin-page-title">
            {ALL_PAGES_ADMIN.PAGE_TITLE}
          </h1>
          <p className="admin-page-description">
            {ALL_PAGES_ADMIN.PAGE_DESCRIPTION}
          </p>
        </div>
        <Button asChild className="w-full sm:w-auto">
          <Link href="/admin/all-pages/add">
            <Plus className="mr-2 h-4 w-4" aria-hidden="true" />
            {ALL_PAGES_ADMIN.ADD_NEW_PAGE}
          </Link>
        </Button>
      </header>

      {isLoading ? (
        <TableSkeleton rows={8} columns={5} toolbarVariant="search10Page2" />
      ) : error ? (
        <div className="rounded-md border border-destructive/50 bg-destructive/10 p-4 text-destructive">
          <p className="font-medium">{ALL_PAGES_ADMIN.ERROR_LOADING_PAGES}</p>
          <p className="mt-1 text-sm">{error}</p>
        </div>
      ) : (
        <AllPagesTable
          pages={pages}
          searchQuery={searchQuery}
          onSearchChange={setSearchQuery}
          onDelete={setDeletingPage}
        />
      )}

      <DeleteStaticPageDialog
        page={deletingPage}
        open={!!deletingPage}
        onOpenChange={(open) => !open && setDeletingPage(null)}
        onConfirm={handleDeletePage}
      />
    </>
  );
}
