import { NavLink, useNavigate } from "react-router-dom";
import { CirclePlus } from "lucide-react";
import { NewsCategoryColumnDefn } from "./NewsCategoryColumn";
import { useTranslation } from "react-i18next";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import { useMemo, useState } from "react";
import Loader from "@/record-management/components/Loader/loader";
import { Button } from "@/shared/common/ui/button";
import { toast } from "sonner";
import { useNewsCategory } from "../hooks/useNewsCategory";
import { ContactUsParams } from "../hooks/useContactUs";

export const NewsCategory = () => {
  const [pageIndex, setPageIndex] = useState(0);
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
  const navigate = useNavigate();
  const pageSize = 10;
  const { t } = useTranslation();
  const baseParams = useMemo(() => {
    const params: Record<string, any> = {
      skip: pageIndex * pageSize,
      take: pageSize,
      orderBy: "createdAt:DESC",
    };

    return params;
  }, [pageIndex]);

  const { items, refetch, deleteItem, error, isLoading, count } =
    useNewsCategory(baseParams);
  const handlePageChange = (newPage: number) => {
    setPageIndex(newPage);
  };

  const handleDeleteClick = async (id: string) => {
    setDeleteConfirmId(id);
  };

  const handleDeleteConfirm = async () => {
    if (!deleteConfirmId) return;

    try {
      await deleteItem(deleteConfirmId);
      toast.success("News category deleted successfully");
      refetch();
    } catch (error) {
      toast.error("Failed to delete news category");
      console.error("Delete error:", error);
    } finally {
      setDeleteConfirmId(null);
    }
  };

  const handleDeleteCancel = () => {
    setDeleteConfirmId(null);
  };

  return (
    <div className="flex flex-col h-full w-full p-6 bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700">
      {/* Header Section */}
      <div className="flex items-center justify-between mb-4 border-b pb-3 border-gray-200 dark:border-gray-700">
        <h1 className="text-xl font-semibold text-gray-800 dark:text-gray-200">
          {t("newsCategory")}
        </h1>
        {
          <NavLink to="/user-management/web-Management/Category/AddCategory">
            <Button
              variant="addRecordBtn"
              className="flex items-center gap-1 bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-lg transition-all"
            >
              <CirclePlus className="w-4 h-4" />
              <span>{t("addNewsCategory")}</span>
            </Button>
          </NavLink>
        }
      </div>

      {/* Content Section */}
      <div className="flex-1 overflow-auto">
        {isLoading && (
          <div className="flex justify-center items-center h-48">
            <Loader />
          </div>
        )}

        {error && (
          <p className="text-center text-red-500 text-sm mt-4">
            {t("userRecord.Error loading records.")}
          </p>
        )}

        {!isLoading && !error && (
          <div className="mt-2">
            <AdvancedTable
              columns={NewsCategoryColumnDefn({
                navigate,
                onDelete: handleDeleteClick,
              })}
              data={items || []}
              tableName="NewsCategorys"
              toolBarPosition="right"
              extraToolbar={<div className="flex gap-2"></div>}
              itemCount={count || 2}
              pageIndex={pageIndex}
              onPageChange={handlePageChange}
              nextFunction={() => handlePageChange(pageIndex + 1)}
              prevFunction={() => handlePageChange(Math.max(pageIndex - 1, 0))}
              refresh={refetch}
            />
          </div>
        )}
      </div>
      {/* Delete Confirmation Dialog */}
      {deleteConfirmId && (
        <div className="fixed inset-0 bg-black/50 dark:bg-black/70 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-md w-full mx-4">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">
              Confirm Delete
            </h3>
            <p className="text-gray-600 dark:text-gray-400 mb-6">
              Are you sure you want to delete this news category? This action
              cannot be undone.
            </p>
            <div className="flex justify-end gap-3">
              <Button
                variant="outline"
                onClick={handleDeleteCancel}
                className="px-4 py-2 dark:border-gray-600 dark:text-gray-200"
              >
                Cancel
              </Button>
              <Button
                onClick={handleDeleteConfirm}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white"
              >
                Delete
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
