import {
  ActionIcon,
  Badge,
  Box,
  Button,
  Card,
  Group,
  Loader,
  Stack,
  Table,
  Text,
  TextInput,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import {
  IconPlus,
  IconSearch,
  IconShieldCheck,
  IconTicket,
  IconTrash,
} from "@tabler/icons-react";
import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router";
import { motion, useReducedMotion } from "framer-motion";
import { BarChart } from "@mantine/charts";
import { useRoleAccess } from "@/hooks/useRoleAccess";
import {
  getAnalytics,
  listAllTickets,
  listAllowlist,
  listAudit,
  type GuruStats,
} from "@/lib/features/guru/query";
import type { GuruTicket } from "@/lib/features/guru/types";
import {
  addToAllowlist,
  removeFromAllowlist,
} from "@/lib/features/guru/action";
import type {
  GuruAllowlistEntry,
  GuruAuditEntry,
} from "@/lib/features/guru/types";

const fmt = (d: string) =>
  new Date(d).toLocaleString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });

/** Super-admin tools: the edit allowlist and the write audit log (spec §3). */
const AllowlistCard = () => {
  const [entries, setEntries] = useState<GuruAllowlistEntry[]>([]);
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await listAllowlist();
    if (res.success && res.data) setEntries(res.data.allowlist);
    setLoading(false);
  }, []);

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

  const add = async () => {
    const value = email.trim();
    if (!value) return;
    setBusy(true);
    const res = await addToAllowlist(value);
    if (res.success) {
      setEmail("");
      notifications.show({ message: `${value} can now confirm member edits.` });
      await load();
    } else {
      notifications.show({ color: "red", message: res.message || "Failed." });
    }
    setBusy(false);
  };

  const remove = async (entry: GuruAllowlistEntry) => {
    const res = await removeFromAllowlist(entry.email);
    if (res.success) {
      notifications.show({ message: `${entry.email} removed.` });
      await load();
    } else {
      notifications.show({ color: "red", message: res.message || "Failed." });
    }
  };

  return (
    <Card padding={18} radius={14} withBorder>
      <Group gap={8} mb={2}>
        <IconShieldCheck size={17} color="#8c7451" />
        <Text fz={14.5} fw={600}>
          Edit allowlist
        </Text>
      </Group>
      <Text fz={12} c="#898781" mb={12}>
        Only these users can confirm member-data changes proposed by the Guru.
        Everyone else gets a refusal — enforced on the server, per request.
      </Text>

      <Group gap={10} mb={14} wrap="nowrap">
        <TextInput
          radius="xl"
          placeholder="name@karmagroup.com"
          value={email}
          onChange={(e) => setEmail(e.currentTarget.value)}
          onKeyDown={(e) => e.key === "Enter" && void add()}
          style={{ flex: 1 }}
        />
        <Button
          radius="xl"
          color="#0d0c0a"
          leftSection={<IconPlus size={14} />}
          onClick={() => void add()}
          loading={busy}
          disabled={!email.trim()}
        >
          Allow
        </Button>
      </Group>

      {loading ? (
        <Group justify="center" py={20}>
          <Loader size="sm" color="#8c7451" />
        </Group>
      ) : entries.length === 0 ? (
        <Text fz={13} c="#52514e" ta="center" py={14}>
          Nobody can confirm edits yet. Add the first user above.
        </Text>
      ) : (
        <Stack gap={8}>
          {entries.map((e) => (
            <Group
              key={e.id}
              justify="space-between"
              p={10}
              style={{
                background: "#faf8f4",
                borderRadius: 10,
                border: "1px solid rgba(11,11,11,.06)",
              }}
            >
              <Box>
                <Text fz={13} fw={600}>
                  {e.email}
                </Text>
                <Text fz={11.5} c="#898781">
                  added by {e.added_by} · {fmt(e.created_at)}
                </Text>
              </Box>
              <ActionIcon
                variant="subtle"
                color="#d03b3b"
                radius="xl"
                onClick={() => void remove(e)}
                aria-label={`Remove ${e.email}`}
              >
                <IconTrash size={16} />
              </ActionIcon>
            </Group>
          ))}
        </Stack>
      )}
    </Card>
  );
};

const AuditCard = () => {
  const [entries, setEntries] = useState<GuruAuditEntry[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    void (async () => {
      const res = await listAudit({ page: 1, limit: 50 });
      if (res.success && res.data) {
        setEntries(res.data.entries);
        setTotal(res.data.total);
      }
      setLoading(false);
    })();
  }, []);

  return (
    <Card padding={18} radius={14} withBorder>
      <Text fz={14.5} fw={600}>
        Audit log
      </Text>
      <Text fz={12} c="#898781" mb={12}>
        Every write attempt and module action · {total} entries
      </Text>
      {loading ? (
        <Group justify="center" py={20}>
          <Loader size="sm" color="#8c7451" />
        </Group>
      ) : entries.length === 0 ? (
        <Text fz={13} c="#52514e" ta="center" py={14}>
          Nothing audited yet.
        </Text>
      ) : (
        <Table.ScrollContainer minWidth={640}>
          <Table fz={12.5} verticalSpacing={8}>
            <Table.Thead>
              <Table.Tr>
                <Table.Th>When</Table.Th>
                <Table.Th>Action</Table.Th>
                <Table.Th>Actor</Table.Th>
                <Table.Th>Member</Table.Th>
                <Table.Th>Result</Table.Th>
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>
              {entries.map((e) => (
                <Table.Tr key={e.id}>
                  <Table.Td style={{ whiteSpace: "nowrap" }}>
                    {fmt(e.created_at)}
                  </Table.Td>
                  <Table.Td>
                    <Text ff="monospace" fz={12}>
                      {e.action}
                    </Text>
                  </Table.Td>
                  <Table.Td>{e.actor_email ?? "—"}</Table.Td>
                  <Table.Td>{e.member_ref ?? "—"}</Table.Td>
                  <Table.Td>
                    {e.success === null ? (
                      "—"
                    ) : e.success ? (
                      <Badge size="xs" radius="xl" color="#1e7a43" variant="light">
                        OK
                      </Badge>
                    ) : (
                      <Badge size="xs" radius="xl" color="#d03b3b" variant="light">
                        FAILED
                      </Badge>
                    )}
                  </Table.Td>
                </Table.Tr>
              ))}
            </Table.Tbody>
          </Table>
        </Table.ScrollContainer>
      )}
    </Card>
  );
};

const OUTCOME_LABELS: Record<string, string> = {
  AUTO_RESOLVED: "Auto-resolved",
  ESCALATED: "Escalated",
  CLOSED_BY_CONCIERGE: "Closed by concierge",
  AUTO_CLOSED_INACTIVE: "Auto-closed (inactive)",
  open: "Open",
};

const AnalyticsCards = () => {
  const [stats, setStats] = useState<GuruStats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    void (async () => {
      const res = await getAnalytics();
      if (res.success && res.data) setStats(res.data);
      setLoading(false);
    })();
  }, []);

  if (loading)
    return (
      <Group justify="center" py={30}>
        <Loader size="sm" color="#8c7451" />
      </Group>
    );
  if (!stats) return null;

  const totals = Object.fromEntries(
    stats.by_outcome.map((o) => [o.outcome, o.count]),
  );
  const totalTickets = stats.by_outcome.reduce((s, o) => s + o.count, 0);

  const tiles = [
    { label: "Total cases", value: totalTickets, hint: "all time" },
    {
      label: "Auto-resolved",
      value: totals.AUTO_RESOLVED ?? 0,
      hint: "closed by the Guru",
    },
    {
      label: "Escalated",
      value: totals.ESCALATED ?? 0,
      hint: "handed to the team",
    },
    {
      label: "Time to resolve",
      value:
        stats.avg_resolution_hours === null
          ? "–"
          : `${stats.avg_resolution_hours}h`,
      hint: "average, resolved cases",
    },
  ];

  return (
    <Stack gap={14}>
      <Group grow gap={14} align="stretch">
        {tiles.map((t) => (
          <Card key={t.label} padding={16} radius={14} withBorder>
            <Text fz={12} c="#52514e">
              {t.label}
            </Text>
            <Text ff="serif" fz={30} fw={600} lh={1.05}>
              {t.value}
            </Text>
            <Text fz={11.5} c="#898781">
              {t.hint}
            </Text>
          </Card>
        ))}
      </Group>

      <Group grow gap={14} align="stretch">
        <Card padding={18} radius={14} withBorder>
          <Text fz={14.5} fw={600}>
            Volume by category
          </Text>
          <Text fz={12} c="#898781" mb={12}>
            What concierges ask about
          </Text>
          {stats.by_category.length === 0 ? (
            <Text fz={13} c="#52514e" py={10} ta="center">
              No cases yet.
            </Text>
          ) : (
            <BarChart
              h={200}
              data={stats.by_category}
              dataKey="category"
              series={[{ name: "count", color: "#8c7451" }]}
            />
          )}
        </Card>
        <Card padding={18} radius={14} withBorder>
          <Text fz={14.5} fw={600}>
            Cases per week
          </Text>
          <Text fz={12} c="#898781" mb={12}>
            Last 12 weeks
          </Text>
          {stats.weekly.length === 0 ? (
            <Text fz={13} c="#52514e" py={10} ta="center">
              Nothing in the last 12 weeks.
            </Text>
          ) : (
            <BarChart
              h={200}
              data={stats.weekly.map((w) => ({
                ...w,
                week: w.week.slice(5),
              }))}
              dataKey="week"
              series={[{ name: "count", color: "#c2a878" }]}
            />
          )}
        </Card>
      </Group>

      {stats.by_outcome.length > 0 && (
        <Card padding={18} radius={14} withBorder>
          <Text fz={14.5} fw={600} mb={10}>
            Outcomes
          </Text>
          <Group gap={10}>
            {stats.by_outcome.map((o) => (
              <Badge
                key={o.outcome}
                size="lg"
                radius="xl"
                variant="light"
                color={
                  o.outcome === "AUTO_RESOLVED"
                    ? "#1e7a43"
                    : o.outcome === "ESCALATED"
                      ? "#d03b3b"
                      : "#8c7451"
                }
              >
                {OUTCOME_LABELS[o.outcome] ?? o.outcome}: {o.count}
              </Badge>
            ))}
          </Group>
        </Card>
      )}
    </Stack>
  );
};

/** Admin-only view across every concierge's cases. */
const AllTicketsCard = () => {
  const [tickets, setTickets] = useState<GuruTicket[]>([]);
  const [total, setTotal] = useState(0);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const t = setTimeout(async () => {
      setLoading(true);
      const res = await listAllTickets({
        page: 1,
        limit: 25,
        ...(search.trim() ? { search: search.trim() } : {}),
      });
      if (res.success && res.data) {
        setTickets(res.data.tickets);
        setTotal(res.data.total);
      }
      setLoading(false);
    }, search ? 350 : 0);
    return () => clearTimeout(t);
  }, [search]);

  return (
    <Card padding={18} radius={14} withBorder>
      <Group justify="space-between" mb={2}>
        <Group gap={8}>
          <IconTicket size={17} color="#8c7451" />
          <Text fz={14.5} fw={600}>
            All tickets
          </Text>
        </Group>
        <TextInput
          size="xs"
          radius="xl"
          leftSection={<IconSearch size={13} color="#898781" />}
          placeholder="Search…"
          value={search}
          onChange={(e) => setSearch(e.currentTarget.value)}
          w={220}
        />
      </Group>
      <Text fz={12} c="#898781" mb={12}>
        Every concierge's cases · {total} total
      </Text>
      {loading ? (
        <Group justify="center" py={20}>
          <Loader size="sm" color="#8c7451" />
        </Group>
      ) : tickets.length === 0 ? (
        <Text fz={13} c="#52514e" ta="center" py={14}>
          Nothing found.
        </Text>
      ) : (
        <Stack gap={6}>
          {tickets.map((t) => (
            <Group
              key={t.id}
              component={Link}
              {...{ to: `/admin/guru/tickets/${t.reference}` }}
              px={12}
              py={9}
              gap={10}
              wrap="nowrap"
              style={{
                background: "#faf8f4",
                borderRadius: 10,
                border: "1px solid rgba(11,11,11,.06)",
                textDecoration: "none",
                color: "inherit",
              }}
            >
              <Text ff="monospace" fz={12} c="#8c7451" style={{ flex: "none" }}>
                {t.reference}
              </Text>
              <Badge
                size="xs"
                radius="xl"
                variant="light"
                color={
                  t.status === "RESOLVED"
                    ? "#1e7a43"
                    : t.status === "ESCALATED"
                      ? "#d03b3b"
                      : "#8c7451"
                }
                style={{ flex: "none" }}
              >
                {t.status}
              </Badge>
              <Text fz={12.5} lineClamp={1} style={{ flex: 1 }}>
                {t.summary || t.category || "New case"}
              </Text>
              <Text fz={11.5} c="#898781" style={{ flex: "none" }}>
                {t.concierge_email}
              </Text>
            </Group>
          ))}
        </Stack>
      )}
    </Card>
  );
};

/** Staggered design-system entrance for admin sections. */
const Rise = ({
  index,
  children,
}: {
  index: number;
  children: React.ReactNode;
}) => {
  const reducedMotion = useReducedMotion();
  return (
    <motion.div
      initial={reducedMotion ? false : { opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.45, delay: index * 0.07, ease: [0.2, 0.7, 0.2, 1] }}
    >
      {children}
    </motion.div>
  );
};

const GuruAdminClientPage = () => {
  const { isSuperAdmin } = useRoleAccess();
  const superAdmin = isSuperAdmin();

  return (
    <Stack gap={14} maw={980} mx="auto">
      <Rise index={0}>
        <AnalyticsCards />
      </Rise>
      <Rise index={1}>
        <AllTicketsCard />
      </Rise>
      {superAdmin ? (
        <>
          <Rise index={2}>
            <AllowlistCard />
          </Rise>
          <Rise index={3}>
            <AuditCard />
          </Rise>
        </>
      ) : (
        <Text fz={12} c="#898781" ta="center">
          The edit allowlist and audit log are visible to super admins only.
        </Text>
      )}
    </Stack>
  );
};

export default GuruAdminClientPage;
