"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  FolderTree,
  Plus,
  Pencil,
  Trash2,
  ToggleLeft,
  ToggleRight,
  AlertCircle,
  X,
} from "lucide-react";
import { cn } from "@/lib/utils/cn";
import { adminApi } from "@/lib/api/client";
import { useTranslation } from "@/lib/hooks/use-translation";
import { tToast } from "@/lib/utils/translated-toast";
import type { Category } from "@/types";

/* ───── Types ───── */

interface CategoryFormData {
  nameHi: string;
  nameEn: string;
  descriptionHi: string;
  descriptionEn: string;
  parentId: number | null;
  sortOrder: number;
}

const emptyForm: CategoryFormData = {
  nameHi: "",
  nameEn: "",
  descriptionHi: "",
  descriptionEn: "",
  parentId: null,
  sortOrder: 0,
};

/* ───── Page ───── */

export default function AdminCategories() {
  const queryClient = useQueryClient();
  const { t: cms, language } = useTranslation(["ADMIN_CATEGORIES", "COMMON"]);

  const [showCreateForm, setShowCreateForm] = useState(false);
  const [editCategory, setEditCategory] = useState<Category | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<Category | null>(null);
  const [formData, setFormData] = useState<CategoryFormData>(emptyForm);

  /* ─── Query ─── */

  const { data: categories = [], isLoading, error } = useQuery<Category[]>({
    queryKey: ["admin-categories"],
    queryFn: async () => {
      const res = await adminApi.categories();
      return res.data;
    },
  });

  /* ─── Mutations ─── */

  const createMutation = useMutation({
    mutationFn: (data: CategoryFormData) =>
      adminApi.createCategory({
        ...data,
        parentId: data.parentId || undefined,
      }),
    onSuccess: () => {
      tToast("success", "admin_categories.category_created", "Category created");
      setShowCreateForm(false);
      setFormData(emptyForm);
      queryClient.invalidateQueries({ queryKey: ["admin-categories"] });
    },
    onError: () => tToast("error", "admin_categories.category_create_failed", "Failed to create category"),
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: CategoryFormData }) =>
      adminApi.updateCategory(id, {
        ...data,
        parentId: data.parentId || undefined,
      }),
    onSuccess: () => {
      tToast("success", "admin_categories.category_updated", "Category updated");
      setEditCategory(null);
      setFormData(emptyForm);
      queryClient.invalidateQueries({ queryKey: ["admin-categories"] });
    },
    onError: () => tToast("error", "admin_categories.category_update_failed", "Failed to update category"),
  });

  const toggleMutation = useMutation({
    mutationFn: (id: number) => adminApi.toggleCategory(id),
    onSuccess: () => {
      tToast("success", "admin_categories.status_toggled", "Status toggled");
      queryClient.invalidateQueries({ queryKey: ["admin-categories"] });
    },
    onError: () => tToast("error", "admin_categories.status_toggle_failed", "Failed to toggle status"),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => adminApi.deleteCategory(id),
    onSuccess: () => {
      tToast("success", "admin_categories.category_deleted", "Category deleted");
      setDeleteConfirm(null);
      queryClient.invalidateQueries({ queryKey: ["admin-categories"] });
    },
    onError: () => tToast("error", "admin_categories.category_delete_failed", "Failed to delete category"),
  });

  /* ─── Helpers ─── */

  function displayName(cat: Category) {
    return language === "hi" ? cat.nameHi : cat.nameEn;
  }

  function parentName(parentId?: number) {
    if (!parentId) return "—";
    const parent = categories.find((c) => c.id === parentId);
    return parent ? displayName(parent) : `#${parentId}`;
  }

  function openEditDialog(cat: Category) {
    setEditCategory(cat);
    setFormData({
      nameHi: cat.nameHi,
      nameEn: cat.nameEn,
      // Blank here used to be unavoidable — the API did not return the stored
      // descriptions — and saving then sent that blank straight back, wiping
      // whatever had been written. The form shows what is stored now.
      descriptionHi: cat.descriptionHi ?? "",
      descriptionEn: cat.descriptionEn ?? "",
      parentId: cat.parentId ?? null,
      sortOrder: cat.sortOrder,
    });
  }

  function openCreateForm() {
    setFormData(emptyForm);
    setShowCreateForm(true);
  }

  function handleFormChange(field: keyof CategoryFormData, value: string | number | null) {
    setFormData((prev) => ({ ...prev, [field]: value }));
  }

  /* ─── Form component ─── */

  function renderForm(opts: {
    title: string;
    onSubmit: () => void;
    onCancel: () => void;
    isPending: boolean;
    submitLabel: string;
  }) {
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
        <div className="w-full max-w-lg bg-white rounded-xl shadow-xl p-6">
          <div className="flex items-center justify-between mb-5">
            <h3 className="text-lg font-semibold text-gray-900">{opts.title}</h3>
            <button onClick={opts.onCancel} className="text-gray-400 hover:text-gray-600 transition">
              <X className="h-5 w-5" />
            </button>
          </div>

          <div className="space-y-4">
            {/* Name Hindi */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {cms("ADMIN_CATEGORIES.categories_form.name_hi", "Name (Hindi)")}
              </label>
              <input
                className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                placeholder={cms("ADMIN_CATEGORIES.categories_form.placeholder_name_hi", "Category name (Hindi)")}
                value={formData.nameHi}
                onChange={(e) => handleFormChange("nameHi", e.target.value)}
              />
            </div>

            {/* Name English */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {cms("ADMIN_CATEGORIES.categories_form.name_en", "Name (English)")}
              </label>
              <input
                className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                placeholder={cms("ADMIN_CATEGORIES.categories_form.placeholder_name_en", "Category name")}
                value={formData.nameEn}
                onChange={(e) => handleFormChange("nameEn", e.target.value)}
              />
            </div>

            {/* Description Hindi */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {cms("ADMIN_CATEGORIES.categories_form.description_hi", "Description (Hindi)")}
              </label>
              <textarea
                rows={2}
                className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                placeholder={cms("ADMIN_CATEGORIES.categories_form.placeholder_desc_hi", "Category description (Hindi)")}
                value={formData.descriptionHi}
                onChange={(e) => handleFormChange("descriptionHi", e.target.value)}
              />
            </div>

            {/* Description English */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {cms("ADMIN_CATEGORIES.categories_form.description_en", "Description (English)")}
              </label>
              <textarea
                rows={2}
                className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                placeholder={cms("ADMIN_CATEGORIES.categories_form.placeholder_desc_en", "Category description")}
                value={formData.descriptionEn}
                onChange={(e) => handleFormChange("descriptionEn", e.target.value)}
              />
            </div>

            {/* Parent Category */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {cms("ADMIN_CATEGORIES.categories_form.parent_category", "Parent Category")}
              </label>
              <select
                className="w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                value={formData.parentId ?? ""}
                onChange={(e) =>
                  handleFormChange("parentId", e.target.value ? Number(e.target.value) : null)
                }
              >
                <option value="">{cms("COMMON.labels.none", "None")}</option>
                {categories
                  .filter((c) => c.id !== editCategory?.id)
                  .map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.nameHi} / {c.nameEn}
                    </option>
                  ))}
              </select>
            </div>

            {/* Sort Order */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {cms("ADMIN_CATEGORIES.categories_form.sort_order", "Sort Order")}
              </label>
              <input
                type="number"
                className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                value={formData.sortOrder}
                onChange={(e) => handleFormChange("sortOrder", Number(e.target.value))}
              />
            </div>
          </div>

          <div className="flex justify-end gap-2 mt-6">
            <button
              onClick={opts.onCancel}
              className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
            >
              {cms("COMMON.buttons.cancel", "Cancel")}
            </button>
            <button
              onClick={opts.onSubmit}
              disabled={!formData.nameHi || !formData.nameEn || opts.isPending}
              className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow hover:bg-indigo-700 disabled:opacity-50 transition"
            >
              {opts.isPending ? "..." : opts.submitLabel}
            </button>
          </div>
        </div>
      </div>
    );
  }

  /* ───── Render ───── */

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">
            {cms("ADMIN_CATEGORIES.categories_header.title", "Category Management")}
          </h1>
          <p className="text-gray-500 text-sm mt-1">
            {cms("ADMIN_CATEGORIES.categories_header.subtitle", "Create, edit & manage categories")}
          </p>
        </div>

        <button
          onClick={openCreateForm}
          className="inline-flex items-center gap-2 rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow hover:bg-indigo-700 transition"
        >
          <Plus className="h-4 w-4" />
          {cms("ADMIN_CATEGORIES.categories_actions.create", "New Category")}
        </button>
      </div>

      {/* Loading / Error */}
      {isLoading && (
        <div className="flex items-center justify-center py-20">
          <p className="text-gray-500 text-lg">{cms("COMMON.status.loading", "Loading...")}</p>
        </div>
      )}

      {error && !isLoading && (
        <div className="flex items-center justify-center py-20">
          <div className="text-center">
            <AlertCircle className="mx-auto h-10 w-10 text-red-400 mb-2" />
            <p className="text-red-600">{cms("COMMON.status.error_loading", "Error loading data")}</p>
          </div>
        </div>
      )}

      {/* Categories table */}
      {!isLoading && !error && (
        <div className="rounded-lg border border-gray-200 bg-white shadow-sm overflow-hidden">
          {categories.length === 0 ? (
            <div className="px-5 py-16 text-center text-gray-500">
              <FolderTree className="mx-auto h-10 w-10 text-gray-300 mb-3" />
              <p>{cms("ADMIN_CATEGORIES.categories_table.empty", "No categories found")}</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 text-left">
                  <tr>
                    <th className="px-5 py-3 font-medium text-gray-500">
                      {cms("ADMIN_CATEGORIES.categories_table.name", "Name")}
                    </th>
                    <th className="px-5 py-3 font-medium text-gray-500">
                      {cms("ADMIN_CATEGORIES.categories_table.slug", "Slug")}
                    </th>
                    <th className="px-5 py-3 font-medium text-gray-500">
                      {cms("ADMIN_CATEGORIES.categories_table.parent", "Parent")}
                    </th>
                    <th className="px-5 py-3 font-medium text-gray-500">
                      {cms("ADMIN_CATEGORIES.categories_table.order", "Order")}
                    </th>
                    <th className="px-5 py-3 font-medium text-gray-500">
                      {cms("ADMIN_CATEGORIES.categories_table.status", "Status")}
                    </th>
                    <th className="px-5 py-3 font-medium text-gray-500">
                      {cms("ADMIN_CATEGORIES.categories_table.actions", "Actions")}
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {categories.map((cat) => (
                    <tr key={cat.id} className="hover:bg-gray-50 transition">
                      {/* Name (bilingual) */}
                      <td className="px-5 py-4">
                        <div className="font-medium text-gray-900">
                          {cat.nameHi}
                        </div>
                        <div className="text-gray-500 text-xs mt-0.5">
                          {cat.nameEn}
                        </div>
                      </td>

                      {/* Slug */}
                      <td className="px-5 py-4 text-gray-600 font-mono text-xs">
                        {cat.slug}
                      </td>

                      {/* Parent */}
                      <td className="px-5 py-4 text-gray-600 text-xs">
                        {parentName(cat.parentId)}
                      </td>

                      {/* Sort Order */}
                      <td className="px-5 py-4 text-gray-600 text-center">
                        {cat.sortOrder}
                      </td>

                      {/* Status */}
                      <td className="px-5 py-4">
                        <span
                          className={cn(
                            "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",
                            cat.active
                              ? "bg-green-100 text-green-700"
                              : "bg-red-100 text-red-700"
                          )}
                        >
                          {cat.active
                            ? cms("COMMON.status.active", "Active")
                            : cms("COMMON.status.inactive", "Inactive")}
                        </span>
                      </td>

                      {/* Actions */}
                      <td className="px-5 py-4">
                        <div className="flex flex-wrap gap-1.5">
                          {/* Toggle */}
                          <button
                            onClick={() => toggleMutation.mutate(cat.id)}
                            disabled={toggleMutation.isPending}
                            className={cn(
                              "inline-flex items-center gap-1 rounded-md px-2.5 py-1.5 text-xs font-medium transition disabled:opacity-50",
                              cat.active
                                ? "bg-amber-50 text-amber-700 hover:bg-amber-100"
                                : "bg-green-50 text-green-700 hover:bg-green-100"
                            )}
                            title={cat.active ? cms("ADMIN_CATEGORIES.categories_actions.deactivate", "Deactivate") : cms("ADMIN_CATEGORIES.categories_actions.activate", "Activate")}
                          >
                            {cat.active ? (
                              <ToggleRight className="h-3.5 w-3.5" />
                            ) : (
                              <ToggleLeft className="h-3.5 w-3.5" />
                            )}
                            {cat.active ? cms("ADMIN_CATEGORIES.categories_actions.deactivate", "Deactivate") : cms("ADMIN_CATEGORIES.categories_actions.activate", "Activate")}
                          </button>

                          {/* Edit */}
                          <button
                            onClick={() => openEditDialog(cat)}
                            className="inline-flex items-center gap-1 rounded-md bg-indigo-50 px-2.5 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100 transition"
                          >
                            <Pencil className="h-3.5 w-3.5" />
                            {cms("COMMON.buttons.edit", "Edit")}
                          </button>

                          {/* Delete */}
                          <button
                            onClick={() => setDeleteConfirm(cat)}
                            className="inline-flex items-center gap-1 rounded-md bg-red-50 px-2.5 py-1.5 text-xs font-medium text-red-700 hover:bg-red-100 transition"
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                            {cms("COMMON.buttons.delete", "Delete")}
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {/* ─── Create Category Modal ─── */}
      {showCreateForm &&
        renderForm({
          title: cms("ADMIN_CATEGORIES.categories_modal.create_title", "Create Category"),
          onSubmit: () => createMutation.mutate(formData),
          onCancel: () => {
            setShowCreateForm(false);
            setFormData(emptyForm);
          },
          isPending: createMutation.isPending,
          submitLabel: cms("COMMON.buttons.create", "Create"),
        })}

      {/* ─── Edit Category Modal ─── */}
      {editCategory &&
        renderForm({
          title: cms("ADMIN_CATEGORIES.categories_modal.edit_title", "Edit Category"),
          onSubmit: () =>
            updateMutation.mutate({ id: editCategory.id, data: formData }),
          onCancel: () => {
            setEditCategory(null);
            setFormData(emptyForm);
          },
          isPending: updateMutation.isPending,
          submitLabel: cms("COMMON.buttons.update", "Update"),
        })}

      {/* ─── Delete Confirmation Modal ─── */}
      {deleteConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="w-full max-w-sm bg-white rounded-xl shadow-xl p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-2">
              {cms("ADMIN_CATEGORIES.categories_modal.delete_title", "Delete Category")}
            </h3>
            <p className="text-sm text-gray-600 mb-4">
              {cms("ADMIN_CATEGORIES.categories_modal.delete_confirm", "Are you sure you want to delete this category?")}
            </p>
            <div className="rounded-md bg-gray-50 px-3 py-2 mb-5">
              <p className="font-medium text-gray-900">{deleteConfirm.nameHi}</p>
              <p className="text-gray-500 text-sm">{deleteConfirm.nameEn}</p>
            </div>
            <div className="flex justify-end gap-2">
              <button
                onClick={() => setDeleteConfirm(null)}
                className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
              >
                {cms("COMMON.buttons.cancel", "Cancel")}
              </button>
              <button
                onClick={() => deleteMutation.mutate(deleteConfirm.id)}
                disabled={deleteMutation.isPending}
                className="rounded-md bg-red-600 px-4 py-2 text-sm font-semibold text-white shadow hover:bg-red-700 disabled:opacity-50 transition"
              >
                {deleteMutation.isPending ? "..." : cms("COMMON.buttons.delete", "Delete")}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
