"use client";

import {
  useCallback,
  useEffect,
  useMemo,
  useState,
  type FormEvent,
  type ReactNode,
} from "react";
import { toast } from "react-toastify";
import {
  CheckCircle,
  Eye,
  GraduationCap,
  Loader2,
  Pencil,
  Plus,
  Trash2,
  X,
  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";

type Status = "active" | "inactive";
type ApiResponse<T> = {
  statusCode?: number;
  success?: boolean;
  data?: T;
  message?: string;
  message_hi?: string;
};
type Actor = { name?: string | null; email?: string | null } | string | null;
type Location = {
  id?: string | number;
  uuid?: string | null;
  title?: string | null;
  title_hi?: string | null;
  name?: string | null;
  name_hi?: string | null;
  status?: string | boolean | number | null;
  is_active?: boolean | number | null;
};
type Course = {
  id?: string | number;
  uuid?: string | null;
  title?: string | null;
  title_hi?: string | null;
  description?: string | null;
  description_hi?: string | null;
  course_location?: string | null;
  course_location_hi?: string | null;
  status?: string | boolean | number | null;
  district_uuids?: string[] | null;
  districts?: Location[] | null;
  locations?: Location[] | null;
  created_by?: Actor;
  updated_by?: Actor;
};
type Pagination = {
  current_page: number;
  data: Course[];
  from: number | null;
  last_page?: number;
  per_page: number;
  to: number | null;
  total: number;
};
type Errors = Record<string, string[]>;
type FormState = {
  title: string;
  title_hi: string;
  description: string;
  description_hi: string;
  course_location: string;
  course_location_hi: string;
  status: Status;
  district_uuids: string[];
};

const emptyPagination: Pagination = {
  current_page: 1,
  data: [],
  from: null,
  last_page: 1,
  per_page: 10,
  to: null,
  total: 0,
};
const initialForm: FormState = {
  title: "",
  title_hi: "",
  description: "",
  description_hi: "",
  course_location: "",
  course_location_hi: "",
  status: "active",
  district_uuids: [],
};
const inputClass = "h-11 rounded-2xl border-[var(--theme-border-soft)]";
const selectClass =
  "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";

function getAdminToken() {
  const token = localStorage.getItem("auth_token");
  if (!token) throw new Error("Admin token missing. Please login again.");
  return token;
}
function statusOf(value?: Course["status"]): Status {
  if (typeof value === "boolean") return value ? "active" : "inactive";
  if (typeof value === "number") return value === 1 ? "active" : "inactive";
  return String(value || "active").toLowerCase() === "inactive"
    ? "inactive"
    : "active";
}
function titleOf(course: Course) {
  return course.title || "Untitled Course";
}
function locTitle(loc: Location) {
  return loc.title || loc.name || String(loc.id || "District");
}
function locUuid(loc: Location) {
  return String(loc.uuid || "");
}
function actorLabel(actor?: Actor) {
  return !actor
    ? "-"
    : typeof actor === "string"
      ? actor
      : actor.name || actor.email || "-";
}
function isActiveLoc(loc: Location) {
  return typeof loc.is_active === "boolean"
    ? loc.is_active
    : typeof loc.is_active === "number"
      ? loc.is_active === 1
      : statusOf(loc.status) === "active";
}
function required(label: string) {
  return [`${label} is required.`];
}
function maxLength(label: string, max: number) {
  return [`${label} must not be greater than ${max} characters.`];
}
function isUuid(value: string) {
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
    value,
  );
}
function fieldError(errors: Errors, field: keyof FormState) {
  return errors[field]?.[0] || "";
}
function RequiredMark() {
  return <span className="text-[var(--theme-accent)]">*</span>;
}
function pageCount(pagination: Pagination) {
  return (
    pagination.last_page ||
    Math.max(1, Math.ceil(pagination.total / pagination.per_page))
  );
}

function parsePagination(data: unknown): Pagination {
  if (!data || typeof data !== "object") return emptyPagination;
  const record = data as Record<string, unknown>;
  const value = record.courses || data;
  if (Array.isArray(value))
    return {
      ...emptyPagination,
      data: value as Course[],
      from: value.length ? 1 : null,
      to: value.length || null,
      total: value.length,
    };
  if (value && typeof value === "object" && "data" in value)
    return value as Pagination;
  return emptyPagination;
}
function parseCourse(data: unknown) {
  if (!data || typeof data !== "object") return null;
  const record = data as Record<string, unknown>;
  return (record.course as Course | undefined) || (data as Course);
}
function parseLocations(data: unknown) {
  if (!data || typeof data !== "object") return [];
  const record = data as Record<string, unknown>;
  const value = record.districts || record.locations || data;
  if (Array.isArray(value)) return value as Location[];
  if (value && typeof value === "object" && "data" in value)
    return ((value as { data?: Location[] }).data || []) as Location[];
  return [];
}
function courseDistrictUuids(course: Course) {
  if (Array.isArray(course.district_uuids))
    return course.district_uuids.map(String);
  return [...(course.districts || []), ...(course.locations || [])]
    .map(locUuid)
    .filter(Boolean);
}
function courseLocations(course: Course, options: Location[]) {
  const attached = [...(course.districts || []), ...(course.locations || [])];
  if (attached.length) return attached;
  const selected = new Set(courseDistrictUuids(course));
  return options.filter((loc) => selected.has(locUuid(loc)));
}
function courseToForm(course: Course): FormState {
  return {
    title: course.title || "",
    title_hi: course.title_hi || "",
    description: course.description || "",
    description_hi: course.description_hi || "",
    course_location: course.course_location || "",
    course_location_hi: course.course_location_hi || "",
    status: statusOf(course.status),
    district_uuids: courseDistrictUuids(course),
  };
}
function validate(form: FormState, districtOptions: Location[]) {
  const errors: Errors = {};

  const title = form.title.trim();
  const titleHi = form.title_hi.trim();
  const courseLocation = form.course_location.trim();
  const courseLocationHi = form.course_location_hi.trim();
  const districtUuids = form.district_uuids.map((uuid) => uuid.trim());
  const validDistrictUuids = new Set(
    districtOptions.map(locUuid).filter((uuid) => isUuid(uuid)),
  );

  if (!title) errors.title = required("Title");
  else if (title.length > 255) errors.title = maxLength("Title", 255);

  if (titleHi.length > 255)
    errors.title_hi = maxLength("Title Hindi", 255);

  if (courseLocation.length > 255)
    errors.course_location = maxLength("Course Location", 255);

  if (courseLocationHi.length > 255)
    errors.course_location_hi = maxLength("Course Location Hindi", 255);

  if (form.status && !["active", "inactive"].includes(form.status))
    errors.status = ["Status must be active or inactive."];

  if (!Array.isArray(form.district_uuids)) {
    errors.district_uuids = ["Districts must be an array."];
  } else if (districtUuids.length === 0) {
    errors.district_uuids = ["Please choose at least one district."];
  } else if (districtUuids.some((uuid) => !uuid)) {
    errors.district_uuids = ["Each selected district is required."];
  } else if (districtUuids.some((uuid) => !isUuid(uuid))) {
    errors.district_uuids = ["Each selected district must be a valid UUID."];
  } else if (new Set(districtUuids).size !== districtUuids.length) {
    errors.district_uuids = ["Districts must not contain duplicate values."];
  } else if (
    validDistrictUuids.size > 0 &&
    districtUuids.some((uuid) => !validDistrictUuids.has(uuid))
  ) {
    errors.district_uuids = ["Each selected district must exist."];
  }

  return errors;
}
function payload(form: FormState) {
  return {
    title: form.title.trim(),
    title_hi: form.title_hi.trim(),
    description: form.description.trim(),
    description_hi: form.description_hi.trim(),
    course_location: form.course_location.trim(),
    course_location_hi: form.course_location_hi.trim(),
    status: form.status,
    district_uuids: form.district_uuids,
  };
}
function StatusBadge({ status }: { status: Status }) {
  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"}`}
    >
      {status}
    </Badge>
  );
}
function LocationChips({ locations }: { locations: Location[] }) {
  if (!locations.length)
    return <span className="text-sm text-muted-foreground">-</span>;
  return (
    <div className="flex flex-wrap gap-1.5">
      {locations.map((loc) => (
        <Badge
          key={locUuid(loc) || locTitle(loc)}
          variant="outline"
          className="rounded-full border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] px-2.5 py-1 font-semibold text-[var(--theme-primary)]"
        >
          {locTitle(loc)}
        </Badge>
      ))}
    </div>
  );
}
function DetailItem({ label, value }: { label: string; value?: ReactNode }) {
  return (
    <div className="grid gap-3 border-b border-[var(--theme-border-soft)] py-4 md:grid-cols-[180px_1fr]">
      <p className="text-sm font-black">{label}</p>
      <div className="whitespace-pre-wrap text-sm leading-7 text-[#1f1711]">
        {value || "-"}
      </div>
    </div>
  );
}

export default function AdminCoursesPage() {
  const [courses, setCourses] = useState<Course[]>([]);
  const [pagination, setPagination] = useState<Pagination>(emptyPagination);
  const [locations, setLocations] = useState<Location[]>([]);
  const [search, setSearch] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [isLocationsLoading, setIsLocationsLoading] = useState(true);
  const [error, setError] = useState("");
  const [statusUpdatingUuid, setStatusUpdatingUuid] = useState<string | null>(
    null,
  );
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingCourse, setEditingCourse] = useState<Course | null>(null);
  const [form, setForm] = useState<FormState>(initialForm);
  const [formErrors, setFormErrors] = useState<Errors>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [viewCourse, setViewCourse] = useState<Course | null>(null);
  const [isViewOpen, setIsViewOpen] = useState(false);
  const [isFetchingDetail, setIsFetchingDetail] = useState(false);
  const [deleteCourse, setDeleteCourse] = useState<Course | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  const fetchCourses = useCallback(async (page = 1) => {
    setIsLoading(true);
    setError("");
    try {
      const token = getAdminToken();
      const response = await apiRequest(apiUrl(`/admin/courses?page=${page}`), {
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: "application/json",
        },
      });
      const result = (await response.json()) as ApiResponse<unknown>;
      if (!response.ok || result.success === false)
        throw new Error(
          getLocalizedApiMessage(result, "Failed to load courses."),
        );
      const nextPagination = parsePagination(result.data);
      setPagination(nextPagination);
      setCourses(nextPagination.data || []);
    } catch (fetchError) {
      const message =
        fetchError instanceof Error
          ? fetchError.message
          : "Failed to load courses.";
      setError(message);
      setPagination(emptyPagination);
      setCourses([]);
      toast.error(message);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const fetchLocations = useCallback(async () => {
    setIsLocationsLoading(true);
    try {
      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl("/masters/districts?per_page=1000"),
        {
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
          },
        },
      );
      const result = (await response.json()) as ApiResponse<unknown>;
      if (!response.ok || result.success === false)
        throw new Error(
          getLocalizedApiMessage(result, "Failed to load districts."),
        );
      setLocations(
        parseLocations(result.data).filter(
          (loc) => isUuid(locUuid(loc)) && isActiveLoc(loc),
        ),
      );
    } catch (locationError) {
      toast.error(
        locationError instanceof Error
          ? locationError.message
          : "Failed to load districts.",
      );
      setLocations([]);
    } finally {
      setIsLocationsLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchCourses();
    fetchLocations();
  }, [fetchCourses, fetchLocations]);

  const filteredCourses = useMemo(() => {
    const query = search.trim().toLowerCase();
    if (!query) return courses;
    return courses.filter((course) =>
      [
        course.title,
        course.title_hi,
        course.description,
        course.description_hi,
        course.course_location,
        course.course_location_hi,
        courseLocations(course, locations).map(locTitle).join(" "),
      ]
        .filter(Boolean)
        .join(" ")
        .toLowerCase()
        .includes(query),
    );
  }, [courses, locations, search]);

  const activeCount = courses.filter(
    (course) => statusOf(course.status) === "active",
  ).length;
  const inactiveCount = courses.filter(
    (course) => statusOf(course.status) === "inactive",
  ).length;
  const selectedLocations = locations.filter((loc) =>
    form.district_uuids.includes(locUuid(loc)),
  );

  const clearFieldError = (field: keyof FormState) => {
    setFormErrors((currentErrors) => {
      if (!currentErrors[field]) return currentErrors;
      const nextErrors = { ...currentErrors };
      delete nextErrors[field];
      return nextErrors;
    });
  };
  const updateFormField = <K extends keyof FormState>(
    field: K,
    value: FormState[K],
  ) => {
    setForm((currentForm) => ({ ...currentForm, [field]: value }));
    clearFieldError(field);
  };
  const toggleDistrict = (uuid: string) => {
    setForm((currentForm) => ({
      ...currentForm,
      district_uuids: currentForm.district_uuids.includes(uuid)
        ? currentForm.district_uuids.filter((item) => item !== uuid)
        : [...currentForm.district_uuids, uuid],
    }));
    clearFieldError("district_uuids");
  };

  const openAddDialog = () => {
    setEditingCourse(null);
    setForm(initialForm);
    setFormErrors({});
    setIsFormOpen(true);
  };
  const openEditDialog = (course: Course) => {
    if (!course.uuid) return toast.error("Course uuid is missing.");
    setEditingCourse(course);
    setForm(courseToForm(course));
    setFormErrors({});
    setIsFormOpen(true);
  };
  const closeFormDialog = () => {
    setIsFormOpen(false);
    setEditingCourse(null);
    setForm(initialForm);
    setFormErrors({});
  };
  const handleFormOpenChange = (open: boolean) => {
    if (open) setIsFormOpen(true);
    else closeFormDialog();
  };

  const openViewDialog = async (course: Course) => {
    if (!course.uuid) return toast.error("Course uuid is missing.");
    setViewCourse(course);
    setIsViewOpen(true);
    setIsFetchingDetail(true);
    try {
      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl(`/admin/courses/${course.uuid}`),
        {
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
          },
        },
      );
      const result = (await response.json()) as ApiResponse<unknown>;
      if (!response.ok || result.success === false)
        throw new Error(
          getLocalizedApiMessage(result, "Failed to load course."),
        );
      setViewCourse(parseCourse(result.data) || course);
    } catch (detailError) {
      toast.error(
        detailError instanceof Error
          ? detailError.message
          : "Failed to load course.",
      );
      setIsViewOpen(false);
      setViewCourse(null);
    } finally {
      setIsFetchingDetail(false);
    }
  };

  const submitCourse = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setFormErrors({});
    const validationErrors = validate(form, locations);
    if (Object.keys(validationErrors).length) {
      setFormErrors(validationErrors);
      toast.error("Please fix validation errors.");
      return;
    }
    setIsSubmitting(true);
    try {
      const token = getAdminToken();
      const isEditing = Boolean(editingCourse?.uuid);
      const response = await apiRequest(
        apiUrl(
          isEditing
            ? `/admin/courses/${editingCourse?.uuid}`
            : "/admin/courses",
        ),
        {
          method: isEditing ? "PUT" : "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload(form)),
        },
      );
      const result = (await response.json()) as ApiResponse<unknown>;
      if (
        response.status === 422 &&
        result.data &&
        typeof result.data === "object"
      ) {
        setFormErrors(result.data as Errors);
        throw new Error(getLocalizedApiMessage(result, "Validation failed."));
      }
      if (!response.ok || result.success === false)
        throw new Error(
          getLocalizedApiMessage(
            result,
            `Failed to ${isEditing ? "update" : "create"} course.`,
          ),
        );
      toast.success(
        getLocalizedApiMessage(
          result,
          `Course ${isEditing ? "updated" : "created"} successfully.`,
        ),
      );
      closeFormDialog();
      fetchCourses(pagination.current_page);
    } catch (submitError) {
      toast.error(
        submitError instanceof Error
          ? submitError.message
          : `Failed to ${editingCourse?.uuid ? "update" : "create"} course.`,
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  const changeStatus = async (course: Course) => {
    if (!course.uuid) return toast.error("Course uuid is missing.");
    const nextStatus =
      statusOf(course.status) === "active" ? "inactive" : "active";
    setStatusUpdatingUuid(course.uuid);
    try {
      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl(`/admin/courses/${course.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."),
      );
      fetchCourses(pagination.current_page);
    } catch (statusError) {
      toast.error(
        statusError instanceof Error
          ? statusError.message
          : "Failed to change status.",
      );
    } finally {
      setStatusUpdatingUuid(null);
    }
  };

  const handleDelete = async () => {
    if (!deleteCourse?.uuid) return toast.error("Course uuid is missing.");
    setIsDeleting(true);
    try {
      const token = getAdminToken();
      const response = await apiRequest(
        apiUrl(`/admin/courses/${deleteCourse.uuid}`),
        {
          method: "DELETE",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
          },
        },
      );
      const result = (await response.json()) as ApiResponse<unknown>;
      if (!response.ok || result.success === false)
        throw new Error(
          getLocalizedApiMessage(result, "Failed to delete course."),
        );
      toast.success(
        getLocalizedApiMessage(result, "Course deleted successfully."),
      );
      setDeleteCourse(null);
      fetchCourses(pagination.current_page);
    } catch (deleteError) {
      toast.error(
        deleteError instanceof Error
          ? deleteError.message
          : "Failed to delete course.",
      );
    } finally {
      setIsDeleting(false);
    }
  };

  return (
    <div className="space-y-6">
      <AdminBreadcrumb
        current="Courses"
        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: "Total",
              count: pagination.total,
              icon: <GraduationCap className="h-4 w-4" />,
            },
            {
              label: "Active",
              count: activeCount,
              icon: <CheckCircle className="h-4 w-4" />,
              tone: "success",
            },
            {
              label: "Inactive",
              count: inactiveCount,
              icon: <XCircle className="h-4 w-4" />,
              tone: "danger",
            },
          ]}
          searchValue={search}
          searchPlaceholder="Search courses"
          onSearchChange={setSearch}
          onSearchClear={() => setSearch("")}
        >
          <Button
            type="button"
            className="h-11 rounded-2xl px-4 text-sm font-bold"
            onClick={openAddDialog}
          >
            <Plus className="h-4 w-4" />
            Add Course
          </Button>
        </AdminTableToolbar>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="min-w-[220px]">Course</TableHead>
                <TableHead className="min-w-[180px]">Course Location</TableHead>
                <TableHead className="min-w-[260px]">Districts</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Created By</TableHead>
                <TableHead>Updated By</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableRow>
                  <TableCell colSpan={7}>
                    <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)]" />
                      Loading courses...
                    </div>
                  </TableCell>
                </TableRow>
              ) : filteredCourses.length ? (
                filteredCourses.map((course) => {
                  const status = statusOf(course.status);
                  const districts = courseLocations(course, locations);
                  return (
                    <TableRow key={course.uuid || course.id}>
                      <TableCell>
                        <p className="font-semibold">{titleOf(course)}</p>
                        <p className="mt-1 line-clamp-2 text-xs text-muted-foreground">
                          {course.description || "-"}
                        </p>
                      </TableCell>
                      <TableCell>
                        <p className="font-semibold">
                          {course.course_location || "-"}
                        </p>
                        {course.course_location_hi && (
                          <p className="mt-1 text-xs text-muted-foreground">
                            {course.course_location_hi}
                          </p>
                        )}
                      </TableCell>
                      <TableCell>
                        <LocationChips locations={districts.slice(0, 3)} />
                        {districts.length > 3 && (
                          <Badge className="mt-1 rounded-full bg-[var(--theme-border-soft)] px-2 py-0.5 text-xs font-bold text-slate-700 shadow-none">
                            +{districts.length - 3}
                          </Badge>
                        )}
                      </TableCell>
                      <TableCell>
                        <StatusBadge status={status} />
                      </TableCell>
                      <TableCell>{actorLabel(course.created_by)}</TableCell>
                      <TableCell>{actorLabel(course.updated_by)}</TableCell>
                      <TableCell>
                        <div className="flex justify-end gap-2">
                          <button
                            type="button"
                            aria-label={`Change ${titleOf(course)} 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 === course.uuid}
                            onClick={() => changeStatus(course)}
                          >
                            <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(course)}
                          >
                            <Eye className="h-4 w-4" />
                            <span className="sr-only">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(course)}
                          >
                            <Pencil className="h-4 w-4" />
                            <span className="sr-only">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={() => setDeleteCourse(course)}
                          >
                            <Trash2 className="h-4 w-4" />
                            <span className="sr-only">Delete</span>
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  );
                })
              ) : (
                <TableRow>
                  <TableCell colSpan={7}>
                    <div className="py-8 text-center text-sm font-medium text-muted-foreground">
                      {error || "No courses found."}
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
          <AdminTablePagination
            total={pagination.total}
            pageSize={pagination.per_page}
            currentPage={pagination.current_page}
            totalPages={pageCount(pagination)}
            from={pagination.from}
            to={pagination.to}
            isLoading={isLoading}
            onPageChange={fetchCourses}
          />
        </CardContent>
      </Card>

      <Dialog open={isFormOpen} onOpenChange={handleFormOpenChange}>
        <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 lg:max-w-5xl">
          <form noValidate onSubmit={submitCourse}>
            <DialogHeader className="border-b border-[var(--theme-border-soft)] bg-white px-6 py-5">
              <DialogTitle className="text-xl font-black text-[#1f1711]">
                {editingCourse ? "Edit Course" : "Add Course"}
              </DialogTitle>
              <DialogDescription>
                {editingCourse
                  ? "Update course details and assigned districts."
                  : "Create a course and assign it to districts."}
              </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">
                  Title <RequiredMark />
                </Label>
                <Input
                  id="title"
                  value={form.title}
                  onChange={(event) =>
                    updateFormField("title", event.target.value)
                  }
                  placeholder="Enter title"
                  maxLength={255}
                  className={inputClass}
                  aria-invalid={Boolean(fieldError(formErrors, "title"))}
                />
                {fieldError(formErrors, "title") && (
                  <p className="text-xs font-medium text-red-600">
                    {fieldError(formErrors, "title")}
                  </p>
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="title_hi">Title Hindi</Label>
                <Input
                  id="title_hi"
                  value={form.title_hi}
                  onChange={(event) =>
                    updateFormField("title_hi", event.target.value)
                  }
                  placeholder="Hindi title"
                  maxLength={255}
                  className={inputClass}
                  aria-invalid={Boolean(fieldError(formErrors, "title_hi"))}
                />
                {fieldError(formErrors, "title_hi") && (
                  <p className="text-xs font-medium text-red-600">
                    {fieldError(formErrors, "title_hi")}
                  </p>
                )}
              </div>
              <div className="space-y-2 md:col-span-2">
                <Label htmlFor="description">Description</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(fieldError(formErrors, "description"))}
                />
                {fieldError(formErrors, "description") && (
                  <p className="text-xs font-medium text-red-600">
                    {fieldError(formErrors, "description")}
                  </p>
                )}
              </div>
              <div className="space-y-2 md:col-span-2">
                <Label htmlFor="description_hi">Description Hindi</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(
                    fieldError(formErrors, "description_hi"),
                  )}
                />
                {fieldError(formErrors, "description_hi") && (
                  <p className="text-xs font-medium text-red-600">
                    {fieldError(formErrors, "description_hi")}
                  </p>
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="course_location">Course Location</Label>
                <Input
                  id="course_location"
                  value={form.course_location}
                  onChange={(event) =>
                    updateFormField("course_location", event.target.value)
                  }
                  placeholder="Dehradun"
                  maxLength={255}
                  className={inputClass}
                  aria-invalid={Boolean(
                    fieldError(formErrors, "course_location"),
                  )}
                />
                {fieldError(formErrors, "course_location") && (
                  <p className="text-xs font-medium text-red-600">
                    {fieldError(formErrors, "course_location")}
                  </p>
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="course_location_hi">
                  Course Location Hindi
                </Label>
                <Input
                  id="course_location_hi"
                  value={form.course_location_hi}
                  onChange={(event) =>
                    updateFormField("course_location_hi", event.target.value)
                  }
                  placeholder="Hindi location"
                  maxLength={255}
                  className={inputClass}
                  aria-invalid={Boolean(
                    fieldError(formErrors, "course_location_hi"),
                  )}
                />
                {fieldError(formErrors, "course_location_hi") && (
                  <p className="text-xs font-medium text-red-600">
                    {fieldError(formErrors, "course_location_hi")}
                  </p>
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="status">Status</Label>
                <select
                  id="status"
                  value={form.status}
                  onChange={(event) =>
                    updateFormField("status", event.target.value as Status)
                  }
                  className={selectClass}
                  aria-invalid={Boolean(fieldError(formErrors, "status"))}
                >
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                </select>
                {fieldError(formErrors, "status") && (
                  <p className="text-xs font-medium text-red-600">
                    {fieldError(formErrors, "status")}
                  </p>
                )}
              </div>
              <div className="space-y-2 md:col-span-2">
                <Label>Districts <RequiredMark /></Label>
                <div
                  className={`rounded-2xl border p-4 ${fieldError(formErrors, "district_uuids") ? "border-red-200 bg-red-50/30" : "border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"}`}
                >
                  {selectedLocations.length > 0 && (
                    <div className="mb-3 flex flex-wrap gap-2">
                      {selectedLocations.map((loc) => (
                        <button
                          key={locUuid(loc)}
                          type="button"
                          className="inline-flex items-center gap-1.5 rounded-full bg-[var(--theme-primary)] px-3 py-1.5 text-xs font-black text-white"
                          onClick={() => toggleDistrict(locUuid(loc))}
                        >
                          {locTitle(loc)}
                          <X className="h-3.5 w-3.5" />
                        </button>
                      ))}
                    </div>
                  )}
                  <div className="flex flex-wrap gap-2">
                    {isLocationsLoading ? (
                      <div className="flex items-center gap-2 py-2 text-sm font-medium text-muted-foreground">
                        <Loader2 className="h-4 w-4 animate-spin text-[var(--theme-primary)]" />
                        Loading districts...
                      </div>
                    ) : locations.length ? (
                      locations.map((loc) => {
                        const uuid = locUuid(loc);
                        const selected = form.district_uuids.includes(uuid);
                        return (
                          <button
                            key={uuid}
                            type="button"
                            className={`rounded-full border px-3 py-1.5 text-xs font-black transition ${selected ? "border-[var(--theme-primary)] bg-white text-[var(--theme-primary)] shadow-sm" : "border-[var(--theme-border-soft)] bg-white text-slate-700 hover:border-[var(--theme-primary)] hover:text-[var(--theme-primary)]"}`}
                            onClick={() => toggleDistrict(uuid)}
                          >
                            {locTitle(loc)}
                          </button>
                        );
                      })
                    ) : (
                      <p className="text-sm font-medium text-muted-foreground">
                        No districts available.
                      </p>
                    )}
                  </div>
                </div>
                {fieldError(formErrors, "district_uuids") && (
                  <p className="text-xs font-medium text-red-600">
                    {fieldError(formErrors, "district_uuids")}
                  </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={closeFormDialog}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                className="h-11 rounded-2xl px-5"
                disabled={isSubmitting}
              >
                {isSubmitting && <Loader2 className="h-4 w-4 animate-spin" />}
                {editingCourse ? "Update Course" : "Save Course"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog open={isViewOpen} onOpenChange={setIsViewOpen}>
        <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]">
              Course Detail
            </DialogTitle>
            <DialogDescription>
              View course information and assigned districts.
            </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 course...
            </div>
          ) : viewCourse ? (
            <div className="px-6 py-2">
              <DetailItem label="Title" value={viewCourse.title} />
              <DetailItem label="Title Hindi" value={viewCourse.title_hi} />
              <DetailItem label="Description" value={viewCourse.description} />
              <DetailItem
                label="Description Hindi"
                value={viewCourse.description_hi}
              />
              <DetailItem
                label="Course Location"
                value={viewCourse.course_location}
              />
              <DetailItem
                label="Course Location Hindi"
                value={viewCourse.course_location_hi}
              />
              <DetailItem
                label="Districts"
                value={
                  <LocationChips
                    locations={courseLocations(viewCourse, locations)}
                  />
                }
              />
              <DetailItem
                label="Status"
                value={<StatusBadge status={statusOf(viewCourse.status)} />}
              />
              <DetailItem
                label="Created By"
                value={actorLabel(viewCourse.created_by)}
              />
              <DetailItem
                label="Updated By"
                value={actorLabel(viewCourse.updated_by)}
              />
            </div>
          ) : null}
        </DialogContent>
      </Dialog>

      <AlertDialog
        open={Boolean(deleteCourse)}
        onOpenChange={(open) => {
          if (!open) setDeleteCourse(null);
        }}
      >
        <AlertDialogContent className="rounded-3xl border-[var(--theme-border-soft)]">
          <AlertDialogHeader>
            <AlertDialogTitle className="text-xl font-black text-[#1f1711]">
              Delete Course
            </AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete{" "}
              <span className="font-bold text-[#1f1711]">
                {deleteCourse ? titleOf(deleteCourse) : ""}
              </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}
            >
              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" />}Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
