"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Eye,
  CheckCircle,
  XCircle,
  Pencil,
  Trash2,
  Clock,
  BookOpen,
  AlertTriangle,
  Download,
  FileText,
  FileSpreadsheet,
  Mail,
  Phone,
  Upload,
} from "lucide-react";
import { apiRequest, apiUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";
import { AdminBreadcrumb } from "@/components/admin/admin-breadcrumb";
import { AdminTableToolbar } from "@/components/admin/admin-table-toolbar";
import { AdminActionButton } from "@/components/admin/admin-action-button";
import { TrustedGuideIcon } from "@/components/guides/trusted-guide-icon";
import { AdminTablePagination } from "@/components/admin/admin-table-pagination";
import { useLanguage } from "@/lib/i18n";
import { toast } from "react-toastify";

type GuideStatus = "pending" | "approved" | "rejected" | "blocked";
type GuideStatusFilter = GuideStatus | "all";
type GuideExportExtension = "csv" | "xlsx" | "pdf";

type ApiListItem = {
  id?: number | string;
  uuid?: string;
  title?: string;
  title_hi?: string | null;
  name?: string;
  name_hi?: string | null;
  course_name?: string | null;
  course_title?: string | null;
  district_name?: string | null;
  district_name_hi?: string | null;
  course_location?: string | null;
  course_location_hi?: string | null;
};

type ApiCourseDistrict = ApiListItem & {
  district?: ApiListItem | string | null;
  course?: ApiCourse | null;
};

type ApiCourse = ApiListItem & {
  district?: ApiListItem | string | null;
  districts?: Array<ApiListItem | string> | null;
  locations?: Array<ApiListItem | string> | null;
  course?: ApiCourse | null;
  course_district?: ApiCourseDistrict | null;
  course_districts?: ApiCourseDistrict[] | null;
};

type GuideDocument = ApiListItem & {
  document_type?: ApiListItem | string | null;
  file?: string;
  file_url?: string;
  url?: string;
  status?: string;
};

type AdminGuide = {
  id: number | string;
  uuid: string;
  name: string;
  name_hi?: string | null;
  email: string;
  phone: string;
  alternate_phone?: string | null;
  address?: string | null;
  address_hi?: string | null;
  year_of_experience?: number | string | null;
  bio?: string | null;
  bio_hi?: string | null;
  status: GuideStatus | string;
  reject_reason?: string | null;
  languages: Array<ApiListItem | string>;
  skills: Array<ApiListItem | string>;
  locations: Array<ApiListItem | string>;
  course?: ApiCourse | null;
  course_district?: ApiCourseDistrict | null;
  guide_documents: GuideDocument[];
  is_trusted?: string | number | boolean | null;
  is_trusted_guide?: string | number | boolean | null;
  trusted_guide?: string | number | boolean | null;
  trustedGuide?: string | number | boolean | null;
  isTrusted?: string | number | boolean | null;
};

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

type GuidesResponse = {
  statusCode: number;
  success: boolean;
  status_counts?: Record<string, number | string | null | undefined>;
  statusCounts?: Record<string, number | string | null | undefined>;
  data?: {
    guides?: PaginatedGuides;
    status_counts?: Record<string, number | string | null | undefined>;
    statusCounts?: Record<string, number | string | null | undefined>;
  };
  message?: string;
  message_hi?: string;
};

type ChangeStatusResponse = {
  statusCode: number;
  success: boolean;
  data?:
    | {
        guide?: AdminGuide;
      }
    | unknown;
  message?: string;
  message_hi?: string;
};

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

type GuideOptionsResponse = {
  statusCode: number;
  success: boolean;
  data?: {
    languages?: ApiListItem[];
    skills?: ApiListItem[];
    locations?: ApiListItem[];
  };
  message?: string;
  message_hi?: string;
};

type GuideOptions = {
  languages: ApiListItem[];
  skills: ApiListItem[];
  locations: ApiListItem[];
};

type GuideEditForm = {
  name: string;
  name_hi: string;
  email: string;
  phone: string;
  alternate_phone: string;
  address: string;
  address_hi: string;
  year_of_experience: string;
  bio: string;
  bio_hi: string;
  language_uuids: string[];
  skill_uuids: string[];
  location_uuids: string[];
};

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

const emptyStatusCounts: Record<GuideStatusFilter, number> = {
  all: 0,
  pending: 0,
  approved: 0,
  rejected: 0,
  blocked: 0,
};

const emptyGuideOptions: GuideOptions = {
  languages: [],
  skills: [],
  locations: [],
};

function toCount(value: number | string | null | undefined) {
  const count = Number(value);
  return Number.isFinite(count) ? count : 0;
}

function normalizeStatusCounts(
  counts?: Record<string, number | string | null | undefined>,
): Record<GuideStatusFilter, number> {
  const pending = toCount(counts?.pending);
  const approved = toCount(counts?.approved ?? counts?.active);
  const rejected = toCount(counts?.rejected);
  const blocked = toCount(counts?.blocked);

  return {
    all:
      toCount(counts?.all ?? counts?.total) ||
      pending + approved + rejected + blocked,
    pending,
    approved,
    rejected,
    blocked,
  };
}

const emptyGuideEditForm: GuideEditForm = {
  name: "",
  name_hi: "",
  email: "",
  phone: "",
  alternate_phone: "",
  address: "",
  address_hi: "",
  year_of_experience: "",
  bio: "",
  bio_hi: "",
  language_uuids: [],
  skill_uuids: [],
  location_uuids: [],
};

const guideImportTemplateHeaders = [
  "name",
  "email",
  "phone",
  "address",
  "year_of_experience",
  "bio",
  "status",
  "languages",
  "locations",
  "skills",
];

const guideExportExtensions: GuideExportExtension[] = ["csv", "xlsx", "pdf"];
const guideExportStatuses: GuideStatusFilter[] = [
  "all",
  "pending",
  "approved",
  "rejected",
  "blocked",
];

const crcTable = Array.from({ length: 256 }, (_, index) => {
  let crc = index;

  for (let bit = 0; bit < 8; bit += 1) {
    crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;
  }

  return crc >>> 0;
});

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

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

  return token;
}

function normalizeStatus(value: string | null): GuideStatusFilter {
  if (value === "all") return "all";

  if (
    value === "approved" ||
    value === "rejected" ||
    value === "pending" ||
    value === "blocked"
  ) {
    return value;
  }

  return "all";
}

function getItemLabel(item: ApiListItem | string) {
  if (typeof item === "string") return item;
  return item.title || item.name || String(item.id || item.uuid || "-");
}

function getOptionalItemLabel(item?: ApiListItem | string | null) {
  if (!item) return "";
  if (typeof item === "string") return item.trim();

  return (
    item.title ||
    item.name ||
    item.course_name ||
    item.course_title ||
    item.district_name ||
    item.course_location ||
    ""
  ).trim();
}

function getItemUuid(item: ApiListItem | string) {
  if (typeof item === "string") return item;
  return item.uuid || String(item.id || "");
}

function firstItem<T>(items?: T[] | null) {
  return Array.isArray(items) ? items[0] : undefined;
}

function getGuideCourseName(guide: AdminGuide) {
  return (
    getOptionalItemLabel(guide.course?.course) ||
    getOptionalItemLabel(guide.course) ||
    getOptionalItemLabel(guide.course_district?.course)
  );
}

function getGuideCourseDistrictName(guide: AdminGuide) {
  const course = guide.course;
  const courseDistrict =
    guide.course_district ||
    course?.course_district ||
    firstItem(course?.course_districts);

  return (
    getOptionalItemLabel(courseDistrict?.district) ||
    getOptionalItemLabel(course?.district) ||
    getOptionalItemLabel(firstItem(course?.districts)) ||
    getOptionalItemLabel(firstItem(course?.locations)) ||
    getOptionalItemLabel({
      district_name: course?.district_name,
      course_location: course?.course_location,
    })
  );
}

function fieldValue(value: unknown) {
  return value === null || value === undefined ? "" : String(value);
}

function isEnabledValue(value: unknown) {
  if (typeof value === "boolean") return value;
  if (typeof value === "number") return value === 1;

  if (typeof value === "string") {
    return ["1", "true", "yes"].includes(value.trim().toLowerCase());
  }

  return false;
}

function isTrustedGuide(guide: AdminGuide) {
  return isEnabledValue(
    guide.is_trusted ??
      guide.is_trusted_guide ??
      guide.trusted_guide ??
      guide.trustedGuide ??
      guide.isTrusted,
  );
}

function createGuideUpdatePayload(
  guide: AdminGuide,
  overrides: Record<string, unknown> = {},
) {
  return {
    name: fieldValue(guide.name).trim(),
    name_hi: fieldValue(guide.name_hi),
    email: fieldValue(guide.email).trim(),
    phone: fieldValue(guide.phone).trim(),
    alternate_phone: fieldValue(guide.alternate_phone),
    address: fieldValue(guide.address),
    address_hi: fieldValue(guide.address_hi),
    year_of_experience: fieldValue(guide.year_of_experience),
    bio: fieldValue(guide.bio),
    bio_hi: fieldValue(guide.bio_hi),
    language_uuids: guide.languages.map(getItemUuid).filter(Boolean),
    skill_uuids: guide.skills.map(getItemUuid).filter(Boolean),
    location_uuids: guide.locations.map(getItemUuid).filter(Boolean),
    ...overrides,
  };
}

function escapeXml(value: string) {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function getColumnName(index: number) {
  let column = "";
  let value = index + 1;

  while (value > 0) {
    const remainder = (value - 1) % 26;
    column = String.fromCharCode(65 + remainder) + column;
    value = Math.floor((value - 1) / 26);
  }

  return column;
}

function stringToBytes(value: string) {
  return new TextEncoder().encode(value);
}

function concatBytes(parts: Uint8Array[]) {
  const totalLength = parts.reduce((sum, part) => sum + part.length, 0);
  const output = new Uint8Array(totalLength);
  let offset = 0;

  parts.forEach((part) => {
    output.set(part, offset);
    offset += part.length;
  });

  return output;
}

function crc32(bytes: Uint8Array) {
  let crc = 0xffffffff;

  bytes.forEach((byte) => {
    crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);
  });

  return (crc ^ 0xffffffff) >>> 0;
}

function writeUint16(bytes: number[], value: number) {
  bytes.push(value & 0xff, (value >>> 8) & 0xff);
}

function writeUint32(bytes: number[], value: number) {
  bytes.push(
    value & 0xff,
    (value >>> 8) & 0xff,
    (value >>> 16) & 0xff,
    (value >>> 24) & 0xff,
  );
}

function createZip(files: Array<{ name: string; content: string }>) {
  const localParts: Uint8Array[] = [];
  const centralParts: Uint8Array[] = [];
  let offset = 0;

  files.forEach((file) => {
    const nameBytes = stringToBytes(file.name);
    const contentBytes = stringToBytes(file.content);
    const checksum = crc32(contentBytes);
    const localHeader: number[] = [];
    const centralHeader: number[] = [];

    writeUint32(localHeader, 0x04034b50);
    writeUint16(localHeader, 20);
    writeUint16(localHeader, 0);
    writeUint16(localHeader, 0);
    writeUint16(localHeader, 0);
    writeUint16(localHeader, 0);
    writeUint32(localHeader, checksum);
    writeUint32(localHeader, contentBytes.length);
    writeUint32(localHeader, contentBytes.length);
    writeUint16(localHeader, nameBytes.length);
    writeUint16(localHeader, 0);

    localParts.push(new Uint8Array(localHeader), nameBytes, contentBytes);

    writeUint32(centralHeader, 0x02014b50);
    writeUint16(centralHeader, 20);
    writeUint16(centralHeader, 20);
    writeUint16(centralHeader, 0);
    writeUint16(centralHeader, 0);
    writeUint16(centralHeader, 0);
    writeUint16(centralHeader, 0);
    writeUint32(centralHeader, checksum);
    writeUint32(centralHeader, contentBytes.length);
    writeUint32(centralHeader, contentBytes.length);
    writeUint16(centralHeader, nameBytes.length);
    writeUint16(centralHeader, 0);
    writeUint16(centralHeader, 0);
    writeUint16(centralHeader, 0);
    writeUint16(centralHeader, 0);
    writeUint32(centralHeader, 0);
    writeUint32(centralHeader, offset);

    centralParts.push(new Uint8Array(centralHeader), nameBytes);
    offset += localHeader.length + nameBytes.length + contentBytes.length;
  });

  const centralDirectory = concatBytes(centralParts);
  const endHeader: number[] = [];

  writeUint32(endHeader, 0x06054b50);
  writeUint16(endHeader, 0);
  writeUint16(endHeader, 0);
  writeUint16(endHeader, files.length);
  writeUint16(endHeader, files.length);
  writeUint32(endHeader, centralDirectory.length);
  writeUint32(endHeader, offset);
  writeUint16(endHeader, 0);

  return concatBytes([
    ...localParts,
    centralDirectory,
    new Uint8Array(endHeader),
  ]);
}

function createGuideTemplateXlsxBlob() {
  const headerCells = guideImportTemplateHeaders
    .map(
      (header, index) =>
        `<c r="${getColumnName(index)}1" t="inlineStr"><is><t>${escapeXml(
          header,
        )}</t></is></c>`,
    )
    .join("");
  const worksheet = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData><row r="1">${headerCells}</row></sheetData></worksheet>`;
  const workbook = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Guides" sheetId="1" r:id="rId1"/></sheets></workbook>`;
  const rels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`;
  const workbookRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>`;
  const contentTypes = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>`;
  const bytes = createZip([
    { name: "[Content_Types].xml", content: contentTypes },
    { name: "_rels/.rels", content: rels },
    { name: "xl/workbook.xml", content: workbook },
    { name: "xl/_rels/workbook.xml.rels", content: workbookRels },
    { name: "xl/worksheets/sheet1.xml", content: worksheet },
  ]);

  return new Blob([bytes], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  });
}

function firstError(errors: ValidationErrors, field: string) {
  return errors[field]?.[0];
}

function getErrors(data: unknown) {
  if (!data || Array.isArray(data) || typeof data !== "object") {
    return {};
  }

  if ("guide" in data) {
    return {};
  }

  return data as ValidationErrors;
}

function guideToEditForm(guide: AdminGuide): GuideEditForm {
  return {
    name: fieldValue(guide.name),
    name_hi: fieldValue(guide.name_hi),
    email: fieldValue(guide.email),
    phone: fieldValue(guide.phone),
    alternate_phone: fieldValue(guide.alternate_phone),
    address: fieldValue(guide.address),
    address_hi: fieldValue(guide.address_hi),
    year_of_experience: fieldValue(guide.year_of_experience),
    bio: fieldValue(guide.bio),
    bio_hi: fieldValue(guide.bio_hi),
    language_uuids: guide.languages.map(getItemUuid).filter(Boolean),
    skill_uuids: guide.skills.map(getItemUuid).filter(Boolean),
    location_uuids: guide.locations.map(getItemUuid).filter(Boolean),
  };
}

function getStatusBadge(status: string, labels: Record<string, string>) {
  const normalizedStatus = status.toLowerCase();
  const variants: Record<string, string> = {
    pending: "bg-[var(--theme-surface-strong)] text-[var(--theme-primary)]",
    approved: "bg-green-50 text-green-700",
    rejected: "bg-red-50 text-red-700",
    blocked: "bg-amber-50 text-amber-700",
  };

  return (
    <Badge
      className={`${variants[normalizedStatus] || "bg-gray-100 text-gray-700"} gap-1.5 rounded-full px-3 py-1 font-semibold capitalize shadow-none`}
    >
      <span className="h-1.5 w-1.5 rounded-full bg-current" />
      {labels[normalizedStatus] || normalizedStatus}
    </Badge>
  );
}

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

function canApproveGuide(status: string) {
  const normalizedStatus = status.toLowerCase();
  return (
    normalizedStatus === "pending" ||
    normalizedStatus === "rejected" ||
    normalizedStatus === "blocked"
  );
}

function canRejectGuide(status: string) {
  const normalizedStatus = status.toLowerCase();
  return normalizedStatus === "pending" || normalizedStatus === "approved";
}

function EditField({
  id,
  label,
  value,
  onChange,
  error,
  type = "text",
}: {
  id: string;
  label: string;
  value: string;
  onChange: (value: string) => void;
  error?: string;
  type?: string;
}) {
  return (
    <div className="space-y-2">
      <Label htmlFor={id} className="text-sm font-bold">
        {label}
      </Label>
      <Input
        id={id}
        type={type}
        value={value}
        onChange={(event) => onChange(event.target.value)}
        className="rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
      />
      {error && <p className="text-xs font-semibold text-red-600">{error}</p>}
    </div>
  );
}

function EditTextarea({
  id,
  label,
  value,
  onChange,
  error,
  rows = 3,
}: {
  id: string;
  label: string;
  value: string;
  onChange: (value: string) => void;
  error?: string;
  rows?: number;
}) {
  return (
    <div className="space-y-2">
      <Label htmlFor={id} className="text-sm font-bold">
        {label}
      </Label>
      <Textarea
        id={id}
        value={value}
        onChange={(event) => onChange(event.target.value)}
        rows={rows}
        className="rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
      />
      {error && <p className="text-xs font-semibold text-red-600">{error}</p>}
    </div>
  );
}

function MultiSelectField({
  label,
  options,
  selected,
  onToggle,
  error,
}: {
  label: string;
  options: ApiListItem[];
  selected: string[];
  onToggle: (uuid: string) => void;
  error?: string;
}) {
  return (
    <div className="space-y-3">
      <Label className="text-sm font-bold">{label}</Label>
      <div className="grid max-h-44 gap-2 overflow-y-auto rounded-2xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] p-3 sm:grid-cols-2">
        {options.map((option) => {
          const uuid = getItemUuid(option);
          const checked = selected.includes(uuid);

          return (
            <label
              key={uuid}
              className="flex cursor-pointer items-center gap-2 rounded-xl bg-white px-3 py-2 text-sm font-semibold"
            >
              <Checkbox
                checked={checked}
                onCheckedChange={() => onToggle(uuid)}
              />
              {getItemLabel(option)}
            </label>
          );
        })}
        {options.length === 0 && (
          <p className="text-sm text-muted-foreground">No options available.</p>
        )}
      </div>
      {error && <p className="text-xs font-semibold text-red-600">{error}</p>}
    </div>
  );
}

export default function AdminGuidesPage() {
  const { t } = useLanguage();
  const router = useRouter();
  const searchParams = useSearchParams();
  const [guides, setGuides] = useState<AdminGuide[]>([]);
  const [pagination, setPagination] =
    useState<PaginatedGuides>(emptyPagination);
  const [searchTerm, setSearchTerm] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [statusCounts, setStatusCounts] =
    useState<Record<GuideStatusFilter, number>>(emptyStatusCounts);
  const [statusUpdatingUuid, setStatusUpdatingUuid] = useState<string | null>(
    null,
  );
  const [trustedUpdatingUuid, setTrustedUpdatingUuid] = useState<string | null>(
    null,
  );
  const [rejectGuide, setRejectGuide] = useState<AdminGuide | null>(null);
  const [deleteGuide, setDeleteGuide] = useState<AdminGuide | null>(null);
  const [rejectReason, setRejectReason] = useState("");
  const [editGuide, setEditGuide] = useState<AdminGuide | null>(null);
  const [editForm, setEditForm] = useState<GuideEditForm>(emptyGuideEditForm);
  const [editErrors, setEditErrors] = useState<ValidationErrors>({});
  const [guideOptions, setGuideOptions] =
    useState<GuideOptions>(emptyGuideOptions);
  const [isOptionsLoading, setIsOptionsLoading] = useState(false);
  const [isGuideSaving, setIsGuideSaving] = useState(false);
  const [isImporting, setIsImporting] = useState(false);
  const [isExporting, setIsExporting] = useState(false);
  const [isImportModalOpen, setIsImportModalOpen] = useState(false);
  const [isExportModalOpen, setIsExportModalOpen] = useState(false);
  const [exportStatus, setExportStatus] = useState<GuideStatusFilter>("all");
  const [exportExtension, setExportExtension] =
    useState<GuideExportExtension>("xlsx");
  const [selectedImportFile, setSelectedImportFile] = useState<File | null>(
    null,
  );
  const importInputRef = useRef<HTMLInputElement | null>(null);

  const activeStatus = normalizeStatus(searchParams.get("status"));
  const activePage = Number(searchParams.get("page") || 1);
  const activeSearch = searchParams.get("search") || "";
  const statusLabels: Record<string, string> = {
    pending: t("common.pending"),
    approved: t("admin.active"),
    rejected: "Deactivated",
    blocked: "Temporarily Blocked",
  };

  const fetchGuides = useCallback(
    async (status: GuideStatusFilter, page: number, search = "") => {
      setIsLoading(true);
      setError("");

      try {
        const token = getAdminToken();
        const params = new URLSearchParams({ page: String(page) });
        const trimmedSearch = search.trim();

        if (trimmedSearch) {
          params.set("search", trimmedSearch);
        }

        if (status !== "all") {
          params.set("status", status);
        }

        const response = await apiRequest(apiUrl(`/admin/guides?${params}`), {
          method: "GET",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
          },
        });
        const result = (await response.json()) as GuidesResponse;

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

        const nextPagination = result.data?.guides || emptyPagination;
        const nextStatusCounts =
          result.data?.status_counts ||
          result.data?.statusCounts ||
          result.status_counts ||
          result.statusCounts;

        setPagination(nextPagination);
        setGuides(nextPagination.data || []);
        setStatusCounts(normalizeStatusCounts(nextStatusCounts));
      } catch (fetchError) {
        const message =
          fetchError instanceof Error
            ? fetchError.message
            : "Failed to load guides.";

        setError(message);
        setPagination(emptyPagination);
        setGuides([]);
        setStatusCounts(emptyStatusCounts);
      } finally {
        setIsLoading(false);
      }
    },
    [],
  );

  const updateSearchUrl = useCallback(
    (search: string) => {
      const params = new URLSearchParams({ page: "1" });
      const trimmedSearch = search.trim();

      if (trimmedSearch) {
        params.set("search", trimmedSearch);
      }

      if (activeStatus !== "all") {
        params.set("status", activeStatus);
      }

      router.push(`/admin/guides?${params}`);
    },
    [activeStatus, router],
  );

  useEffect(() => {
    setSearchTerm(activeSearch);
    fetchGuides(activeStatus, activePage, activeSearch);
  }, [activePage, activeSearch, activeStatus, fetchGuides]);

  useEffect(() => {
    if (searchTerm === activeSearch) {
      return;
    }

    const timer = window.setTimeout(() => {
      updateSearchUrl(searchTerm);
    }, 350);

    return () => window.clearTimeout(timer);
  }, [activeSearch, searchTerm, updateSearchUrl]);

  const updateListUrl = (
    status: GuideStatusFilter,
    page = 1,
    search = activeSearch,
  ) => {
    const params = new URLSearchParams({ page: String(page) });
    const trimmedSearch = search.trim();

    if (trimmedSearch) {
      params.set("search", trimmedSearch);
    }

    if (status !== "all") {
      params.set("status", status);
    }

    router.push(`/admin/guides?${params}`);
  };

  const openDetails = (guide: AdminGuide) => {
    const guideKey = guide.uuid || String(guide.id);
    router.push(`/admin/guides/${guideKey}`);
  };

  const fetchGuideOptions = useCallback(async () => {
    if (
      guideOptions.languages.length > 0 &&
      guideOptions.skills.length > 0 &&
      guideOptions.locations.length > 0
    ) {
      return;
    }

    setIsOptionsLoading(true);

    try {
      const response = await apiRequest(apiUrl("/guide-registration/options"), {
        method: "GET",
        headers: {
          Accept: "application/json",
        },
      });
      const result = (await response.json()) as GuideOptionsResponse;

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

      setGuideOptions({
        languages: result.data?.languages || [],
        skills: result.data?.skills || [],
        locations: result.data?.locations || [],
      });
    } catch (optionsError) {
      setError(
        optionsError instanceof Error
          ? optionsError.message
          : "Failed to load guide options.",
      );
    } finally {
      setIsOptionsLoading(false);
    }
  }, [guideOptions]);

  const openEdit = (guide: AdminGuide) => {
    const guideKey = guide.uuid || String(guide.id);
    router.push(`/admin/guides/${guideKey}/edit`);
  };

  const setEditField = (field: keyof GuideEditForm, value: string) => {
    setEditForm((current) => ({ ...current, [field]: value }));
    setEditErrors((current) => ({ ...current, [field]: [] }));
  };

  const toggleEditSelection = (
    field: "language_uuids" | "skill_uuids" | "location_uuids",
    uuid: string,
  ) => {
    setEditForm((current) => {
      const selected = current[field];
      const nextSelected = selected.includes(uuid)
        ? selected.filter((value) => value !== uuid)
        : [...selected, uuid];

      return { ...current, [field]: nextSelected };
    });
    setEditErrors((current) => ({ ...current, [field]: [] }));
  };

  const closeEdit = () => {
    setEditGuide(null);
    setEditForm(emptyGuideEditForm);
    setEditErrors({});
  };

  const getExportFilename = (
    response: Response,
    status: GuideStatusFilter,
    extension: GuideExportExtension,
  ) => {
    const disposition = response.headers.get("content-disposition") || "";
    const filenameMatch = disposition.match(/filename="?([^"]+)"?/i);

    if (filenameMatch?.[1]) {
      return filenameMatch[1];
    }

    return status === "all"
      ? `guides-export.${extension}`
      : `guides-${status}-export.${extension}`;
  };

  const exportGuides = async (
    status: GuideStatusFilter,
    extension: GuideExportExtension,
  ) => {
    setIsExporting(true);
    setError("");

    try {
      const token = getAdminToken();
      const params = new URLSearchParams();
      params.set("extension", extension);

      if (status !== "all") {
        params.set("status", status);
      }

      const response = await apiRequest(
        apiUrl(`/admin/guides/export?${params}`),
        {
          method: "GET",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
          },
        },
      );

      if (!response.ok) {
        const result = await response.json().catch(() => ({}));
        throw new Error(getLocalizedApiMessage(result, "Guide export failed."));
      }

      const blob = await response.blob();
      const downloadUrl = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = downloadUrl;
      link.download = getExportFilename(response, status, extension);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(downloadUrl);
      toast.success("Guide export downloaded successfully.");
      setIsExportModalOpen(false);
    } catch (exportError) {
      const message =
        exportError instanceof Error
          ? exportError.message
          : "Guide export failed.";
      setError(message);
      toast.error(message);
    } finally {
      setIsExporting(false);
    }
  };

  const downloadBlob = (blob: Blob, filename: string) => {
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(downloadUrl);
  };

  const downloadCsvTemplate = () => {
    const csvContent = `${guideImportTemplateHeaders.join(",")}\r\n`;
    downloadBlob(
      new Blob([csvContent], { type: "text/csv;charset=utf-8" }),
      "guide-import-template.csv",
    );
  };

  const downloadXlsxTemplate = () => {
    downloadBlob(createGuideTemplateXlsxBlob(), "guide-import-template.xlsx");
  };

  const closeImportModal = () => {
    setIsImportModalOpen(false);
    setSelectedImportFile(null);

    if (importInputRef.current) {
      importInputRef.current.value = "";
    }
  };

  const importGuides = async (file: File) => {
    setIsImporting(true);
    setError("");

    try {
      const token = getAdminToken();
      const formData = new FormData();
      formData.append("file", file);

      const response = await apiRequest(apiUrl("/admin/guides/import"), {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: "application/json",
        },
        body: formData,
      });
      const result = await response.json().catch(() => ({}));

      if (!response.ok || result.success === false) {
        throw new Error(getLocalizedApiMessage(result, "Guide import failed."));
      }

      toast.success(
        getLocalizedApiMessage(result, "Guides imported successfully."),
      );
      closeImportModal();
      await fetchGuides(activeStatus, activePage, activeSearch);
    } catch (importError) {
      const message =
        importError instanceof Error
          ? importError.message
          : "Guide import failed.";
      setError(message);
      toast.error(message);
    } finally {
      setIsImporting(false);
      if (importInputRef.current) {
        importInputRef.current.value = "";
      }
    }
  };

  const saveGuide = async () => {
    if (!editGuide) return;

    const guideUuid = editGuide.uuid || String(editGuide.id);
    setIsGuideSaving(true);
    setEditErrors({});
    setError("");

    try {
      const token = getAdminToken();
      const response = await apiRequest(apiUrl(`/admin/guides/${guideUuid}`), {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          ...createGuideUpdatePayload(editGuide),
          name: editForm.name.trim(),
          name_hi: editForm.name_hi,
          email: editForm.email.trim(),
          phone: editForm.phone.trim(),
          alternate_phone: editForm.alternate_phone,
          address: editForm.address,
          address_hi: editForm.address_hi,
          year_of_experience: editForm.year_of_experience,
          bio: editForm.bio,
          bio_hi: editForm.bio_hi,
          language_uuids: editForm.language_uuids,
          skill_uuids: editForm.skill_uuids,
          location_uuids: editForm.location_uuids,
        }),
      });
      const result = (await response.json()) as ChangeStatusResponse;

      if (!response.ok || result.success === false) {
        setEditErrors(getErrors(result.data));
        throw new Error(
          getLocalizedApiMessage(result, "Failed to update guide."),
        );
      }

      closeEdit();
      await fetchGuides(activeStatus, activePage, activeSearch);
    } catch (saveError) {
      setError(
        saveError instanceof Error
          ? saveError.message
          : "Failed to update guide.",
      );
    } finally {
      setIsGuideSaving(false);
    }
  };

  const changeGuideStatus = async (
    guide: AdminGuide,
    status: Extract<GuideStatus, "approved" | "rejected">,
    rejectReasonValue = "",
  ) => {
    const guideUuid = guide.uuid || String(guide.id);

    setStatusUpdatingUuid(guideUuid);
    setError("");

    try {
      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl(`/admin/guides/${guideUuid}/change-status`),
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            status,
            ...(status === "rejected"
              ? { reject_reason: rejectReasonValue }
              : {}),
          }),
        },
      );
      const result = (await response.json()) as ChangeStatusResponse;

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

      await fetchGuides(activeStatus, activePage, activeSearch);
      setRejectGuide(null);
      setRejectReason("");
    } catch (statusError) {
      setError(
        statusError instanceof Error
          ? statusError.message
          : "Failed to update guide status.",
      );
    } finally {
      setStatusUpdatingUuid(null);
    }
  };

  const changeTrustedGuide = async (guide: AdminGuide, trusted: boolean) => {
    const guideUuid = guide.uuid || String(guide.id);

    setTrustedUpdatingUuid(guideUuid);
    setError("");

    try {
      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl(`/admin/guides/${guideUuid}/change-trusted`),
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            is_trusted: trusted ? "yes" : "no",
          }),
        },
      );
      const result = (await response.json()) as ChangeStatusResponse;

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

      toast.success(
        getLocalizedApiMessage(
          result,
          trusted ? "Guide marked as trusted." : "Guide marked as normal.",
        ),
      );
      await fetchGuides(activeStatus, activePage, activeSearch);
    } catch (trustedError) {
      const message =
        trustedError instanceof Error
          ? trustedError.message
          : "Failed to update trusted guide.";
      setError(message);
      toast.error(message);
    } finally {
      setTrustedUpdatingUuid(null);
    }
  };
  const deleteSelectedGuide = async () => {
    if (!deleteGuide) return;

    const guideUuid = deleteGuide.uuid || String(deleteGuide.id);
    setStatusUpdatingUuid(guideUuid);
    setError("");

    try {
      const token = getAdminToken();
      const response = await apiRequest(apiUrl(`/admin/guides/${guideUuid}`), {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: "application/json",
        },
      });
      const result = (await response.json()) as ChangeStatusResponse;

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

      toast.success(
        getLocalizedApiMessage(result, "Guide deleted successfully."),
      );
      setDeleteGuide(null);
      await fetchGuides(activeStatus, activePage, activeSearch);
    } catch (deleteError) {
      const message =
        deleteError instanceof Error
          ? deleteError.message
          : "Failed to delete guide.";
      setError(message);
      toast.error(message);
    } finally {
      setStatusUpdatingUuid(null);
    }
  };

  const visibleFrom =
    pagination.from ??
    (pagination.total > 0
      ? (pagination.current_page - 1) * pagination.per_page + 1
      : 0);
  const visibleTo =
    pagination.to ??
    Math.min(pagination.total, pagination.current_page * pagination.per_page);

  return (
    <div className="space-y-6">
      <AdminBreadcrumb current="Guide Management" />

      <div className="flex flex-col gap-4 rounded-3xl border border-[var(--theme-border)] bg-white p-5 shadow-sm sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-black text-foreground">
            Guide Management
          </h1>
          <p className="mt-1 text-sm font-medium text-muted-foreground">
            Import, export, review, approve, reject, and manage guide records.
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <Button
            type="button"
            variant="outline"
            disabled={isImporting}
            className="h-10 rounded-full border-[var(--theme-border-soft)] font-bold"
            onClick={() => setIsImportModalOpen(true)}
          >
            <Upload className="h-4 w-4" />
            {isImporting ? "Importing..." : "Import"}
          </Button>
          <Button
            type="button"
            disabled={isExporting}
            className="h-10 rounded-full bg-[var(--theme-primary)] font-bold text-white hover:bg-[var(--theme-primary)]/90"
            onClick={() => {
              setExportStatus(activeStatus);
              setIsExportModalOpen(true);
            }}
          >
            <Download className="h-4 w-4" />
            {isExporting ? "Exporting..." : "Export"}
          </Button>
        </div>
      </div>

      <Card className="overflow-hidden rounded-3xl border-[var(--theme-border-soft)] bg-white py-0 shadow-sm">
        <AdminTableToolbar
          stats={[
            {
              label: t("admin.all"),
              count: statusCounts.all,
              icon: <BookOpen className="h-4 w-4" />,
              active: activeStatus === "all",
              onClick: () => updateListUrl("all"),
            },
            {
              label: t("common.pending"),
              count: statusCounts.pending,
              icon: <Clock className="h-4 w-4" />,
              tone: "warning",
              active: activeStatus === "pending",
              onClick: () => updateListUrl("pending"),
            },
            {
              label: t("admin.active"),
              count: statusCounts.approved,
              icon: <CheckCircle className="h-4 w-4" />,
              tone: "success",
              active: activeStatus === "approved",
              onClick: () => updateListUrl("approved"),
            },
            {
              label: "Deactivated",
              count: statusCounts.rejected,
              icon: <XCircle className="h-4 w-4" />,
              tone: "danger",
              active: activeStatus === "rejected",
              onClick: () => updateListUrl("rejected"),
            },
            {
              label: "Blocked",
              count: statusCounts.blocked,
              icon: <AlertTriangle className="h-4 w-4" />,
              tone: "warning",
              active: activeStatus === "blocked",
              onClick: () => updateListUrl("blocked"),
            },
          ]}
          searchValue={searchTerm}
          searchPlaceholder={t("admin.searchGuides")}
          onSearchChange={setSearchTerm}
          onSearchClear={() => {
            setSearchTerm("");
            updateSearchUrl("");
          }}
          compactStats
        />

        <CardContent className="p-0">
          {error && (
            <Alert className="m-6 border-red-200 bg-red-50 text-red-700">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t("admin.guide")}</TableHead>
                <TableHead>Course</TableHead>
                <TableHead>{t("admin.locations")}</TableHead>
                <TableHead>{t("common.status")}</TableHead>
                <TableHead>Verification Process</TableHead>
                <TableHead>Trusted Guide</TableHead>
                <TableHead className="text-right">
                  {t("common.actions")}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading && (
                <TableRow>
                  <TableCell
                    colSpan={7}
                    className="h-28 text-center text-muted-foreground"
                  >
                    {t("admin.loadingGuides")}
                  </TableCell>
                </TableRow>
              )}

              {!isLoading &&
                guides.map((guide) => (
                  <TableRow key={guide.uuid || guide.id}>
                    <TableCell className="w-[260px]">
                      <div className="space-y-1">
                        <div className="flex min-w-0 items-center gap-2 font-bold">
                          <span className="truncate">{guide.name}</span>
                          {isTrustedGuide(guide) && (
                            <Badge className="inline-flex items-center gap-1 rounded-full border-0 bg-gradient-to-r from-[var(--theme-secondary)] via-[var(--theme-primary)] to-[var(--theme-accent)] px-2 py-0.5 text-[10px] font-black text-white shadow-none hover:from-[var(--theme-primary)] hover:via-[var(--theme-secondary)] hover:to-[var(--theme-primary-dark)]">
                              <TrustedGuideIcon
                                className="h-3.5 w-3.5 shrink-0 text-white"
                                solid
                              />
                              Trusted
                            </Badge>
                          )}
                        </div>
                        <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
                          <Mail className="h-3.5 w-3.5 shrink-0 text-[var(--theme-primary)]" />
                          {guide.email}
                        </div>
                        <div className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground">
                          <Phone className="h-3.5 w-3.5 shrink-0 text-[var(--theme-primary)]" />
                          {guide.phone || "-"}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell className="w-[220px] align-middle">
                      <div className="max-w-[220px] space-y-1">
                        <p className="truncate text-sm font-bold text-foreground">
                          {getGuideCourseName(guide) || "-"}
                        </p>
                        <p className="truncate text-xs font-medium text-muted-foreground">
                          {getGuideCourseDistrictName(guide) || "-"}
                        </p>
                      </div>
                    </TableCell>
                    <TableCell className="w-[240px] align-middle">
                      <div className="flex max-w-[210px] flex-wrap items-center gap-1.5">
                        {guide.locations.length > 0 ? (
                          guide.locations.slice(0, 3).map((location) => {
                            const label = getItemLabel(location);

                            return (
                              <Badge
                                key={
                                  getItemUuid(location) ||
                                  getItemLabel(location)
                                }
                                variant="secondary"
                                title={label}
                                className="inline-flex h-6 max-w-[92px] items-center rounded-full bg-[var(--theme-primary)] px-2 text-[10px] font-bold leading-none text-white shadow-none hover:bg-[var(--theme-primary)]"
                              >
                                <span className="truncate">{label}</span>
                              </Badge>
                            );
                          })
                        ) : (
                          <span className="text-sm text-muted-foreground">
                            -
                          </span>
                        )}
                        {guide.locations.length > 3 && (
                          <Badge
                            variant="secondary"
                            className="inline-flex h-6 items-center rounded-full bg-[var(--theme-primary)] px-2 text-[10px] font-bold leading-none text-white shadow-none hover:bg-[var(--theme-primary)]"
                          >
                            +{guide.locations.length - 3}
                          </Badge>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="w-[340px] max-w-[340px] align-top">
                      <div className="min-w-0 space-y-2">
                        {getStatusBadge(guide.status, statusLabels)}
                        {guide.status.toLowerCase() === "rejected" &&
                          guide.reject_reason && (
                            <div
                              title={guide.reject_reason}
                              className="flex max-w-[300px] items-start gap-2 rounded-xl bg-red-50 px-3 py-2 text-red-700"
                            >
                              <XCircle className="mt-0.5 h-4 w-4 shrink-0 text-red-700" />
                              <p className="whitespace-normal break-words text-xs font-semibold leading-5">
                                {guide.reject_reason}
                              </p>
                            </div>
                          )}
                        {guide.status.toLowerCase() === "blocked" && (
                          <div className="flex max-w-[300px] items-start gap-2 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-amber-800">
                            <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600" />
                            <p className="whitespace-normal break-words text-xs font-medium leading-5">
                              This account has been temporarily blocked for 24
                              hours due to multiple failed login attempts. You
                              can approve the account to restore access
                              immediately.
                            </p>
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="w-[190px]">
                      {(() => {
                        const normalizedStatus = guide.status.toLowerCase();
                        const guideUuid = guide.uuid || String(guide.id);
                        const isUpdating = statusUpdatingUuid === guideUuid;
                        const isActive = normalizedStatus === "approved";
                        const isDeactivated = normalizedStatus === "rejected";

                        return (
                          <div
                            className="inline-flex h-7 overflow-hidden rounded bg-white text-[10px] font-bold shadow-sm"
                            role="group"
                            aria-label={`Set verification status for ${guide.name}`}
                          >
                            <button
                              type="button"
                              disabled={
                                !canApproveGuide(guide.status) || isUpdating
                              }
                              onClick={() =>
                                changeGuideStatus(guide, "approved")
                              }
                              className={`min-w-[54px] rounded-l border border-green-500 px-1.5 transition disabled:cursor-not-allowed disabled:opacity-60 ${
                                isActive
                                  ? "bg-green-600 text-white hover:bg-green-700"
                                  : "bg-white text-green-700 hover:bg-green-50"
                              }`}
                            >
                              Active
                            </button>
                            <button
                              type="button"
                              disabled={
                                !canRejectGuide(guide.status) || isUpdating
                              }
                              onClick={() => {
                                setRejectGuide(guide);
                                setRejectReason("");
                              }}
                              className={`-ml-px min-w-[68px] rounded-r border border-red-500 px-1.5 transition disabled:cursor-not-allowed disabled:opacity-60 ${
                                isDeactivated
                                  ? "bg-red-600 text-white hover:bg-red-700"
                                  : "bg-white text-red-700 hover:bg-red-50"
                              }`}
                            >
                              Deactivate
                            </button>
                          </div>
                        );
                      })()}
                    </TableCell>
                    <TableCell className="w-[160px] align-middle">
                      {(() => {
                        const trusted = isTrustedGuide(guide);
                        const guideUuid = guide.uuid || String(guide.id);

                        return (
                          <div
                            className="inline-flex h-7 overflow-hidden rounded bg-white text-[10px] font-bold shadow-sm"
                            role="group"
                            aria-label={`Set trusted status for ${guide.name}`}
                          >
                            <button
                              type="button"
                              disabled={trustedUpdatingUuid === guideUuid}
                              onClick={() => changeTrustedGuide(guide, false)}
                              className={`min-w-[50px] rounded-l border border-slate-600 px-1.5 transition disabled:cursor-not-allowed disabled:opacity-60 ${
                                trusted
                                  ? "bg-white text-slate-600 hover:bg-[var(--theme-highlight)]"
                                  : "bg-[var(--theme-surface-strong)] text-slate-600 hover:bg-[var(--theme-highlight)]"
                              }`}
                            >
                              Normal
                            </button>
                            <button
                              type="button"
                              disabled={trustedUpdatingUuid === guideUuid}
                              onClick={() => changeTrustedGuide(guide, true)}
                              className={`-ml-px min-w-[56px] rounded-r border border-[var(--theme-primary)] px-1.5 transition disabled:cursor-not-allowed disabled:opacity-60 ${
                                trusted
                                  ? "bg-gradient-to-r from-[var(--theme-secondary)] via-[var(--theme-primary)] to-[var(--theme-accent)] text-white hover:from-[var(--theme-primary)] hover:via-[var(--theme-secondary)] hover:to-[var(--theme-primary-dark)]"
                                  : "bg-white text-[var(--theme-primary-dark)] hover:bg-[var(--theme-highlight)]"
                              }`}
                            >
                              Trusted
                            </button>
                          </div>
                        );
                      })()}
                    </TableCell>
                    <TableCell className="w-[150px]">
                      <div className="flex justify-end gap-2">
                        <AdminActionButton
                          icon={Eye}
                          label={t("common.view")}
                          onClick={() => openDetails(guide)}
                        />
                        <AdminActionButton
                          icon={Pencil}
                          label={t("common.edit")}
                          onClick={() => openEdit(guide)}
                        />
                        <AdminActionButton
                          icon={Trash2}
                          label={t("common.delete")}
                          tone="danger"
                          onClick={() => setDeleteGuide(guide)}
                        />
                      </div>
                    </TableCell>
                  </TableRow>
                ))}

              {!isLoading && guides.length === 0 && (
                <TableRow>
                  <TableCell
                    colSpan={7}
                    className="h-28 text-center text-muted-foreground"
                  >
                    {t("admin.noGuidesFound")}
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>

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

      <Dialog
        open={isExportModalOpen}
        onOpenChange={(open) => {
          if (!open && !isExporting) {
            setIsExportModalOpen(false);
          } else if (open) {
            setIsExportModalOpen(true);
          }
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Export Guides</DialogTitle>
            <DialogDescription>
              Choose a file extension and guide status for the export.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-5">
            <div className="space-y-3">
              <Label className="text-sm font-bold">File Extension</Label>
              <div className="flex flex-wrap gap-2">
                {guideExportExtensions.map((extension) => {
                  const active = exportExtension === extension;
                  const Icon =
                    extension === "xlsx" ? FileSpreadsheet : FileText;
                  const colorClass =
                    extension === "pdf"
                      ? active
                        ? "bg-red-600 text-white hover:bg-red-700 hover:text-white"
                        : "border-red-200 bg-red-50 text-red-700 hover:bg-red-100 hover:text-red-700"
                      : extension === "xlsx"
                        ? active
                          ? "bg-green-600 text-white hover:bg-green-700 hover:text-white"
                          : "border-green-200 bg-green-50 text-green-700 hover:bg-green-100 hover:text-green-700"
                        : active
                          ? "bg-yellow-500 text-white hover:bg-yellow-600 hover:text-white"
                          : "border-yellow-200 bg-yellow-50 text-yellow-700 hover:bg-yellow-100 hover:text-yellow-700";

                  return (
                    <Button
                      key={extension}
                      type="button"
                      variant="outline"
                      disabled={isExporting}
                      className={`h-9 rounded-lg px-3 text-xs font-black uppercase ${colorClass}`}
                      onClick={() => setExportExtension(extension)}
                    >
                      <Icon className="h-3.5 w-3.5" />
                      {extension}
                    </Button>
                  );
                })}
              </div>
            </div>

            <div className="space-y-3">
              <Label className="text-sm font-bold">Guide Profile Status</Label>
              <div className="flex flex-wrap gap-2">
                {guideExportStatuses.map((status) => {
                  const active = exportStatus === status;
                  const label =
                    status === "all"
                      ? t("admin.all")
                      : statusLabels[status] || status;
                  const StatusIcon =
                    status === "approved"
                      ? CheckCircle
                      : status === "rejected"
                        ? XCircle
                        : status === "blocked"
                          ? AlertTriangle
                          : status === "pending"
                            ? Clock
                            : BookOpen;
                  const colorClass =
                    status === "approved"
                      ? active
                        ? "bg-green-600 text-white hover:bg-green-700 hover:text-white"
                        : "border-green-200 bg-green-50 text-green-700 hover:bg-green-100 hover:text-green-700"
                      : status === "rejected"
                        ? active
                          ? "bg-red-600 text-white hover:bg-red-700 hover:text-white"
                          : "border-red-200 bg-red-50 text-red-700 hover:bg-red-100 hover:text-red-700"
                        : status === "blocked"
                          ? active
                            ? "bg-amber-600 text-white hover:bg-amber-700 hover:text-white"
                            : "border-amber-200 bg-amber-50 text-amber-700 hover:bg-amber-100 hover:text-amber-700"
                          : status === "pending"
                            ? active
                              ? "bg-yellow-500 text-white hover:bg-yellow-600 hover:text-white"
                              : "border-yellow-200 bg-yellow-50 text-yellow-700 hover:bg-yellow-100 hover:text-yellow-700"
                            : active
                              ? "bg-slate-700 text-white hover:bg-slate-800 hover:text-white"
                              : "border-slate-200 bg-slate-50 text-slate-700 hover:bg-slate-100 hover:text-slate-700";

                  return (
                    <Button
                      key={status}
                      type="button"
                      variant="outline"
                      disabled={isExporting}
                      className={`h-9 rounded-lg px-3 text-xs font-black capitalize ${colorClass}`}
                      onClick={() => setExportStatus(status)}
                    >
                      <StatusIcon className="h-3.5 w-3.5" />
                      {label}
                    </Button>
                  );
                })}
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => setIsExportModalOpen(false)}
              disabled={isExporting}
              className="hover:border-slate-300 hover:text-foreground"
            >
              Cancel
            </Button>
            <Button
              type="button"
              disabled={isExporting}
              className="bg-[var(--theme-primary)] font-bold text-white hover:bg-[var(--theme-primary)]/90 hover:text-white"
              onClick={() => exportGuides(exportStatus, exportExtension)}
            >
              <Download className="h-4 w-4" />
              {isExporting ? "Exporting..." : "Export"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={isImportModalOpen}
        onOpenChange={(open) => {
          if (open) {
            setIsImportModalOpen(true);
          } else {
            closeImportModal();
          }
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Import Guides</DialogTitle>
            <DialogDescription>
              Download an empty dummy file, fill guide records, then upload the
              completed CSV or XLSX file.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-5">
            <div className="rounded-2xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] p-4">
              <Label className="text-sm font-bold">Download Dummy File</Label>
              <div className="mt-3 flex flex-wrap gap-2">
                <Button
                  type="button"
                  variant="outline"
                  className="h-9 rounded-lg border-green-200 bg-green-50 px-3 text-xs font-black text-green-700 hover:bg-green-100 hover:text-green-700"
                  onClick={downloadXlsxTemplate}
                >
                  <FileSpreadsheet className="h-3.5 w-3.5" />
                  XLSX
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  className="h-9 rounded-lg border-yellow-200 bg-yellow-50 px-3 text-xs font-black text-yellow-700 hover:bg-yellow-100 hover:text-yellow-700"
                  onClick={downloadCsvTemplate}
                >
                  <FileText className="h-3.5 w-3.5" />
                  CSV
                </Button>
              </div>
            </div>

            <div className="rounded-2xl border border-dashed border-[var(--theme-border)] bg-white p-4">
              <Label htmlFor="guide-import-file" className="text-sm font-bold">
                Upload File
              </Label>
              <Input
                id="guide-import-file"
                ref={importInputRef}
                type="file"
                accept=".csv,.xls,.xlsx"
                disabled={isImporting}
                className="mt-3 h-11 rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                onChange={(event) => {
                  setSelectedImportFile(event.target.files?.[0] || null);
                }}
              />
              {selectedImportFile && (
                <p className="mt-2 text-xs font-semibold text-muted-foreground">
                  Selected: {selectedImportFile.name}
                </p>
              )}
            </div>
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={closeImportModal}
              disabled={isImporting}
            >
              Cancel
            </Button>
            <Button
              type="button"
              disabled={!selectedImportFile || isImporting}
              className="bg-[var(--theme-primary)] font-bold text-white hover:bg-[var(--theme-primary)]/90"
              onClick={() => {
                if (selectedImportFile) {
                  importGuides(selectedImportFile);
                }
              }}
            >
              <Upload className="h-4 w-4" />
              {isImporting ? "Uploading..." : "Upload"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={Boolean(editGuide)}
        onOpenChange={(open) => {
          if (!open) closeEdit();
        }}
      >
        <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-4xl">
          <DialogHeader>
            <DialogTitle>{t("admin.editGuide")}</DialogTitle>
            <DialogDescription>
              {t("admin.editGuideDescription")}
            </DialogDescription>
          </DialogHeader>

          {isOptionsLoading ? (
            <div className="rounded-2xl border border-[var(--theme-border-soft)] p-6 text-center text-sm text-muted-foreground">
              Loading guide options...
            </div>
          ) : (
            <div className="space-y-6">
              <div className="grid gap-4 md:grid-cols-2">
                <EditField
                  id="guide-edit-name"
                  label="Full Name"
                  value={editForm.name}
                  onChange={(value) => setEditField("name", value)}
                  error={firstError(editErrors, "name")}
                />
                <EditField
                  id="guide-edit-name-hi"
                  label="Full Name in Hindi"
                  value={editForm.name_hi}
                  onChange={(value) => setEditField("name_hi", value)}
                  error={firstError(editErrors, "name_hi")}
                />
                <EditField
                  id="guide-edit-email"
                  label="Email"
                  type="email"
                  value={editForm.email}
                  onChange={(value) => setEditField("email", value)}
                  error={firstError(editErrors, "email")}
                />
                <EditField
                  id="guide-edit-phone"
                  label="Phone"
                  value={editForm.phone}
                  onChange={(value) => setEditField("phone", value)}
                  error={firstError(editErrors, "phone")}
                />
                <EditField
                  id="guide-edit-alternate-phone"
                  label="Alternate Phone"
                  value={editForm.alternate_phone}
                  onChange={(value) => setEditField("alternate_phone", value)}
                  error={firstError(editErrors, "alternate_phone")}
                />
                <EditField
                  id="guide-edit-experience"
                  label="Experience (Years)"
                  type="number"
                  value={editForm.year_of_experience}
                  onChange={(value) =>
                    setEditField("year_of_experience", value)
                  }
                  error={firstError(editErrors, "year_of_experience")}
                />
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <EditTextarea
                  id="guide-edit-address"
                  label="Address"
                  value={editForm.address}
                  onChange={(value) => setEditField("address", value)}
                  error={firstError(editErrors, "address")}
                />
                <EditTextarea
                  id="guide-edit-address-hi"
                  label="Address in Hindi"
                  value={editForm.address_hi}
                  onChange={(value) => setEditField("address_hi", value)}
                  error={firstError(editErrors, "address_hi")}
                />
                <EditTextarea
                  id="guide-edit-bio"
                  label="Professional Bio"
                  value={editForm.bio}
                  onChange={(value) => setEditField("bio", value)}
                  error={firstError(editErrors, "bio")}
                  rows={4}
                />
                <EditTextarea
                  id="guide-edit-bio-hi"
                  label="Professional Bio in Hindi"
                  value={editForm.bio_hi}
                  onChange={(value) => setEditField("bio_hi", value)}
                  error={firstError(editErrors, "bio_hi")}
                  rows={4}
                />
              </div>

              <div className="grid gap-4 lg:grid-cols-3">
                <MultiSelectField
                  label="Spoken Languages"
                  options={guideOptions.languages}
                  selected={editForm.language_uuids}
                  onToggle={(uuid) =>
                    toggleEditSelection("language_uuids", uuid)
                  }
                  error={
                    firstError(editErrors, "language_uuids") ||
                    firstError(editErrors, "language_uuids.0")
                  }
                />
                <MultiSelectField
                  label="Areas of Expertise"
                  options={guideOptions.skills}
                  selected={editForm.skill_uuids}
                  onToggle={(uuid) => toggleEditSelection("skill_uuids", uuid)}
                  error={
                    firstError(editErrors, "skill_uuids") ||
                    firstError(editErrors, "skill_uuids.0")
                  }
                />
                <MultiSelectField
                  label="Areas of Operation"
                  options={guideOptions.locations}
                  selected={editForm.location_uuids}
                  onToggle={(uuid) =>
                    toggleEditSelection("location_uuids", uuid)
                  }
                  error={
                    firstError(editErrors, "location_uuids") ||
                    firstError(editErrors, "location_uuids.0")
                  }
                />
              </div>
            </div>
          )}

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={closeEdit}
              disabled={isGuideSaving}
            >
              Cancel
            </Button>
            <Button
              type="button"
              onClick={saveGuide}
              disabled={isGuideSaving || isOptionsLoading}
              className="bg-[var(--theme-primary)] hover:bg-[var(--theme-accent-dark)]"
            >
              {isGuideSaving ? "Saving..." : "Save Guide"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={Boolean(rejectGuide)}
        onOpenChange={(open) => {
          if (!open) {
            setRejectGuide(null);
            setRejectReason("");
          }
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Deactivate Guide</DialogTitle>
            <DialogDescription>
              Please provide the reason for deactivating this guide.
            </DialogDescription>
          </DialogHeader>
          <Textarea
            placeholder="Enter deactivate reason."
            value={rejectReason}
            onChange={(event) => setRejectReason(event.target.value)}
            rows={4}
          />
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setRejectGuide(null);
                setRejectReason("");
              }}
            >
              Cancel
            </Button>
            <Button
              type="button"
              variant="destructive"
              disabled={
                !rejectGuide ||
                !rejectReason.trim() ||
                statusUpdatingUuid ===
                  (rejectGuide.uuid || String(rejectGuide.id))
              }
              onClick={() => {
                if (!rejectGuide) return;
                changeGuideStatus(rejectGuide, "rejected", rejectReason.trim());
              }}
            >
              Reject
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={Boolean(deleteGuide)}
        onOpenChange={(open) => {
          if (!open) {
            setDeleteGuide(null);
          }
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("common.delete")}</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete this guide?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => setDeleteGuide(null)}
              disabled={Boolean(
                deleteGuide &&
                statusUpdatingUuid ===
                  (deleteGuide.uuid || String(deleteGuide.id)),
              )}
            >
              Cancel
            </Button>
            <Button
              type="button"
              variant="destructive"
              disabled={Boolean(
                deleteGuide &&
                statusUpdatingUuid ===
                  (deleteGuide.uuid || String(deleteGuide.id)),
              )}
              onClick={deleteSelectedGuide}
            >
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
