"use client";

import {
  Badge,
  Button,
  Drawer,
  Flex,
  Group,
  Modal,
  Pagination,
  Select,
  Stack,
  Table,
  Text,
  TextInput,
  Title,
  SimpleGrid,
  Card,
  SegmentedControl,
  AspectRatio,
  Image,
  Tooltip,
  Box,
  Paper,
  Divider,
  ActionIcon,
  ThemeIcon,
} from "@mantine/core";
import { useDisclosure, useDebouncedValue } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";
import {
  IconBuilding,
  IconHistory,
  IconPlus,
  IconRefresh,
  IconSearch,
  IconTrash,
  IconEdit,
  IconLayoutGrid,
  IconList,
  IconMapPin,
  IconMail,
  IconPhone,
  IconCheck,
} from "@tabler/icons-react";
import moment from "moment";
import React, { useMemo, useState, useEffect } from "react";
import { useNavigate, useSearchParams } from "react-router";
import {
  deleteResort,
  syncResorts,
  syncResortsJson,
} from "@/lib/features/resorts/action";
import { listResorts } from "@/lib/features/resorts/query";
import type {
  ResortListItem,
  ResortListResponse,
} from "@/lib/features/resorts/types";
import type { AccessScope } from "@/lib/features/types";
import { ResortsLogsPanel } from "./_components/ResortsLogsPanel";

interface Props {
  initialData: ResortListResponse;
  initialError?: string;
  accessScope: AccessScope;
  systemMetrics?: {
    active: number;
    inactive: number;
    grades: Record<string, number>;
  };
}

const GRADE_COLORS: Record<
  string,
  { bg: string; text: string; border: string }
> = {
  PLATINUM: {
    bg: "var(--mantine-color-gray-0)",
    text: "var(--mantine-color-gray-8)",
    border: "var(--mantine-color-gray-3)",
  },
  EMERALD: {
    bg: "var(--mantine-color-gray-0)",
    text: "var(--mantine-color-gray-8)",
    border: "var(--mantine-color-gray-3)",
  },
  TITANIUM: {
    bg: "var(--mantine-color-gray-1)",
    text: "var(--mantine-color-gray-8)",
    border: "var(--mantine-color-gray-3)",
  },
  SILVER: {
    bg: "var(--mantine-color-gray-0)",
    text: "var(--mantine-color-gray-8)",
    border: "var(--mantine-color-gray-3)",
  },
};

const PAGE_SIZE_OPTIONS = ["10", "20", "50"];

const formatResortLocation = (resort: ResortListItem) => {
  const address = resort.address?.trim();
  const stateRegion = resort.state_region?.trim();
  const country = resort.country?.trim();

  if (!address) {
    const parts = [stateRegion, country].filter(Boolean);
    return parts.length > 0 ? parts.join(", ") : "";
  }

  let result = address;

  // Clean trailing commas/dots if any
  result = result.replace(/,\s*$/, "");

  if (
    stateRegion &&
    !result.toLowerCase().includes(stateRegion.toLowerCase())
  ) {
    result = `${result}, ${stateRegion}`;
  }
  if (country && !result.toLowerCase().includes(country.toLowerCase())) {
    result = `${result}, ${country}`;
  }
  return result;
};

export default function ResortsListClientPage({
  initialData,
  initialError,
  accessScope,
  systemMetrics,
}: Props) {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();

  const [items, setItems] = useState<ResortListItem[]>(initialData.items ?? []);
  const [total, setTotal] = useState(initialData.total ?? 0);
  const [loading, setLoading] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [syncingJson, setSyncingJson] = useState(false);

  // Sync state from loaderData when search params trigger a reload
  useEffect(() => {
    setItems(initialData.items ?? []);
    setTotal(initialData.total ?? 0);
  }, [initialData]);

  // Derived state from URL searchParams
  const page = parseInt(searchParams.get("page") || "1", 10);
  const pageSize = searchParams.get("pageSize") || "20";
  const search = searchParams.get("search") || "";
  const gradeFilter = searchParams.get("grade") || null;
  const statusFilter = searchParams.get("is_active") || null;

  // Local state for search text to allow smooth typing before debouncing
  const [localSearch, setLocalSearch] = useState(search);
  const [debouncedSearch] = useDebouncedValue(localSearch, 300);

  // Sync localSearch state if URL search param changes from outside (e.g. going back)
  useEffect(() => {
    setLocalSearch(search);
  }, [search]);

  // Update query params in URL
  const updateParams = (updates: Record<string, any>) => {
    setLoading(true);
    const newParams = new URLSearchParams(searchParams);

    Object.entries(updates).forEach(([key, value]) => {
      if (value === undefined || value === null || value === "") {
        newParams.delete(key);
      } else {
        newParams.set(key, String(value));
      }
    });

    // Reset to page 1 if we're changing filters/search
    if (
      !updates.page &&
      (updates.search !== undefined ||
        updates.grade !== undefined ||
        updates.is_active !== undefined)
    ) {
      newParams.set("page", "1");
    }

    setSearchParams(newParams);
    setLoading(false);
  };

  // Trigger search parameter update when debounced search value changes
  useEffect(() => {
    if (debouncedSearch !== search) {
      updateParams({ search: debouncedSearch });
    }
  }, [debouncedSearch]);

  const [deleteTarget, setDeleteTarget] = useState<ResortListItem | null>(null);
  const [deleting, setDeleting] = useState(false);
  const [deleteOpened, { open: openDelete, close: closeDelete }] =
    useDisclosure(false);
  const [historyOpened, { open: openHistory, close: closeHistory }] =
    useDisclosure(false);

  const [viewMode, setViewMode] = useState<string>("table");

  // Calculate live dynamic metrics from all items for the dashboard
  const metrics = useMemo(() => {
    if (systemMetrics) return systemMetrics;

    const active = items.filter((r) => r.is_active).length;
    const inactive = items.filter((r) => !r.is_active).length;

    // Count grades
    const grades: Record<string, number> = {
      PLATINUM: 0,
      EMERALD: 0,
      TITANIUM: 0,
      SILVER: 0,
    };
    items.forEach((r) => {
      if (r.grade && r.grade in grades) {
        grades[r.grade]++;
      }
    });

    return { active, inactive, grades };
  }, [items, systemMetrics]);

  const handleSyncResortsJson = async () => {
    setSyncingJson(true);
    try {
      const res = await syncResortsJson();
      if (res.success && res.data) {
        notifications.show({
          color: "green",
          message: `Successfully synced configurations from resort.json: ${res.data.updatedResorts} resorts and ${res.data.updatedUnits} units updated.`,
        });
        navigate(".", { replace: true });
      } else {
        notifications.show({
          color: "red",
          message:
            res.message || "Failed to sync configurations from resort.json",
        });
      }
    } catch {
      notifications.show({
        color: "red",
        message: "Failed to sync configurations from resort.json",
      });
    } finally {
      setSyncingJson(false);
    }
  };

  const handleSyncResorts = async () => {
    setSyncing(true);
    try {
      const res = await syncResorts();
      if (res.success && res.data) {
        notifications.show({
          color: "green",
          message: `Successfully synced ${res.data.synced} resorts from Strapi.`,
        });
        navigate(".", { replace: true });
      } else {
        notifications.show({
          color: "red",
          message: res.message || "Failed to sync resorts",
        });
      }
    } catch {
      notifications.show({
        color: "red",
        message: "An unexpected error occurred during sync",
      });
    } finally {
      setSyncing(false);
    }
  };

  const handleGradeFilter = (val: string | null) => {
    updateParams({ grade: val });
  };

  const handleStatusFilter = (val: string | null) => {
    updateParams({ is_active: val });
  };

  const handlePageChange = (p: number) => {
    updateParams({ page: p });
  };

  const handlePageSizeChange = (ps: string | null) => {
    updateParams({ pageSize: ps || "20", page: 1 });
  };

  const handleDeleteClick = (e: React.MouseEvent, resort: ResortListItem) => {
    e.stopPropagation();
    setDeleteTarget(resort);
    openDelete();
  };

  const handleDeleteConfirm = async () => {
    if (!deleteTarget) return;
    setDeleting(true);
    try {
      const res = await deleteResort(deleteTarget.id);
      if (res.success) {
        notifications.show({ color: "green", message: "Resort deleted" });
        setItems((prev) => prev.filter((r) => r.id !== deleteTarget.id));
        setTotal((t) => t - 1);
        closeDelete();
      } else {
        notifications.show({
          color: "red",
          message: res.message || "Delete failed",
        });
      }
    } catch {
      notifications.show({ color: "red", message: "Delete failed" });
    } finally {
      setDeleting(false);
    }
  };

  const totalPages = Math.ceil(total / parseInt(pageSize, 10));

  return (
    <Stack
      px={28}
      py={20}
      gap="xl"
      style={{
        minHeight: "100%",
        backgroundColor: "var(--mantine-color-gray-0)",
      }}
    >
      {/* Clean Header */}
      <Flex
        justify="space-between"
        align="center"
        direction={{ base: "column", sm: "row" }}
        gap="md"
        mb="xl"
      >
        <Group gap="sm">
          <ThemeIcon size={36} radius="xl" variant="light" color="gray">
            <IconBuilding size={20} style={{ color: "#495057" }} />
          </ThemeIcon>
          <Stack gap={2}>
            <Title
              order={3}
              style={{
                fontFamily: "Outfit, Inter, sans-serif",
                fontWeight: 700,
                color: "#212529",
              }}
            >
              Resort Catalog
            </Title>
            <Text size="xs" c="dimmed">
              Manage resort inventory, metadata, pricing tiers, and room
              classification configurations.
            </Text>
          </Stack>
        </Group>
        <Group gap="xs" wrap="wrap">
          <Button
            variant="light"
            color="gray"
            radius="md"
            size="sm"
            leftSection={<IconHistory size={16} />}
            onClick={openHistory}
          >
            Activity
          </Button>
          <Button
            variant="light"
            color="gray"
            radius="md"
            size="sm"
            leftSection={<IconRefresh size={16} />}
            onClick={() => navigate(".", { replace: true })}
            loading={loading}
          >
            Refresh
          </Button>
          {accessScope.update && (
            <>
              <Button
                variant="light"
                color="gray"
                radius="md"
                size="sm"
                leftSection={<IconRefresh size={16} />}
                onClick={handleSyncResorts}
                loading={syncing}
              >
                Sync Strapi
              </Button>
              {/* <Button variant="light" color="gray" radius="md" size="sm" leftSection={<IconRefresh size={16} />} onClick={handleSyncResortsJson} loading={syncingJson}>
                Sync resort.json
              </Button> */}
            </>
          )}
        </Group>
      </Flex>

      {/* Metrics Dashboard */}
      <SimpleGrid cols={{ base: 1, sm: 2, md: 4 }} spacing="md">
        <Paper
          withBorder
          p="lg"
          radius="md"
          style={{
            background: "#ffffff",
            position: "relative",
            overflow: "hidden",
          }}
        >
          <Text size="xs" c="dimmed" tt="uppercase" fw={700} lts={1}>
            Total Resorts
          </Text>
          <Text size="xl" fw={800} mt="xs" c="gray.8">
            {total}
          </Text>
          <Box
            style={{
              position: "absolute",
              bottom: -10,
              right: -10,
              opacity: 0.08,
            }}
          >
            <IconBuilding size={80} />
          </Box>
        </Paper>

        <Paper
          withBorder
          p="lg"
          radius="md"
          style={{
            background: "#ffffff",
            position: "relative",
            overflow: "hidden",
          }}
        >
          <Text size="xs" c="dimmed" tt="uppercase" fw={700} lts={1}>
            Active in System
          </Text>
          <Text size="xl" fw={800} mt="xs" c="gray.8">
            {metrics.active}
          </Text>
          <Box
            style={{
              position: "absolute",
              bottom: -10,
              right: -10,
              opacity: 0.08,
            }}
          >
            <IconCheck size={80} />
          </Box>
        </Paper>

        <Paper
          withBorder
          p="lg"
          radius="md"
          style={{
            background: "#ffffff",
            position: "relative",
            overflow: "hidden",
          }}
        >
          <Text size="xs" c="dimmed" tt="uppercase" fw={700} lts={1}>
            Inactive
          </Text>
          <Text size="xl" fw={800} mt="xs" c="gray.8">
            {metrics.inactive}
          </Text>
          <Box
            style={{
              position: "absolute",
              bottom: -10,
              right: -10,
              opacity: 0.08,
            }}
          >
            <IconTrash size={80} />
          </Box>
        </Paper>

        <Paper
          withBorder
          p="lg"
          radius="md"
          style={{
            background: "#ffffff",
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
          }}
        >
          <Text size="xs" c="dimmed" tt="uppercase" fw={700} lts={1} mb="xs">
            Grade Breakdown
          </Text>
          <Group gap="xs" wrap="wrap">
            {Object.keys(GRADE_COLORS).map((gr) => (
              <Tooltip label={`${gr} tier`} key={gr}>
                <Badge
                  style={{
                    backgroundColor: GRADE_COLORS[gr].bg,
                    color: GRADE_COLORS[gr].text,
                    border: `1px solid ${GRADE_COLORS[gr].border}`,
                  }}
                  variant="light"
                  size="sm"
                >
                  {gr.charAt(0) + gr.slice(1).toLowerCase()}:{" "}
                  {metrics.grades[gr] || 0}
                </Badge>
              </Tooltip>
            ))}
          </Group>
        </Paper>
      </SimpleGrid>

      {initialError && (
        <Paper
          withBorder
          p="md"
          radius="md"
          style={{
            backgroundColor: "var(--mantine-color-red-0)",
            borderColor: "var(--mantine-color-red-2)",
          }}
        >
          <Text size="sm" c="red">
            {initialError}
          </Text>
        </Paper>
      )}

      {/* Advanced Filter Panel */}
      <Paper
        withBorder
        radius="md"
        p="md"
        style={{ backgroundColor: "#ffffff" }}
      >
        <Flex justify="space-between" align="center" wrap="wrap" gap="md">
          <Group gap="sm" style={{ flex: 1, minWidth: 280 }}>
            <TextInput
              placeholder="Search by resort name..."
              leftSection={
                <IconSearch
                  size={18}
                  stroke={1.5}
                  color="var(--mantine-color-gray-5)"
                />
              }
              value={localSearch}
              onChange={(e) => setLocalSearch(e.currentTarget.value)}
              size="sm"
              radius="md"
              style={{ flex: 1, maxWidth: 350 }}
            />
            <Select
              placeholder="Filter by Grade"
              data={[
                { value: "PLATINUM", label: "Platinum" },
                { value: "EMERALD", label: "Emerald" },
                { value: "TITANIUM", label: "Titanium" },
                { value: "SILVER", label: "Silver" },
              ]}
              value={gradeFilter}
              onChange={handleGradeFilter}
              clearable
              size="sm"
              radius="md"
              style={{ width: 150 }}
            />
            <Select
              placeholder="Status"
              data={[
                { value: "true", label: "Active" },
                { value: "false", label: "Inactive" },
              ]}
              value={statusFilter}
              onChange={handleStatusFilter}
              clearable
              size="sm"
              radius="md"
              style={{ width: 120 }}
            />
            {(search || gradeFilter || statusFilter) && (
              <Button
                variant="subtle"
                color="red"
                size="sm"
                radius="md"
                onClick={() => {
                  setLocalSearch("");
                  updateParams({
                    search: "",
                    grade: "",
                    is_active: "",
                    page: 1,
                  });
                }}
              >
                Clear Filters
              </Button>
            )}
          </Group>
          <Group gap="xs">
            <Text size="sm" fw={600} c="dimmed">
              View Layout
            </Text>
            <SegmentedControl
              value={viewMode}
              onChange={setViewMode}
              radius="md"
              data={[
                {
                  value: "table",
                  label: (
                    <CenterLabel
                      icon={<IconIconList size={16} />}
                      label="Table"
                    />
                  ),
                },
                {
                  value: "grid",
                  label: (
                    <CenterLabel
                      icon={<IconLayoutGrid size={16} />}
                      label="Grid"
                    />
                  ),
                },
              ]}
            />
          </Group>
        </Flex>
      </Paper>

      {/* Main Content Area */}
      <Stack gap="md">
        {items.length === 0 ? (
          <Paper
            withBorder
            radius="md"
            p="xl"
            style={{ backgroundColor: "#ffffff", textAlign: "center" }}
          >
            <Stack align="center" py="xl" gap="xs">
              <IconBuilding
                size={50}
                opacity={0.2}
                color="var(--mantine-color-gray-6)"
              />
              <Text fw={600} size="md" c="gray.7">
                No resorts matched your criteria.
              </Text>
              <Text size="sm" c="dimmed">
                Try clearing your filters or refreshing to restore the standard
                view.
              </Text>
            </Stack>
          </Paper>
        ) : viewMode === "grid" ? (
          /* Premium Grid View */
          <SimpleGrid cols={{ base: 1, sm: 2, md: 3 }} spacing="lg">
            {items.map((resort) => (
              <Card
                key={resort.id}
                withBorder
                radius="lg"
                p="md"
                shadow="sm"
                style={{
                  backgroundColor: "#ffffff",
                  transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",
                  cursor: "pointer",
                }}
                className="resort-hover-card"
                onClick={() => navigate(`/admin/resorts/${resort.id}`)}
              >
                {/* Image Section */}
                <Card.Section style={{ position: "relative" }}>
                  {resort.cover_image ? (
                    <AspectRatio ratio={16 / 9}>
                      <Image
                        src={resort.cover_image}
                        fallbackSrc="https://placehold.co/600x400?text=No+Cover+Image"
                        alt={resort.name}
                        style={{
                          borderTopLeftRadius: "12px",
                          borderTopRightRadius: "12px",
                        }}
                      />
                    </AspectRatio>
                  ) : (
                    <AspectRatio ratio={16 / 9}>
                      <Box
                        style={{
                          background: "#f1f3f5",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          borderTopLeftRadius: "12px",
                          borderTopRightRadius: "12px",
                        }}
                      >
                        <IconBuilding
                          size={50}
                          color="var(--mantine-color-gray-5)"
                          style={{ opacity: 0.6 }}
                        />
                      </Box>
                    </AspectRatio>
                  )}
                  {/* Status Indicator Badges */}
                  <Box style={{ position: "absolute", top: 12, right: 12 }}>
                    <Badge
                      color={resort.is_active ? "green" : "gray"}
                      variant="filled"
                      size="sm"
                    >
                      {resort.is_active ? "Active" : "Inactive"}
                    </Badge>
                  </Box>
                  {resort.grade && (
                    <Box style={{ position: "absolute", bottom: 12, left: 12 }}>
                      <Badge
                        style={{
                          backgroundColor: "#ffffff",
                          color: GRADE_COLORS[resort.grade]?.text || "gray",
                          border: `1px solid ${GRADE_COLORS[resort.grade]?.border || "var(--mantine-color-gray-3)"}`,
                        }}
                        size="sm"
                        variant="white"
                      >
                        {resort.grade}
                      </Badge>
                    </Box>
                  )}
                </Card.Section>

                {/* Details Section */}
                <Stack gap="sm" mt="md" style={{ flexGrow: 1 }}>
                  <Stack gap={2}>
                    <Text
                      fw={700}
                      size="md"
                      c="gray.9"
                      style={{ fontFamily: "Outfit, Inter, sans-serif" }}
                    >
                      {resort.name}
                    </Text>
                    {resort.code && (
                      <Text size="sm" fw={600} c="dimmed">
                        CODE: {resort.code}
                      </Text>
                    )}
                  </Stack>

                  <Divider />

                  <Stack gap={4}>
                    <Group gap={6} wrap="nowrap">
                      <IconMapPin
                        size={14}
                        color="var(--mantine-color-gray-5)"
                      />
                      <Text
                        size="sm"
                        c="dimmed"
                        style={{
                          whiteSpace: "nowrap",
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                        }}
                      >
                        {formatResortLocation(resort) || "No address defined"}
                      </Text>
                    </Group>
                    {resort.phone && (
                      <Group gap={6} wrap="nowrap">
                        <IconPhone
                          size={14}
                          color="var(--mantine-color-gray-5)"
                        />
                        <Text size="sm" c="dimmed">
                          {resort.phone}
                        </Text>
                      </Group>
                    )}
                    {resort.email && (
                      <Group gap={6} wrap="nowrap">
                        <IconMail
                          size={14}
                          color="var(--mantine-color-gray-5)"
                        />
                        <Text
                          size="sm"
                          c="dimmed"
                          style={{
                            whiteSpace: "nowrap",
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                          }}
                        >
                          {resort.email}
                        </Text>
                      </Group>
                    )}
                  </Stack>
                </Stack>

                {/* Card Actions */}
                <Card.Section
                  px="md"
                  py="xs"
                  style={{
                    borderTop: "1px solid var(--mantine-color-gray-2)",
                    marginTop: "auto",
                  }}
                >
                  <Group
                    justify="space-between"
                    align="center"
                    style={{ width: "100%" }}
                  >
                    <Text size="xs" c="dimmed">
                      Created:{" "}
                      {resort.created_at
                        ? moment(resort.created_at).format("MMM YYYY")
                        : "—"}
                    </Text>
                    <Group gap="xs" onClick={(e) => e.stopPropagation()}>
                      {accessScope.update && (
                        <ActionIcon
                          variant="subtle"
                          color="gray"
                          size="sm"
                          onClick={() =>
                            navigate(`/admin/resorts/${resort.id}`)
                          }
                        >
                          <IconEdit size={16} />
                        </ActionIcon>
                      )}
                      {accessScope.delete && (
                        <ActionIcon
                          variant="subtle"
                          color="red"
                          size="sm"
                          onClick={(e) => handleDeleteClick(e, resort)}
                        >
                          <IconTrash size={16} />
                        </ActionIcon>
                      )}
                    </Group>
                  </Group>
                </Card.Section>
              </Card>
            ))}
          </SimpleGrid>
        ) : (
          /* Premium Table View */
          <Paper
            withBorder
            radius="md"
            style={{ overflow: "hidden", backgroundColor: "#ffffff" }}
          >
            <Table
              striped
              highlightOnHover
              verticalSpacing="md"
              horizontalSpacing="md"
            >
              <Table.Thead
                style={{ backgroundColor: "var(--mantine-color-gray-1)" }}
              >
                <Table.Tr>
                  <Table.Th style={{ color: "var(--mantine-color-gray-7)" }}>
                    Resort Name
                  </Table.Th>
                  <Table.Th style={{ color: "var(--mantine-color-gray-7)" }}>
                    Code
                  </Table.Th>
                  <Table.Th style={{ color: "var(--mantine-color-gray-7)" }}>
                    Grade
                  </Table.Th>
                  <Table.Th style={{ color: "var(--mantine-color-gray-7)" }}>
                    Status
                  </Table.Th>
                  <Table.Th style={{ color: "var(--mantine-color-gray-7)" }}>
                    Location
                  </Table.Th>
                  <Table.Th style={{ color: "var(--mantine-color-gray-7)" }}>
                    Created
                  </Table.Th>
                  <Table.Th
                    style={{ color: "var(--mantine-color-gray-7)", width: 120 }}
                  >
                    Actions
                  </Table.Th>
                </Table.Tr>
              </Table.Thead>
              <Table.Tbody>
                {items.map((resort) => (
                  <Table.Tr
                    key={resort.id}
                    style={{
                      cursor: "pointer",
                      transition: "background-color 0.2s",
                    }}
                    onClick={() => navigate(`/admin/resorts/${resort.id}`)}
                  >
                    <Table.Td>
                      <Text fw={700} size="sm" c="gray.9">
                        {resort.name}
                      </Text>
                    </Table.Td>
                    <Table.Td>
                      <Text fw={600} size="sm" c="dimmed">
                        {resort.code || "—"}
                      </Text>
                    </Table.Td>
                    <Table.Td>
                      {resort.grade ? (
                        <Badge
                          style={{
                            backgroundColor: GRADE_COLORS[resort.grade]?.bg,
                            color: GRADE_COLORS[resort.grade]?.text,
                            border: `1px solid ${GRADE_COLORS[resort.grade]?.border}`,
                          }}
                          variant="light"
                          size="sm"
                        >
                          {resort.grade.charAt(0) +
                            resort.grade.slice(1).toLowerCase()}
                        </Badge>
                      ) : (
                        <Text size="sm" c="dimmed">
                          —
                        </Text>
                      )}
                    </Table.Td>
                    <Table.Td>
                      <Badge
                        color={resort.is_active ? "green" : "gray"}
                        variant="light"
                        size="sm"
                      >
                        {resort.is_active ? "Active" : "Inactive"}
                      </Badge>
                    </Table.Td>
                    <Table.Td>
                      <Text
                        size="sm"
                        c="dimmed"
                        style={{
                          maxWidth: 200,
                          whiteSpace: "nowrap",
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                        }}
                      >
                        {formatResortLocation(resort) || "—"}
                      </Text>
                    </Table.Td>
                    <Table.Td>
                      <Text size="sm" c="dimmed">
                        {resort.created_at
                          ? moment(resort.created_at).format("DD MMM YYYY")
                          : "—"}
                      </Text>
                    </Table.Td>
                    <Table.Td onClick={(e) => e.stopPropagation()}>
                      <Group gap="xs" justify="flex-start">
                        {accessScope.update && (
                          <Tooltip
                            label="Edit Details"
                            position="top"
                            withArrow
                          >
                            <ActionIcon
                              variant="light"
                              color="gray"
                              size="md"
                              onClick={() =>
                                navigate(`/admin/resorts/${resort.id}`)
                              }
                            >
                              <IconEdit size={16} />
                            </ActionIcon>
                          </Tooltip>
                        )}
                        {accessScope.delete && (
                          <Tooltip
                            label="Delete Resort"
                            position="top"
                            withArrow
                          >
                            <ActionIcon
                              variant="light"
                              color="red"
                              size="md"
                              onClick={(e) => handleDeleteClick(e, resort)}
                            >
                              <IconTrash size={16} />
                            </ActionIcon>
                          </Tooltip>
                        )}
                      </Group>
                    </Table.Td>
                  </Table.Tr>
                ))}
              </Table.Tbody>
            </Table>
          </Paper>
        )}

        {/* Footer & Pagination Controls */}
        <Paper
          withBorder
          p="md"
          radius="md"
          style={{ backgroundColor: "#ffffff" }}
        >
          <Flex justify="space-between" align="center" wrap="wrap" gap="md">
            <Group gap="xs">
              <Select
                style={{ width: 80 }}
                data={PAGE_SIZE_OPTIONS}
                value={pageSize}
                onChange={handlePageSizeChange}
                size="sm"
                radius="md"
              />
              <Text size="xs" c="dimmed" fw={600}>
                Entries per page
              </Text>
            </Group>
            <Group gap="md">
              <Text size="xs" c="dimmed" fw={600}>
                {total} resort{total !== 1 ? "s" : ""} found
              </Text>
              <Pagination
                total={totalPages}
                value={page}
                onChange={handlePageChange}
                size="sm"
                radius="md"
              />
            </Group>
          </Flex>
        </Paper>
      </Stack>

      {/* Delete Confirmation Modal */}
      <Modal
        opened={deleteOpened}
        onClose={closeDelete}
        title="Delete Resort Configuration"
        centered
        size="md"
        radius="lg"
      >
        <Stack p="xs">
          <Text size="sm">
            Are you sure you want to delete{" "}
            <Text span fw={700} c="red.6">
              {deleteTarget?.name}
            </Text>
            ?
          </Text>
          <Text size="xs" c="dimmed">
            This is an irreversible operation. It will permanently remove the
            resort and all room units associated with it from the datastore.
          </Text>
          <Group justify="flex-end" mt="md">
            <Button
              variant="subtle"
              color="gray"
              radius="md"
              onClick={closeDelete}
            >
              Cancel
            </Button>
            <Button
              color="red"
              radius="md"
              onClick={handleDeleteConfirm}
              loading={deleting}
            >
              Confirm Delete
            </Button>
          </Group>
        </Stack>
      </Modal>

      {/* Activity Logs Drawer */}
      <Drawer
        opened={historyOpened}
        onClose={closeHistory}
        title="Resort Modification Logs"
        position="right"
        size="lg"
      >
        <ResortsLogsPanel resortId={null} />
      </Drawer>

      {/* Custom Styles Injection */}
      <style>{`
        .resort-hover-card:hover {
          transform: translateY(-5px);
          box-shadow: var(--mantine-shadow-md) !important;
          border-color: var(--mantine-color-gray-4) !important;
        }
        @keyframes pulse {
          0% { box-shadow: 0 0 0 0 rgba(47, 158, 68, 0.4); }
          70% { box-shadow: 0 0 0 8px rgba(47, 158, 68, 0); }
          100% { box-shadow: 0 0 0 0 rgba(47, 158, 68, 0); }
        }
      `}</style>
    </Stack>
  );
}

// Helpers for segmented view toggling inside React Server Components compatibility
function CenterLabel({
  icon,
  label,
}: {
  icon: React.ReactNode;
  label: string;
}) {
  return (
    <Group gap="xs" wrap="nowrap" justify="center">
      {icon}
      <Text size="xs" fw={600}>
        {label}
      </Text>
    </Group>
  );
}

function IconIconList({ size }: { size: number }) {
  return <IconList size={size} />;
}
