import {
  Badge,
  Box,
  Button,
  Group,
  Loader,
  SegmentedControl,
  Stack,
  Text,
  TextInput,
} from "@mantine/core";
import { IconMessagePlus, IconSearch, IconTicket } from "@tabler/icons-react";
import { motion, useReducedMotion } from "framer-motion";
import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router";
import { listMyTickets } from "@/lib/features/guru/query";
import type {
  GuruTicket,
  GuruTicketStatus,
} from "@/lib/features/guru/types";

const STATUS_META: Record<
  string,
  { color: string; wash: string; label: string }
> = {
  OPEN: { color: "#8c7451", wash: "#f6f1e8", label: "Open" },
  RESOLVED: { color: "#1e7a43", wash: "#e9f6ee", label: "Resolved" },
  ESCALATED: { color: "#d03b3b", wash: "#fdeceb", label: "Escalated" },
};

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

/** Concierge view: own cases only — the admin view lives under Admin. */
const GuruTicketsClientPage = () => {
  const [tickets, setTickets] = useState<GuruTicket[]>([]);
  const [status, setStatus] = useState<string>("all");
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const reducedMotion = useReducedMotion();

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    const res = await listMyTickets({
      page: 1,
      limit: 50,
      ...(status !== "all"
        ? { statuses: [status as GuruTicketStatus] }
        : {}),
      ...(search.trim() ? { search: search.trim() } : {}),
    });
    if (res.success && res.data) {
      setTickets(res.data.tickets);
    } else {
      setError(res.message || "Could not load your cases.");
    }
    setLoading(false);
  }, [status, search]);

  useEffect(() => {
    const t = setTimeout(() => void load(), search ? 350 : 0);
    return () => clearTimeout(t);
  }, [load, search]);

  return (
    <Stack gap={14} maw={900} mx="auto">
      <Group justify="space-between" gap={10} wrap="wrap">
        <Group gap={10} style={{ flex: 1 }} wrap="nowrap">
          <TextInput
            radius="xl"
            leftSection={<IconSearch size={15} color="#898781" />}
            placeholder="Search reference, member or summary…"
            value={search}
            onChange={(e) => setSearch(e.currentTarget.value)}
            style={{ flex: 1, maxWidth: 380 }}
          />
          <SegmentedControl
            size="xs"
            radius="xl"
            value={status}
            onChange={setStatus}
            data={[
              { label: "All", value: "all" },
              { label: "Open", value: "OPEN" },
              { label: "Resolved", value: "RESOLVED" },
              { label: "Escalated", value: "ESCALATED" },
            ]}
          />
        </Group>
        <Button
          component={Link}
          to="/admin/guru/chat"
          size="sm"
          radius="xl"
          color="#0d0c0a"
          leftSection={<IconMessagePlus size={15} />}
        >
          New chat
        </Button>
      </Group>

      {loading && (
        <Group justify="center" py={70}>
          <Loader size="sm" color="#8c7451" />
          <Text fz={13} c="#52514e">
            Loading your cases…
          </Text>
        </Group>
      )}

      {!loading && error && (
        <Box
          p={14}
          style={{
            background: "#fdeceb",
            border: "1px solid #f3c6c4",
            borderRadius: 12,
          }}
        >
          <Text fz={13} c="#7a1f1f">
            <b>Couldn't load your cases.</b> {error}{" "}
            <Text
              component="span"
              fz={12.5}
              c="#8c7451"
              td="underline"
              style={{ cursor: "pointer" }}
              onClick={() => void load()}
            >
              Try again
            </Text>
          </Text>
        </Box>
      )}

      {!loading && !error && tickets.length === 0 && (
        <Box
          py={50}
          px={20}
          ta="center"
          style={{
            background: "#fff",
            borderRadius: 14,
            border: "1px dashed #c3c2b7",
          }}
        >
          <Text ff="serif" fz={24} fw={600} c="#0b0b0b">
            {search || status !== "all"
              ? "Nothing matches"
              : "No cases yet"}
          </Text>
          <Text fz={13} c="#52514e" mt={6}>
            {search || status !== "all"
              ? "Try a different search or filter."
              : "Start a chat with the Guru and your cases will appear here."}
          </Text>
        </Box>
      )}

      <Stack gap={8}>
        {!loading &&
          tickets.map((t, i) => {
            const meta = STATUS_META[t.status] ?? STATUS_META.OPEN;
            return (
              <motion.div
                key={t.id}
                initial={reducedMotion ? false : { opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{
                  duration: 0.4,
                  delay: Math.min(i, 12) * 0.05,
                  ease: [0.2, 0.7, 0.2, 1],
                }}
              >
                <Box
                  component={Link}
                  to={`/admin/guru/tickets/${t.reference}`}
                  px={16}
                  py={12}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 14,
                    background: "#fff",
                    border: "1px solid rgba(11,11,11,.07)",
                    borderRadius: 12,
                    textDecoration: "none",
                    color: "inherit",
                    transition:
                      "border-color .15s, box-shadow .15s, transform .15s",
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.borderColor = "#8c7451";
                    e.currentTarget.style.boxShadow =
                      "0 6px 18px #0d0c0a12";
                    e.currentTarget.style.transform = "translateY(-1px)";
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.borderColor =
                      "rgba(11,11,11,.07)";
                    e.currentTarget.style.boxShadow = "none";
                    e.currentTarget.style.transform = "none";
                  }}
                >
                  <Box
                    w={38}
                    h={38}
                    style={{
                      flex: "none",
                      borderRadius: 10,
                      background: meta.wash,
                      color: meta.color,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                    }}
                  >
                    <IconTicket size={18} />
                  </Box>
                  <Box miw={0} style={{ flex: 1 }}>
                    <Group gap={8} wrap="nowrap">
                      <Text ff="monospace" fz={12} c="#8c7451">
                        {t.reference}
                      </Text>
                      {t.category && (
                        <Text
                          fz={11.5}
                          c="#52514e"
                          px={8}
                          style={{
                            background: "#f6f4ef",
                            borderRadius: 7,
                            flex: "none",
                          }}
                        >
                          {t.category}
                        </Text>
                      )}
                      {t.member_ref && (
                        <Text fz={11.5} c="#898781" style={{ flex: "none" }}>
                          member {t.member_ref}
                        </Text>
                      )}
                    </Group>
                    <Text fz={13.5} fw={600} lineClamp={1} mt={2}>
                      {t.summary || "No summary yet"}
                    </Text>
                  </Box>
                  <Stack gap={4} align="flex-end" style={{ flex: "none" }}>
                    <Badge
                      size="xs"
                      radius="xl"
                      variant="light"
                      color={meta.color}
                    >
                      {meta.label}
                    </Badge>
                    <Text fz={11.5} c="#898781">
                      {fmt(t.created_at)}
                    </Text>
                  </Stack>
                </Box>
              </motion.div>
            );
          })}
      </Stack>
    </Stack>
  );
};

export default GuruTicketsClientPage;
