"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { toast } from "react-toastify";
import {
  CheckCircle,
  Eye,
  FolderTree,
  Image as ImageIcon,
  Loader2,
  Pencil,
  Plus,
  Trash2,
  Upload,
  XCircle,
} from "lucide-react";
import { AdminBreadcrumb } from "@/components/admin/admin-breadcrumb";
import { AdminTablePagination } from "@/components/admin/admin-table-pagination";
import { AdminTableToolbar } from "@/components/admin/admin-table-toolbar";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { apiRequest, apiUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";
import { useLanguage } from "@/lib/i18n";

type MasterStatus = "active" | "inactive";

type ApiResponse<T> = {
  statusCode?: number;
  success?: boolean;
  data?: T;
  message?: string;
  message_hi?: string;
};

type MasterItem = {
  id?: number | string;
  uuid?: string;
  title?: string;
  title_hi?: string | null;
  name?: string;
  description?: string | null;
  description_hi?: string | null;
  image?: string | null;
  status?: string | boolean | number;
  created_by?:
    | {
        name?: string;
        email?: string;
      }
    | string
    | null;
  updated_by?:
    | {
        name?: string;
        email?: string;
      }
    | string
    | null;
  created_at?: string;
  updated_at?: string;
};

type ValidationErrors = Record<string, string[]>;

type MasterForm = {
  title: string;
  title_hi: string;
  description: string;
  description_hi: string;
  image: File | null;
  imagePreview: string;
  removeImage: boolean;
  status: MasterStatus;
};

type PaginatedMasterItems = {
  current_page: number;
  data: MasterItem[];
  from: number | null;
  last_page?: number;
  per_page: number;
  to: number | null;
  total: number;
};

type MasterDirectoryListPageProps = {
  title: string;
  singularTitle: string;
  endpoint: string;
  dataKey: string;
  enableImageUpload?: boolean;
};

const emptyPagination: PaginatedMasterItems = {
  current_page: 1,
  data: [],
  from: null,
  last_page: 1,
  per_page: 10,
  to: null,
  total: 0,
};

const initialForm: MasterForm = {
  title: "",
  title_hi: "",
  description: "",
  description_hi: "",
  image: null,
  imagePreview: "",
  removeImage: false,
  status: "active",
};

const formControlClass = "h-11 rounded-2xl border-[var(--theme-border-soft)]";
const formSelectClass =
  "h-11 w-full rounded-2xl border border-[var(--theme-border-soft)] px-3 text-sm font-medium outline-none transition focus:border-[var(--theme-secondary)] focus:ring-2 focus:ring-[var(--theme-secondary)]/20";
const apiOrigin = apiUrl("").replace(/\/api\/?$/, "");

function getAdminToken() {
  const token = localStorage.getItem("auth_token");

  if (!token) {
    throw new Error("Admin token missing. Please login again.");
  }

  return token;
}

function getItemTitle(item: MasterItem) {
  return item.title || item.name || "Untitled";
}

function getActorLabel(actor: MasterItem["created_by"]) {
  if (!actor) return "-";
  if (typeof actor === "string") return actor;
  return actor.name || actor.email || "-";
}

function getStatus(item: MasterItem): MasterStatus {
  if (typeof item.status === "boolean") {
    return item.status ? "active" : "inactive";
  }

  if (typeof item.status === "number") {
    return item.status === 1 ? "active" : "inactive";
  }

  return String(item.status || "active").toLowerCase() === "inactive"
    ? "inactive"
    : "active";
}

function imageUrl(path?: string | null) {
  if (!path) return "";
  if (
    path.startsWith("blob:") ||
    path.startsWith("http") ||
    path.startsWith("/")
  ) {
    return path;
  }

  return `${apiOrigin}/storage/${path.replace(/^\/?storage\//, "")}`;
}

function getPaginationFromResponse(
  data: unknown,
  dataKey: string,
): PaginatedMasterItems {
  if (!data || typeof data !== "object") return emptyPagination;

  const record = data as Record<string, unknown>;
  const value = record[dataKey];

  if (Array.isArray(value)) {
    return {
      ...emptyPagination,
      data: value as MasterItem[],
      from: value.length > 0 ? 1 : null,
      to: value.length || null,
      total: value.length,
    };
  }

  if (value && typeof value === "object" && "data" in value) {
    return value as PaginatedMasterItems;
  }

  return emptyPagination;
}

function getPageCount(pagination: PaginatedMasterItems) {
  return (
    pagination.last_page ||
    Math.max(1, Math.ceil(pagination.total / pagination.per_page))
  );
}

function StatusBadge({
  status,
  label,
}: {
  status: MasterStatus;
  label: string;
}) {
  return (
    <Badge
      className={`rounded-full px-3 py-1 font-semibold capitalize shadow-none ${
        status === "active"
          ? "bg-green-50 text-green-700"
          : "bg-red-50 text-red-700"
      }`}
    >
      {label}
    </Badge>
  );
}

function RequiredMark() {
  return <span className="text-[var(--theme-accent)]">*</span>;
}

function getFieldError(
  errors: ValidationErrors,
  field: keyof MasterForm | "image",
) {
  return errors[field]?.[0] || "";
}

function requiredError(label: string) {
  return [`${label} is required.`];
}

function validateForm(form: MasterForm) {
  const errors: ValidationErrors = {};

  if (!form.title.trim()) errors.title = requiredError("Title");
  if (!form.title_hi.trim()) errors.title_hi = requiredError("Title Hindi");
  if (!form.description.trim())
    errors.description = requiredError("Description");
  if (!form.description_hi.trim()) {
    errors.description_hi = requiredError("Description Hindi");
  }
  if (!form.status) errors.status = requiredError("Status");

  return errors;
}

function buildPayload(
  form: MasterForm,
  useFormData: true,
  methodOverride?: "PUT",
): FormData;
function buildPayload(
  form: MasterForm,
  useFormData?: false,
): {
  title: string;
  title_hi: string;
  description: string;
  description_hi: string;
  status: MasterStatus;
};
function buildPayload(
  form: MasterForm,
  useFormData = false,
  methodOverride?: "PUT",
) {
  if (!useFormData) {
    return {
      title: form.title.trim(),
      title_hi: form.title_hi.trim(),
      description: form.description.trim(),
      description_hi: form.description_hi.trim(),
      status: form.status,
    };
  }

  const payload = new FormData();
  if (methodOverride) {
    payload.append("_method", methodOverride);
  }
  payload.append("title", form.title.trim());
  payload.append("title_hi", form.title_hi.trim());
  payload.append("description", form.description.trim());
  payload.append("description_hi", form.description_hi.trim());
  payload.append("status", form.status);

  if (form.image) {
    payload.append("image", form.image);
  }

  if (form.removeImage) {
    payload.append("remove_image", "1");
  }

  return payload;
}

function itemToForm(item: MasterItem): MasterForm {
  return {
    title: getItemTitle(item),
    title_hi: item.title_hi || "",
    description: item.description || "",
    description_hi: item.description_hi || "",
    image: null,
    imagePreview: imageUrl(item.image),
    removeImage: false,
    status: getStatus(item),
  };
}

function getItemFromResponse(data: unknown, dataKey: string) {
  if (!data || typeof data !== "object") return null;

  const record = data as Record<string, unknown>;
  const singularKey = dataKey.endsWith("s") ? dataKey.slice(0, -1) : dataKey;

  return (
    (record[singularKey] as MasterItem | undefined) ||
    (record.item as MasterItem | undefined) ||
    (data as MasterItem)
  );
}

function DetailItem({
  label,
  value,
}: {
  label: string;
  value?: React.ReactNode;
}) {
  return (
    <div className="grid gap-3 border-b border-[var(--theme-border-soft)] py-4 md:grid-cols-[160px_1fr]">
      <p className="text-sm font-black">{label}</p>
      <div className="whitespace-pre-wrap text-sm leading-7 text-[#1f1711]">
        {value || "-"}
      </div>
    </div>
  );
}

function MasterImageUpload({
  preview,
  error,
  onChange,
  onRemove,
}: {
  preview: string;
  error?: string;
  onChange: (file: File) => void;
  onRemove: () => void;
}) {
  return (
    <div className="space-y-2 md:col-span-2">
      <Label>Image</Label>
      <div className="flex flex-col gap-4 rounded-2xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] p-4 sm:flex-row sm:items-center">
        <div className="flex h-20 w-24 shrink-0 items-center justify-center overflow-hidden rounded-2xl bg-white text-slate-600">
          {preview ? (
            <img
              src={preview}
              alt="Preview"
              className="h-full w-full object-cover"
            />
          ) : (
            <ImageIcon className="h-8 w-8" />
          )}
        </div>
        <div className="flex-1">
          <p className="text-sm font-semibold text-[#1f1711]">Upload image</p>
          <p className="mt-1 text-xs text-muted-foreground">
            JPG, PNG, GIF or WEBP. Max size 5MB.
          </p>
          {error && (
            <p className="mt-1 text-xs font-medium text-red-600">{error}</p>
          )}
        </div>
        <div className="flex gap-2">
          <Button
            type="button"
            variant="outline"
            className="h-10 rounded-2xl border-[var(--theme-border-soft)] bg-white px-4"
            asChild
          >
            <label>
              <Upload className="h-4 w-4" />
              Upload
              <input
                type="file"
                accept="image/jpeg,image/png,image/gif,image/webp"
                className="sr-only"
                onChange={(event) => {
                  const file = event.target.files?.[0];
                  if (file) onChange(file);
                  event.target.value = "";
                }}
              />
            </label>
          </Button>
          {preview && (
            <Button
              type="button"
              variant="outline"
              className="h-10 rounded-2xl border-[var(--theme-border-soft)] bg-white px-4"
              onClick={onRemove}
            >
              <XCircle className="h-4 w-4" />
              Remove
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}

export function MasterDirectoryListPage({
  title,
  singularTitle,
  endpoint,
  dataKey,
  enableImageUpload = false,
}: MasterDirectoryListPageProps) {
  const { t } = useLanguage();
  const [items, setItems] = useState<MasterItem[]>([]);
  const [pagination, setPagination] =
    useState<PaginatedMasterItems>(emptyPagination);
  const [searchTerm, setSearchTerm] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [statusUpdatingUuid, setStatusUpdatingUuid] = useState<string | null>(
    null,
  );
  const [isFormDialogOpen, setIsFormDialogOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<MasterItem | null>(null);
  const [form, setForm] = useState<MasterForm>(initialForm);
  const [formErrors, setFormErrors] = useState<ValidationErrors>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [viewItem, setViewItem] = useState<MasterItem | null>(null);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);
  const [isFetchingDetail, setIsFetchingDetail] = useState(false);
  const [deleteItem, setDeleteItem] = useState<MasterItem | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  const fetchItems = useCallback(
    async (page = 1) => {
      setIsLoading(true);
      setError("");

      try {
        const token = getAdminToken();
        const response = await apiRequest(apiUrl(`${endpoint}?page=${page}`), {
          method: "GET",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
        });
        const result = (await response.json()) as ApiResponse<unknown>;

        if (!response.ok || result.success === false) {
          throw new Error(
            getLocalizedApiMessage(result, `Failed to load ${title}.`),
          );
        }

        const nextPagination = getPaginationFromResponse(result.data, dataKey);

        setPagination(nextPagination);
        setItems(nextPagination.data || []);
      } catch (fetchError) {
        const message =
          fetchError instanceof Error
            ? fetchError.message
            : `Failed to load ${title}.`;

        setError(message);
        setItems([]);
        setPagination(emptyPagination);
        toast.error(message);
      } finally {
        setIsLoading(false);
      }
    },
    [dataKey, endpoint, title],
  );

  useEffect(() => {
    fetchItems();
  }, [fetchItems]);

  const filteredItems = useMemo(() => {
    const query = searchTerm.trim().toLowerCase();
    if (!query) return items;

    return items.filter(
      (item) =>
        getItemTitle(item).toLowerCase().includes(query) ||
        String(item.title_hi || "")
          .toLowerCase()
          .includes(query) ||
        String(item.description || "")
          .toLowerCase()
          .includes(query),
    );
  }, [items, searchTerm]);

  const activeCount = items.filter(
    (item) => getStatus(item) === "active",
  ).length;
  const inactiveCount = items.filter(
    (item) => getStatus(item) === "inactive",
  ).length;
  const localizedTitle =
    title === "Document Types"
      ? t("admin.documentTypes")
      : (title === "Languages" || title === "Spoken Languages")
        ? t("admin.languages")
        : (title === "Locations" || title === "Service Locations")
          ? t("admin.locations")
          : title === "Expertises"
            ? t("admin.expertises")
            : title;
  const localizedSingularTitle =
    singularTitle === "Document Type"
      ? t("admin.documentTypes")
      : singularTitle === "Language"
        ? t("admin.languages")
        : (singularTitle === "Location" || singularTitle === "Service Location")
          ? t("admin.serviceLocation")
          : singularTitle === "Expertise"
            ? t("admin.expertises")
            : singularTitle;
  const statusLabel = (status: MasterStatus) =>
    status === "active" ? t("admin.active") : t("admin.inactive");

  const changeStatus = async (item: MasterItem) => {
    if (!item.uuid) {
      toast.error(`${singularTitle} uuid is missing.`);
      return;
    }

    const nextStatus = getStatus(item) === "active" ? "inactive" : "active";
    setStatusUpdatingUuid(item.uuid);

    try {
      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl(`${endpoint}/${item.uuid}/change-status`),
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ status: nextStatus }),
        },
      );
      const result = (await response.json()) as ApiResponse<unknown>;

      if (!response.ok || result.success === false) {
        throw new Error(
          getLocalizedApiMessage(result, "Failed to change status."),
        );
      }

      toast.success(
        getLocalizedApiMessage(result, "Status updated successfully."),
      );
      fetchItems(pagination.current_page);
    } catch (statusError) {
      const message =
        statusError instanceof Error
          ? statusError.message
          : "Failed to change status.";
      toast.error(message);
    } finally {
      setStatusUpdatingUuid(null);
    }
  };

  const updateFormField = (
    field: keyof MasterForm,
    value: MasterForm[keyof MasterForm],
  ) => {
    setForm((currentForm) => ({ ...currentForm, [field]: value }));
    setFormErrors((currentErrors) => {
      if (!currentErrors[field]) return currentErrors;
      const nextErrors = { ...currentErrors };
      delete nextErrors[field];
      return nextErrors;
    });
  };

  const updateImageField = (file: File) => {
    setForm((currentForm) => ({
      ...currentForm,
      image: file,
      imagePreview: URL.createObjectURL(file),
      removeImage: false,
    }));
    setFormErrors((currentErrors) => {
      if (!currentErrors.image) return currentErrors;
      const nextErrors = { ...currentErrors };
      delete nextErrors.image;
      return nextErrors;
    });
  };

  const removeImageField = () => {
    setForm((currentForm) => ({
      ...currentForm,
      image: null,
      imagePreview: "",
      removeImage: true,
    }));
    setFormErrors((currentErrors) => {
      if (!currentErrors.image) return currentErrors;
      const nextErrors = { ...currentErrors };
      delete nextErrors.image;
      return nextErrors;
    });
  };

  const openAddDialog = () => {
    setEditingItem(null);
    setForm(initialForm);
    setFormErrors({});
    setIsFormDialogOpen(true);
  };

  const openEditDialog = (item: MasterItem) => {
    if (!item.uuid) {
      toast.error(`${singularTitle} uuid is missing.`);
      return;
    }

    setEditingItem(item);
    setForm(itemToForm(item));
    setFormErrors({});
    setIsFormDialogOpen(true);
  };

  const handleFormDialogOpenChange = (open: boolean) => {
    setIsFormDialogOpen(open);

    if (!open) {
      setEditingItem(null);
      setForm(initialForm);
      setFormErrors({});
    }
  };

  const openViewDialog = async (item: MasterItem) => {
    if (!item.uuid) {
      toast.error(`${singularTitle} uuid is missing.`);
      return;
    }

    setViewItem(item);
    setIsViewDialogOpen(true);
    setIsFetchingDetail(true);

    try {
      const token = getAdminToken();
      const response = await apiRequest(apiUrl(`${endpoint}/${item.uuid}`), {
        method: "GET",
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      });
      const result = (await response.json()) as ApiResponse<unknown>;

      if (!response.ok || result.success === false) {
        throw new Error(
          getLocalizedApiMessage(result, `Failed to load ${singularTitle}.`),
        );
      }

      setViewItem(getItemFromResponse(result.data, dataKey) || item);
    } catch (detailError) {
      const message =
        detailError instanceof Error
          ? detailError.message
          : `Failed to load ${singularTitle}.`;
      toast.error(message);
      setIsViewDialogOpen(false);
      setViewItem(null);
    } finally {
      setIsFetchingDetail(false);
    }
  };

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setFormErrors({});

    const validationErrors = validateForm(form);

    if (Object.keys(validationErrors).length > 0) {
      setFormErrors(validationErrors);
      toast.error("Please fill all required fields.");
      return;
    }

    setIsSubmitting(true);

    try {
      const token = getAdminToken();
      const isEditing = Boolean(editingItem?.uuid);
      const response = await apiRequest(
        apiUrl(isEditing ? `${endpoint}/${editingItem?.uuid}` : endpoint),
        {
          method: enableImageUpload ? "POST" : isEditing ? "PUT" : "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            ...(enableImageUpload
              ? {}
              : { "Content-Type": "application/json" }),
          },
          body: enableImageUpload
            ? buildPayload(form, true, isEditing ? "PUT" : undefined)
            : JSON.stringify(buildPayload(form)),
        },
      );
      const result = (await response.json()) as ApiResponse<ValidationErrors>;

      if (response.status === 422 && result.data) {
        setFormErrors(result.data);
        throw new Error(getLocalizedApiMessage(result, "Validation failed."));
      }

      if (!response.ok || result.success === false) {
        throw new Error(
          getLocalizedApiMessage(
            result,
            `Failed to ${isEditing ? "update" : "create"} ${singularTitle}.`,
          ),
        );
      }

      toast.success(
        getLocalizedApiMessage(
          result,
          `${singularTitle} ${isEditing ? "updated" : "created"} successfully.`,
        ),
      );
      setIsFormDialogOpen(false);
      setEditingItem(null);
      setForm(initialForm);
      fetchItems(pagination.current_page);
    } catch (submitError) {
      const message =
        submitError instanceof Error
          ? submitError.message
          : `Failed to ${editingItem?.uuid ? "update" : "create"} ${singularTitle}.`;
      toast.error(message);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteItem?.uuid) {
      toast.error(`${singularTitle} uuid is missing.`);
      return;
    }

    setIsDeleting(true);

    try {
      const token = getAdminToken();
      const response = await apiRequest(apiUrl(`${endpoint}/${deleteItem.uuid}`), {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      });
      const result = (await response.json()) as ApiResponse<unknown>;

      if (!response.ok || result.success === false) {
        throw new Error(
          getLocalizedApiMessage(result, `Failed to delete ${singularTitle}.`),
        );
      }

      toast.success(
        getLocalizedApiMessage(
          result,
          `${singularTitle} deleted successfully.`,
        ),
      );
      setDeleteItem(null);
      fetchItems(pagination.current_page);
    } catch (deleteError) {
      const message =
        deleteError instanceof Error
          ? deleteError.message
          : `Failed to delete ${singularTitle}.`;
      toast.error(message);
    } finally {
      setIsDeleting(false);
    }
  };

  return (
    <div className="space-y-6">
      <AdminBreadcrumb
        current={title}
        parent="Master Directories"
        parentHref="/admin/master-directories/document-types"
      />

      <Card className="overflow-hidden rounded-3xl border-[var(--theme-border-soft)] bg-white py-0 shadow-sm">
        <AdminTableToolbar
          stats={[
            {
              label: t("admin.total"),
              count: pagination.total,
              icon: <FolderTree className="h-4 w-4" />,
            },
            {
              label: t("admin.active"),
              count: activeCount,
              icon: <CheckCircle className="h-4 w-4" />,
              tone: "success",
            },
            {
              label: t("admin.inactive"),
              count: inactiveCount,
              icon: <XCircle className="h-4 w-4" />,
              tone: "danger",
            },
          ]}
          searchValue={searchTerm}
          searchPlaceholder={`${t("admin.searchPrefix")} ${localizedTitle}`}
          onSearchChange={setSearchTerm}
        >
          <Button
            type="button"
            className="h-11 rounded-2xl px-4 text-sm font-bold"
            onClick={openAddDialog}
          >
            <Plus className="h-4 w-4" />
            {t("admin.add")} {localizedSingularTitle}
          </Button>
        </AdminTableToolbar>

        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{localizedSingularTitle}</TableHead>
                {enableImageUpload && <TableHead>Image</TableHead>}
                <TableHead>{t("admin.hindiTitle")}</TableHead>
                <TableHead>{t("common.status")}</TableHead>
                <TableHead>{t("admin.createdBy")}</TableHead>
                <TableHead>{t("admin.updatedBy")}</TableHead>
                <TableHead className="text-right">
                  {t("common.actions")}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableRow>
                  <TableCell colSpan={enableImageUpload ? 7 : 6}>
                    <div className="flex items-center justify-center gap-3 py-8 text-sm font-medium text-muted-foreground">
                      <Loader2 className="h-4 w-4 animate-spin text-[var(--theme-primary)]" />
                      {t("common.loading")}
                    </div>
                  </TableCell>
                </TableRow>
              ) : filteredItems.length > 0 ? (
                filteredItems.map((item) => {
                  const status = getStatus(item);

                  return (
                    <TableRow key={item.uuid || item.id}>
                      <TableCell className="font-semibold">
                        {getItemTitle(item)}
                      </TableCell>
                      {enableImageUpload && (
                        <TableCell>
                          {item.image ? (
                            <img
                              src={imageUrl(item.image)}
                              alt={getItemTitle(item)}
                              className="h-12 w-16 rounded-xl object-cover"
                            />
                          ) : (
                            <div className="flex h-12 w-16 items-center justify-center rounded-xl bg-[var(--theme-surface)] text-slate-600">
                              <ImageIcon className="h-5 w-5" />
                            </div>
                          )}
                        </TableCell>
                      )}
                      <TableCell>{item.title_hi || "-"}</TableCell>
                      <TableCell>
                        <StatusBadge
                          status={status}
                          label={statusLabel(status)}
                        />
                      </TableCell>
                      <TableCell>{getActorLabel(item.created_by)}</TableCell>
                      <TableCell>{getActorLabel(item.updated_by)}</TableCell>
                      <TableCell>
                        <div className="flex justify-end gap-2">
                          <button
                            type="button"
                            aria-label={`Change ${getItemTitle(item)} status`}
                            className={`relative h-[22px] w-10 rounded-full border transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--theme-secondary)]/30 ${
                              status === "active"
                                ? "border-[var(--theme-primary)] bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] shadow-sm shadow-[var(--theme-secondary)]/20"
                                : "border-[var(--theme-border-soft)] bg-[var(--theme-border-soft)]"
                            }`}
                            disabled={statusUpdatingUuid === item.uuid}
                            onClick={() => changeStatus(item)}
                          >
                            <span
                              className={`absolute left-0.5 top-1/2 h-4 w-4 -translate-y-1/2 rounded-full bg-white shadow-sm ring-1 ring-black/5 transition-transform duration-200 ${
                                status === "active"
                                  ? "translate-x-[18px]"
                                  : "translate-x-0.5"
                              }`}
                            />
                          </button>
                          <Button
                            type="button"
                            variant="outline"
                            size="icon"
                            className="h-9 w-9 rounded-xl border-0 bg-[var(--theme-border-soft)] text-slate-600 shadow-none hover:bg-[var(--theme-border-soft)] hover:text-[#6f5a4c]"
                            onClick={() => openViewDialog(item)}
                          >
                            <Eye className="h-4 w-4" />
                            <span className="sr-only">{t("common.view")}</span>
                          </Button>
                          <Button
                            type="button"
                            variant="outline"
                            size="icon"
                            className="h-9 w-9 rounded-xl border-0 bg-[var(--theme-border-soft)] text-slate-600 shadow-none hover:bg-[var(--theme-border-soft)] hover:text-[#6f5a4c]"
                            onClick={() => openEditDialog(item)}
                          >
                            <Pencil className="h-4 w-4" />
                            <span className="sr-only">{t("common.edit")}</span>
                          </Button>
                          <Button
                            type="button"
                            variant="outline"
                            size="icon"
                            className="h-9 w-9 rounded-xl border-0 bg-[#fff1f1] text-red-600 shadow-none hover:bg-[#ffe4e4] hover:text-red-700"
                            onClick={() => setDeleteItem(item)}
                          >
                            <Trash2 className="h-4 w-4" />
                            <span className="sr-only">
                              {t("common.delete")}
                            </span>
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  );
                })
              ) : (
                <TableRow>
                  <TableCell colSpan={enableImageUpload ? 7 : 6}>
                    <div className="py-8 text-center text-sm font-medium text-muted-foreground">
                      {error ||
                        `${localizedTitle} ${t("admin.noReportsFound")}`}
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>

          <AdminTablePagination
            total={pagination.total}
            pageSize={pagination.per_page}
            currentPage={pagination.current_page}
            totalPages={getPageCount(pagination)}
            from={pagination.from}
            to={pagination.to}
            isLoading={isLoading}
            onPageChange={(page) => fetchItems(page)}
          />
        </CardContent>
      </Card>

      <Dialog open={isFormDialogOpen} onOpenChange={handleFormDialogOpenChange}>
        <DialogContent className="max-h-[90vh] max-w-[calc(100%-2rem)] overflow-y-auto rounded-3xl border-[var(--theme-border-soft)] p-0 sm:max-w-4xl">
          <form noValidate onSubmit={handleSubmit}>
            <DialogHeader className="border-b border-[var(--theme-border-soft)] bg-white px-6 py-5">
              <DialogTitle className="text-xl font-black text-[#1f1711]">
                {editingItem
                  ? `${t("common.edit")} ${localizedSingularTitle}`
                  : `${t("admin.add")} ${localizedSingularTitle}`}
              </DialogTitle>
              <DialogDescription>
                {editingItem
                  ? `${localizedSingularTitle} अपडेट करें।`
                  : `${localizedSingularTitle} जोड़ें।`}
              </DialogDescription>
            </DialogHeader>

            <div className="grid gap-5 bg-white px-6 py-6 md:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="title">
                  {t("admin.title")} <RequiredMark />
                </Label>
                <Input
                  id="title"
                  value={form.title}
                  onChange={(event) =>
                    updateFormField("title", event.target.value)
                  }
                  placeholder="Enter title"
                  className={formControlClass}
                  aria-invalid={Boolean(getFieldError(formErrors, "title"))}
                />
                {getFieldError(formErrors, "title") && (
                  <p className="text-xs font-medium text-red-600">
                    {getFieldError(formErrors, "title")}
                  </p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="title_hi">
                  {t("admin.hindiTitle")} <RequiredMark />
                </Label>
                <Input
                  id="title_hi"
                  value={form.title_hi}
                  onChange={(event) =>
                    updateFormField("title_hi", event.target.value)
                  }
                  placeholder="Hindi title"
                  className={formControlClass}
                  aria-invalid={Boolean(getFieldError(formErrors, "title_hi"))}
                />
                {getFieldError(formErrors, "title_hi") && (
                  <p className="text-xs font-medium text-red-600">
                    {getFieldError(formErrors, "title_hi")}
                  </p>
                )}
              </div>

              <div className="space-y-2 md:col-span-2">
                <Label htmlFor="description">
                  {t("admin.description")} <RequiredMark />
                </Label>
                <Textarea
                  id="description"
                  value={form.description}
                  onChange={(event) =>
                    updateFormField("description", event.target.value)
                  }
                  placeholder="Enter description"
                  className="min-h-24 rounded-2xl border-[var(--theme-border-soft)]"
                  aria-invalid={Boolean(
                    getFieldError(formErrors, "description"),
                  )}
                />
                {getFieldError(formErrors, "description") && (
                  <p className="text-xs font-medium text-red-600">
                    {getFieldError(formErrors, "description")}
                  </p>
                )}
              </div>

              <div className="space-y-2 md:col-span-2">
                <Label htmlFor="description_hi">
                  {t("admin.descriptionHindi")} <RequiredMark />
                </Label>
                <Textarea
                  id="description_hi"
                  value={form.description_hi}
                  onChange={(event) =>
                    updateFormField("description_hi", event.target.value)
                  }
                  placeholder="Hindi description"
                  className="min-h-24 rounded-2xl border-[var(--theme-border-soft)]"
                  aria-invalid={Boolean(
                    getFieldError(formErrors, "description_hi"),
                  )}
                />
                {getFieldError(formErrors, "description_hi") && (
                  <p className="text-xs font-medium text-red-600">
                    {getFieldError(formErrors, "description_hi")}
                  </p>
                )}
              </div>

              {enableImageUpload && (
                <MasterImageUpload
                  preview={form.imagePreview}
                  error={getFieldError(formErrors, "image")}
                  onChange={updateImageField}
                  onRemove={removeImageField}
                />
              )}

              <div className="space-y-2">
                <Label htmlFor="status">
                  {t("common.status")} <RequiredMark />
                </Label>
                <select
                  id="status"
                  value={form.status}
                  onChange={(event) =>
                    updateFormField(
                      "status",
                      event.target.value as MasterForm["status"],
                    )
                  }
                  className={formSelectClass}
                  aria-invalid={Boolean(getFieldError(formErrors, "status"))}
                >
                  <option value="active">{t("admin.active")}</option>
                  <option value="inactive">{t("admin.inactive")}</option>
                </select>
                {getFieldError(formErrors, "status") && (
                  <p className="text-xs font-medium text-red-600">
                    {getFieldError(formErrors, "status")}
                  </p>
                )}
              </div>
            </div>

            <DialogFooter className="border-t border-[var(--theme-border-soft)] bg-white px-6 py-4">
              <Button
                type="button"
                variant="outline"
                className="h-11 rounded-2xl border-[var(--theme-border-soft)] bg-white px-5"
                onClick={() => handleFormDialogOpenChange(false)}
                disabled={isSubmitting}
              >
                {t("common.cancel")}
              </Button>
              <Button
                type="submit"
                className="h-11 rounded-2xl px-5"
                disabled={isSubmitting}
              >
                {isSubmitting && <Loader2 className="h-4 w-4 animate-spin" />}
                {editingItem
                  ? `${t("common.save")} ${localizedSingularTitle}`
                  : `${t("common.save")} ${localizedSingularTitle}`}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-h-[90vh] max-w-[calc(100%-2rem)] overflow-y-auto rounded-3xl border-[var(--theme-border-soft)] p-0 sm:max-w-3xl">
          <DialogHeader className="border-b border-[var(--theme-border-soft)] px-6 py-5">
            <DialogTitle className="text-xl font-black text-[#1f1711]">
              {localizedSingularTitle} Detail
            </DialogTitle>
            <DialogDescription>
              View {singularTitle.toLowerCase()} information in English and
              Hindi.
            </DialogDescription>
          </DialogHeader>

          {isFetchingDetail ? (
            <div className="flex items-center justify-center gap-3 px-6 py-10 text-muted-foreground">
              <Loader2 className="h-5 w-5 animate-spin text-[var(--theme-primary)]" />
              Loading {singularTitle.toLowerCase()}...
            </div>
          ) : viewItem ? (
            <div className="px-6 py-2">
              <DetailItem
                label={t("admin.title")}
                value={getItemTitle(viewItem)}
              />
              {enableImageUpload && (
                <DetailItem
                  label="Image"
                  value={
                    viewItem.image ? (
                      <img
                        src={imageUrl(viewItem.image)}
                        alt={getItemTitle(viewItem)}
                        className="h-24 w-32 rounded-2xl object-cover"
                      />
                    ) : (
                      "-"
                    )
                  }
                />
              )}
              <DetailItem
                label={t("admin.hindiTitle")}
                value={viewItem.title_hi}
              />
              <DetailItem
                label={t("admin.description")}
                value={viewItem.description}
              />
              <DetailItem
                label={t("admin.descriptionHindi")}
                value={viewItem.description_hi}
              />
              <DetailItem
                label="Status"
                value={
                  <StatusBadge
                    status={getStatus(viewItem)}
                    label={statusLabel(getStatus(viewItem))}
                  />
                }
              />
            </div>
          ) : null}
        </DialogContent>
      </Dialog>

      <AlertDialog
        open={Boolean(deleteItem)}
        onOpenChange={(open) => {
          if (!open) setDeleteItem(null);
        }}
      >
        <AlertDialogContent className="rounded-3xl border-[var(--theme-border-soft)]">
          <AlertDialogHeader>
            <AlertDialogTitle className="text-xl font-black text-[#1f1711]">
              {t("common.delete")} {localizedSingularTitle}
            </AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete{" "}
              <span className="font-bold text-[#1f1711]">
                {deleteItem ? getItemTitle(deleteItem) : ""}
              </span>
              ? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel
              className="h-11 rounded-2xl border-[var(--theme-border-soft)] bg-white px-5"
              disabled={isDeleting}
            >
              {t("common.cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              className="h-11 rounded-2xl bg-red-600 px-5 text-white shadow-sm hover:bg-red-700"
              disabled={isDeleting}
              onClick={handleDelete}
            >
              {isDeleting && <Loader2 className="h-4 w-4 animate-spin" />}
              {t("common.delete")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
