import React, { useState } from "react";
import { Switch } from "@headlessui/react";
import {
  useGetCategoryTreeQuery,
  useDeleteCategoryMutation,
} from "../../features/categories/categoryAPI";
import {
  FiEdit,
  FiTrash2,
  FiEye,
  FiPlus,
  FiGrid,
  FiLayers,
  FiTag,
  FiChevronRight,
} from "react-icons/fi";
import { useNavigate } from "react-router-dom";
import Table from "../../components/common/Table";
import Pagination from "../../components/common/Pagination";
import {
  useUpdateCategoryStatusMutation,
  useReorderCategoriesMutation,
} from "../../features/categories/categoryAPI";
import ConfirmModal from "../../components/common/ConfirmModal";

const CategoryList = () => {
  const { data, isLoading } = useGetCategoryTreeQuery();
  const [deleteCategory] = useDeleteCategoryMutation();
  const [updateCategoryStatus] = useUpdateCategoryStatusMutation();
  const [reorderCategories] = useReorderCategoriesMutation();

  const [isReorderMode, setIsReorderMode] = useState(false);
  const [reorderData, setReorderData] = useState([]);
  const navigate = useNavigate();

  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState(null);

  const [currentPage, setCurrentPage] = useState(1);
  const perPage = 20;

  // Flatten tree
  const flatten = (nodes, level = 0) => {
    let list = [];

    [...nodes]
      .sort((a, b) => a.sequence - b.sequence) // 🔥 sort here
      .forEach((node) => {
        list.push({ ...node, level });

        if (node.children?.length) {
          list = list.concat(flatten(node.children, level + 1));
        }
      });

    return list;
  };

  const flatCategories = flatten(data?.data || []);

  const startReorder = () => {
    const topLevel = flatCategories.filter((c) => c.level === 0);
    setReorderData(topLevel);
    setIsReorderMode(true);
  };

  const cancelReorder = () => {
    setReorderData([]);
    setIsReorderMode(false);
  };

  const moveRow = (index, direction) => {
    const updated = [...reorderData];
    const targetIndex = direction === "up" ? index - 1 : index + 1;

    if (targetIndex < 0 || targetIndex >= updated.length) return;

    [updated[index], updated[targetIndex]] = [
      updated[targetIndex],
      updated[index],
    ];

    setReorderData(updated);
  };

  const submitReorder = async () => {
    const orders = reorderData.map((item, index) => ({
      id: item.id,
      sequence: index + 1,
    }));

    try {
      await reorderCategories(orders).unwrap();
      setIsReorderMode(false);
    } catch (err) {
      console.error(err);
    }
  };

  // Pagination logic
  const totalPages = Math.ceil(flatCategories.length / perPage);
  const paginatedData = flatCategories.slice(
    (currentPage - 1) * perPage,
    currentPage * perPage
  );

  // Level label
  const getLevelLabel = (level) => {
    if (level === 0) return "Main Category";
    if (level === 1) return "Sub Category";
    return "Child";
  };

  // Level icon
  const getLevelIcon = (level) => {
    if (level === 0) return <FiGrid className="text-indigo-600" size={18} />;
    if (level === 1) return <FiLayers className="text-blue-600" size={18} />;
    return <FiTag className="text-green-600" size={16} />;
  };

  const handleConfirmDelete = async () => {
    if (!selectedCategory) return;

    try {
      await deleteCategory(selectedCategory.id).unwrap();
      setShowDeleteModal(false);
      setSelectedCategory(null);
    } catch (error) {
      alert(error?.data?.message || "Failed to delete category");
    }
  };

  // Table columns
  const columns = [
    {
      key: "name",
      label: "Category",
      render: (value, row) => (
        <div
          className="flex items-center gap-2"
          style={{ marginLeft: `${row.level * 20}px` }}
        >
          {row.level > 0 && <FiChevronRight className="text-gray-400" />}
          {getLevelIcon(row.level)}
          <span className="font-medium text-gray-800">{row.name}</span>
        </div>
      ),
    },
    {
      key: "type",
      label: "Type",
      render: (_, row) => (
        <span
          className={`px-2 py-1 text-xs rounded-full ${
            row.level === 0
              ? "bg-indigo-100 text-indigo-700"
              : row.level === 1
              ? "bg-blue-100 text-blue-700"
              : "bg-green-100 text-green-700"
          }`}
        >
          {getLevelLabel(row.level)}
        </span>
      ),
    },
    { key: "slug", label: "Slug" },
    // { key: "status", label: "Status" },
    {
      key: "status",
      label: "Status",
      render: (_, row) => (
        <Switch
          checked={row.isActive}
          onChange={async (val) => {
            await updateCategoryStatus({ id: row.id, isActive: val });
          }}
          className={`${
            row.isActive ? "bg-green-500" : "bg-gray-300"
          } relative inline-flex h-6 w-11 items-center rounded-full`}
        >
          <span
            className={`${
              row.isActive ? "translate-x-6" : "translate-x-1"
            } inline-block h-4 w-4 transform rounded-full bg-white transition`}
          />
        </Switch>
      ),
    },
  ];

  // Row action buttons
  const rowActions = (row) => (
    <>
      <button
        onClick={() => navigate(`/categories/${row.id}`)}
        className="text-blue-600 hover:text-blue-800"
      >
        <FiEye size={18} />
      </button>

      <button
        onClick={() => navigate(`/categories/edit/${row.id}`)}
        className="text-green-600 hover:text-green-800"
      >
        <FiEdit size={18} />
      </button>

      <button
        onClick={() => {
          setSelectedCategory(row);
          setShowDeleteModal(true);
        }}
        className="text-red-600 hover:text-red-800"
      >
        <FiTrash2 size={18} />
      </button>

      {/* <button
        onClick={() => navigate("/categories/reorder")}
        className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition"
      >
        <FiLayers /> Reorder Categories
      </button> */}
    </>
  );

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-semibold">Categories</h2>

        <div className="flex gap-2">
          {!isReorderMode && (
            <>
              <button
                onClick={startReorder}
                className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
              >
                <FiLayers /> Reorder Categories
              </button>

              <button
                onClick={() => navigate("/categories/add")}
                className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                <FiPlus /> Add Category
              </button>
            </>
          )}

          {isReorderMode && (
            <>
              <button
                onClick={submitReorder}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700"
              >
                Update Order
              </button>

              <button
                onClick={cancelReorder}
                className="px-4 py-2 bg-gray-300 rounded-lg hover:bg-gray-400"
              >
                Cancel
              </button>
            </>
          )}
        </div>
      </div>

      {/* Table */}
      {/* <Table
        columns={columns}
        data={isLoading ? [] : paginatedData}
        actions={rowActions}
      /> */}

      <Table
        columns={[
          ...columns,
          ...(isReorderMode
            ? [
                {
                  key: "reorder",
                  label: "Reorder",
                  render: (_, __, index) => (
                    <div className="flex gap-1">
                      <button
                        onClick={() => moveRow(index, "up")}
                        className="px-2 py-1 bg-gray-200 rounded"
                      >
                        ↑
                      </button>
                      <button
                        onClick={() => moveRow(index, "down")}
                        className="px-2 py-1 bg-gray-200 rounded"
                      >
                        ↓
                      </button>
                    </div>
                  ),
                },
              ]
            : []),
        ]}
        data={isLoading ? [] : isReorderMode ? reorderData : paginatedData}
        actions={isReorderMode ? null : rowActions}
      />

      {/* Pagination */}
      <Pagination
        currentPage={currentPage}
        totalPages={totalPages}
        onPageChange={(pg) => setCurrentPage(pg)}
      />

      <ConfirmModal
        isOpen={showDeleteModal}
        title="Delete Category"
        message={`Are you sure you want to delete "${selectedCategory?.name}"?`}
        onCancel={() => {
          setShowDeleteModal(false);
          setSelectedCategory(null);
        }}
        onConfirm={handleConfirmDelete}
      />
    </div>
  );
};

export default CategoryList;
