"use client";

import { useState, useMemo } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  ChevronLeft,
  ChevronRight,
  ArrowUpDown,
  ArrowUp,
  ArrowDown,
  Pencil,
  Trash2,
  Check,
  X,
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ALL_PAGES_ADMIN } from "@/lib/strings";
import { Search } from "lucide-react";
import { EDIT_STATIC_PAGE_STORAGE_KEY } from "./add-legal-page-client";
import type { StaticPageDetail } from "@/core/api/services/static-pages";

export interface AdminPageItem {
  id: string;
  name: string;
  /** Full path for the Manage link (e.g. /admin/legal-pages/slug) */
  href: string;
  /** Slug only, shown in Route column (e.g. testing-legal-page) */
  slug: string;
  status: string;
  /** 1 = show in header, 0 = hide */
  show_in_header: number;
  /** 1 = show in footer, 0 = hide */
  show_in_footer: number;
  /** When set, Manage uses this data instead of loading from detail API */
  raw?: StaticPageDetail | null;
}

type SortField = "name" | "slug" | "status";
type SortDirection = "asc" | "desc";

const ITEMS_PER_PAGE_OPTIONS = [10, 20, 50, 100];

interface AllPagesTableProps {
  pages: AdminPageItem[];
  searchQuery: string;
  onSearchChange: (value: string) => void;
  onDelete: (page: AdminPageItem) => void;
}

export function AllPagesTable({
  pages,
  searchQuery,
  onSearchChange,
  onDelete,
}: AllPagesTableProps) {
  const router = useRouter();
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [sortField, setSortField] = useState<SortField>("name");
  const [sortDirection, setSortDirection] = useState<SortDirection>("asc");

  const handleEditClick = (page: AdminPageItem) => {
    if (page.raw) {
      sessionStorage.setItem(
        EDIT_STATIC_PAGE_STORAGE_KEY,
        JSON.stringify({ slug: page.slug, data: page.raw })
      );
      router.push(page.href);
      return true;
    }
    return false;
  };

  const filteredData = useMemo(() => {
    if (!searchQuery.trim()) return pages;
    const q = searchQuery.toLowerCase().trim();
    return pages.filter(
      (p) =>
        p.name.toLowerCase().includes(q) ||
        p.slug.toLowerCase().includes(q) ||
        p.status.toLowerCase().includes(q)
    );
  }, [pages, searchQuery]);

  const sortedData = useMemo(() => {
    return [...filteredData].sort((a, b) => {
      let comparison = 0;
      switch (sortField) {
        case "name":
          comparison = a.name.localeCompare(b.name);
          break;
        case "slug":
          comparison = a.slug.localeCompare(b.slug);
          break;
        case "status":
          comparison = a.status.localeCompare(b.status);
          break;
      }
      return sortDirection === "asc" ? comparison : -comparison;
    });
  }, [filteredData, sortField, sortDirection]);

  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return sortedData.slice(startIndex, startIndex + itemsPerPage);
  }, [sortedData, currentPage, itemsPerPage]);

  const totalPages = Math.ceil(sortedData.length / itemsPerPage);

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      setSortDirection("asc");
    }
  };

  const getSortIcon = (field: SortField) => {
    if (sortField !== field) {
      return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
    }
    return sortDirection === "asc" ? (
      <ArrowUp className="ml-1 h-3 w-3" />
    ) : (
      <ArrowDown className="ml-1 h-3 w-3" />
    );
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(Math.max(1, Math.min(page, totalPages)));
  };

  const handleItemsPerPageChange = (value: string) => {
    setItemsPerPage(Number(value));
    setCurrentPage(1);
  };

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-12 gap-4 items-center">
        <div className="col-span-12 sm:col-span-10 relative flex justify-start">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder={ALL_PAGES_ADMIN.SEARCH_PLACEHOLDER_TABLE}
            value={searchQuery}
            onChange={(e) => {
              onSearchChange(e.target.value);
              setCurrentPage(1);
            }}
            className="pl-9"
            aria-label={ALL_PAGES_ADMIN.SEARCH_ARIA}
          />
        </div>
        <div className="col-span-12 sm:col-span-2 flex items-center justify-end gap-2">
          <span
            className="text-sm text-muted-foreground whitespace-nowrap"
            aria-label={ALL_PAGES_ADMIN.GO_TO_PAGE}
          >
            {ALL_PAGES_ADMIN.PAGE} {currentPage}/{Math.max(1, totalPages)}
          </span>
          <Select
            value={String(itemsPerPage)}
            onValueChange={handleItemsPerPageChange}
          >
            <SelectTrigger
              className="w-20"
              aria-label={ALL_PAGES_ADMIN.ITEMS_PER_PAGE_ARIA}
            >
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {ITEMS_PER_PAGE_OPTIONS.map((option) => (
                <SelectItem key={option} value={String(option)}>
                  {option}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      <div className="flex items-center justify-between text-sm text-muted-foreground">
        <p>
          {ALL_PAGES_ADMIN.SHOWING_TO_OF}{" "}
          {paginatedData.length > 0 ? (currentPage - 1) * itemsPerPage + 1 : 0}{" "}
          {ALL_PAGES_ADMIN.TO}{" "}
          {Math.min(currentPage * itemsPerPage, sortedData.length)}{" "}
          {ALL_PAGES_ADMIN.OF} {sortedData.length} {ALL_PAGES_ADMIN.PAGES}
        </p>
        {searchQuery && (
          <Badge variant="secondary" className="font-normal">
            {ALL_PAGES_ADMIN.FILTERED_FROM_TOTAL} {pages.length}{" "}
            {ALL_PAGES_ADMIN.TOTAL}
          </Badge>
        )}
      </div>

      <div className="rounded-md border overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-16 text-center">
                {ALL_PAGES_ADMIN.S_NO}
              </TableHead>
              <TableHead>
                <Button
                  variant="ghost"
                  size="sm"
                  className="-ml-3 h-8 data-[state=open]:bg-accent"
                  onClick={() => handleSort("name")}
                >
                  {ALL_PAGES_ADMIN.PAGE_NAME}
                  {getSortIcon("name")}
                </Button>
              </TableHead>
              <TableHead>
                <Button
                  variant="ghost"
                  size="sm"
                  className="-ml-3 h-8 data-[state=open]:bg-accent"
                  onClick={() => handleSort("slug")}
                >
                  {ALL_PAGES_ADMIN.ROUTE}
                  {getSortIcon("slug")}
                </Button>
              </TableHead>
              <TableHead>
                <Button
                  variant="ghost"
                  size="sm"
                  className="-ml-3 h-8 data-[state=open]:bg-accent"
                  onClick={() => handleSort("status")}
                >
                  {ALL_PAGES_ADMIN.STATUS}
                  {getSortIcon("status")}
                </Button>
              </TableHead>
              <TableHead className="text-center">
                {ALL_PAGES_ADMIN.SHOW_IN_HEADER_LABEL}
              </TableHead>
              <TableHead className="text-center">
                {ALL_PAGES_ADMIN.SHOW_IN_FOOTER_LABEL}
              </TableHead>
              <TableHead className="text-right w-40">
                {ALL_PAGES_ADMIN.ACTIONS}
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {paginatedData.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="h-24 text-center">
                  <p className="text-muted-foreground">
                    {searchQuery
                      ? `${ALL_PAGES_ADMIN.NO_PAGES_MATCHING}${searchQuery}"`
                      : ALL_PAGES_ADMIN.NO_PAGES_FOUND}
                  </p>
                </TableCell>
              </TableRow>
            ) : (
              paginatedData.map((page, index) => (
                <TableRow key={page.id}>
                  <TableCell className="text-center font-medium text-muted-foreground">
                    {(currentPage - 1) * itemsPerPage + index + 1}
                  </TableCell>
                  <TableCell className="font-medium max-w-xs">
                    <div className="truncate" title={page.name}>
                      {page.name}
                    </div>
                  </TableCell>
                  <TableCell>
                    <code className="text-xs bg-muted px-2 py-1 rounded">
                      {page.slug}
                    </code>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline" className="font-normal">
                      {String(page.status).toLowerCase() === "active"
                        ? ALL_PAGES_ADMIN.ACTIVE
                        : ALL_PAGES_ADMIN.INACTIVE}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-center">
                    {page.show_in_header === 1 ? (
                      <span
                        className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-green-100 text-green-700"
                        aria-label={`${ALL_PAGES_ADMIN.SHOW_IN_HEADER_LABEL}: yes`}
                      >
                        <Check className="h-4 w-4 shrink-0 stroke-[2.5]" />
                      </span>
                    ) : (
                      <span
                        className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-red-100 text-red-600"
                        aria-label={`${ALL_PAGES_ADMIN.SHOW_IN_HEADER_LABEL}: no`}
                      >
                        <X className="h-4 w-4 shrink-0 stroke-[2.5]" />
                      </span>
                    )}
                  </TableCell>
                  <TableCell className="text-center">
                    {page.show_in_footer === 1 ? (
                      <span
                        className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-green-100 text-green-700"
                        aria-label={`${ALL_PAGES_ADMIN.SHOW_IN_FOOTER_LABEL}: yes`}
                      >
                        <Check className="h-4 w-4 shrink-0 stroke-[2.5]" />
                      </span>
                    ) : (
                      <span
                        className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-red-100 text-red-600"
                        aria-label={`${ALL_PAGES_ADMIN.SHOW_IN_FOOTER_LABEL}: no`}
                      >
                        <X className="h-4 w-4 shrink-0 stroke-[2.5]" />
                      </span>
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2">
                      {page.raw != null ? (
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleEditClick(page)}
                          aria-label={`${ALL_PAGES_ADMIN.EDIT} ${page.name}`}
                          title={ALL_PAGES_ADMIN.EDIT}
                        >
                          <Pencil className="h-4 w-4" aria-hidden="true" />
                        </Button>
                      ) : (
                        <Button
                          variant="outline"
                          size="sm"
                          asChild
                          aria-label={`${ALL_PAGES_ADMIN.EDIT} ${page.name}`}
                          title={ALL_PAGES_ADMIN.EDIT}
                        >
                          <Link href={page.href}>
                            <Pencil className="h-4 w-4" aria-hidden="true" />
                          </Link>
                        </Button>
                      )}
                      <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => onDelete(page)}
                        aria-label={`${ALL_PAGES_ADMIN.DELETE} ${page.name}`}
                        title={ALL_PAGES_ADMIN.DELETE}
                      >
                        <Trash2 className="h-4 w-4" aria-hidden="true" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">
            {ALL_PAGES_ADMIN.PAGE} {currentPage} {ALL_PAGES_ADMIN.OF}{" "}
            {totalPages}
          </p>
          <div className="flex items-center gap-1">
            <Button
              variant="outline"
              size="icon"
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
              aria-label={ALL_PAGES_ADMIN.PREVIOUS_PAGE}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <div className="hidden sm:flex items-center gap-1">
              {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                let pageNum: number;
                if (totalPages <= 5) {
                  pageNum = i + 1;
                } else if (currentPage <= 3) {
                  pageNum = i + 1;
                } else if (currentPage >= totalPages - 2) {
                  pageNum = totalPages - 4 + i;
                } else {
                  pageNum = currentPage - 2 + i;
                }
                return (
                  <Button
                    key={pageNum}
                    variant={currentPage === pageNum ? "default" : "outline"}
                    size="icon"
                    onClick={() => handlePageChange(pageNum)}
                    aria-label={`${ALL_PAGES_ADMIN.GO_TO_PAGE} ${pageNum}`}
                    aria-current={currentPage === pageNum ? "page" : undefined}
                  >
                    {pageNum}
                  </Button>
                );
              })}
            </div>
            <Button
              variant="outline"
              size="icon"
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages}
              aria-label={ALL_PAGES_ADMIN.NEXT_PAGE}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
