"use client";

/**
 * Promo access roles — list.
 *
 * Reached from the Access List rather than the nav: a role grants the same promo
 * code / campaign / export access, just as a reusable bundle. Creating and editing
 * happen on their own page, so this stays a plain list.
 */

import {
  Badge,
  Button,
  Card,
  Container,
  Flex,
  Group,
  Modal,
  Skeleton,
  Stack,
  Table,
  Text,
  Title,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import {
  IconArrowLeft,
  IconPencil,
  IconPlus,
  IconShieldLock,
  IconTrash,
} from "@tabler/icons-react";
import { useCallback, useEffect, useState } from "react";
import { Link, useNavigate } from "react-router";
import {
  deletePromoAccessRole,
  listPromoAccessRoles,
  type PromoAccessRoleSummary,
} from "@/lib/features/promo-access-roles/query";
import type { AccessScope } from "@/lib/features/types";
import styles from "@/routes/promo-code-campaigns/_components/promo.module.css";

export default function PromoAccessRolesClientPage({
  accessScope,
}: {
  accessScope: AccessScope;
}) {
  const navigate = useNavigate();
  const [roles, setRoles] = useState<PromoAccessRoleSummary[]>([]);
  const [loading, setLoading] = useState(true);
  const [deleting, setDeleting] = useState<PromoAccessRoleSummary | null>(null);
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await listPromoAccessRoles();
    setRoles(res.success && res.data ? res.data : []);
    setLoading(false);
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  const remove = async () => {
    if (!deleting) return;
    setBusy(true);
    const res = await deletePromoAccessRole(deleting.id);
    setBusy(false);
    notifications.show({
      color: res.success ? "green" : "red",
      message: res.message,
    });
    if (res.success) {
      setDeleting(null);
      await load();
    }
  };

  return (
    <Container fluid px={0} py={0}>
      <Flex justify="space-between" align="center" wrap="wrap" gap="sm" mb="md">
        <Group gap="sm">
          <Button
            variant="subtle"
            size="compact-sm"
            leftSection={<IconArrowLeft size={15} />}
            component={Link}
            to="/admin/access-list"
          >
            Access List
          </Button>
          <Group gap={8}>
            <IconShieldLock size={19} stroke={1.8} />
            <Title order={4}>Promo Code Roles</Title>
            <Badge variant="light" size="sm">
              {roles.length}
            </Badge>
          </Group>
        </Group>
        {accessScope.create && (
          <Button
            leftSection={<IconPlus size={16} />}
            onClick={() => navigate("/admin/promo-access-roles/new")}
          >
            Create role
          </Button>
        )}
      </Flex>

      <Text size="sm" c="dimmed" mb="md">
        A role bundles campaigns, promo codes and export permissions. Apply one to a
        member from their Access List page — their settings stay editable afterwards.
      </Text>

      <Card className={styles.sectionCard} p="md">
        {loading ? (
          <Stack gap={6}>
            {Array.from({ length: 5 }, (_, i) => (
              <Skeleton key={i} height={38} radius="sm" />
            ))}
          </Stack>
        ) : roles.length === 0 ? (
          <Stack align="center" gap="sm" py="xl">
            <Text size="sm" c="dimmed">
              No roles yet.
            </Text>
            {accessScope.create && (
              <Button
                variant="light"
                leftSection={<IconPlus size={15} />}
                onClick={() => navigate("/admin/promo-access-roles/new")}
              >
                Create the first role
              </Button>
            )}
          </Stack>
        ) : (
          <Table stickyHeader>
            <Table.Thead className={styles.tableHead}>
              <Table.Tr>
                <Table.Th className={styles.th}>Role</Table.Th>
                <Table.Th className={styles.th}>Campaigns</Table.Th>
                <Table.Th className={styles.th}>Promo codes</Table.Th>
                <Table.Th className={styles.th} />
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>
              {roles.map((r) => (
                <Table.Tr
                  key={r.id}
                  className={styles.row}
                  onClick={() => navigate(`/admin/promo-access-roles/${r.id}`)}
                >
                  <Table.Td>
                    <Stack gap={0}>
                      <Text size="sm" fw={600}>
                        {r.name}
                      </Text>
                      {r.description && (
                        <Text size="xs" c="dimmed" lineClamp={1}>
                          {r.description}
                        </Text>
                      )}
                    </Stack>
                  </Table.Td>
                  <Table.Td className={styles.num}>{r.campaign_count}</Table.Td>
                  <Table.Td className={styles.num}>
                    {r.promo_code_count}
                  </Table.Td>
                  <Table.Td onClick={(e) => e.stopPropagation()}>
                    <Group gap={6} justify="flex-end" wrap="nowrap">
                      <Button
                        size="compact-xs"
                        variant="light"
                        leftSection={<IconPencil size={13} />}
                        component={Link}
                        to={`/admin/promo-access-roles/${r.id}`}
                      >
                        Edit
                      </Button>
                      {accessScope.delete && (
                        <Button
                          size="compact-xs"
                          variant="subtle"
                          color="red"
                          onClick={() => setDeleting(r)}
                        >
                          <IconTrash size={14} />
                        </Button>
                      )}
                    </Group>
                  </Table.Td>
                </Table.Tr>
              ))}
            </Table.Tbody>
          </Table>
        )}
      </Card>

      <Modal
        opened={deleting !== null}
        onClose={() => setDeleting(null)}
        title="Delete role?"
        centered
      >
        <Stack gap="sm">
          <Text size="sm">
            Delete <b>{deleting?.name}</b>?
          </Text>
          {/* Applying was a copy, so nobody loses access — worth saying plainly. */}
          <Text size="xs" c="dimmed">
            Members already set up from this role keep their access — only the
            reusable role is removed.
          </Text>
          <Group justify="flex-end">
            <Button variant="default" onClick={() => setDeleting(null)}>
              Cancel
            </Button>
            <Button color="red" loading={busy} onClick={() => void remove()}>
              Delete
            </Button>
          </Group>
        </Stack>
      </Modal>
    </Container>
  );
}
