import {
  Badge,
  Box,
  Button,
  Card,
  Group,
  Loader,
  Stack,
  Text,
} from "@mantine/core";
import { IconMessageCircle } from "@tabler/icons-react";
import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router";
import {
  getTicket,
  getTicketUpdates,
  type GuruTicketUpdate,
} from "@/lib/features/guru/query";
import type {
  GuruPendingAction,
  GuruTicket,
} from "@/lib/features/guru/types";

const GuruTicketDetailClientPage = ({
  reference,
  isAdmin,
}: {
  reference: string;
  isAdmin: boolean;
}) => {
  const [ticket, setTicket] = useState<GuruTicket | null>(null);
  const [actions, setActions] = useState<GuruPendingAction[]>([]);
  const [updates, setUpdates] = useState<GuruTicketUpdate[] | null>(null);
  const [taskStatus, setTaskStatus] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [closing, setClosing] = useState(false);

  const doClose = async () => {
    setClosing(true);
    const { closeTicket } = await import("@/lib/features/guru/action");
    const { notifications } = await import("@mantine/notifications");
    const res = await closeTicket(reference);
    if (res.success) {
      notifications.show({
        message: `${reference} closed — ClickUp and the member log are updated.`,
      });
      setTicket((t) => (t ? { ...t, status: "RESOLVED" } : t));
    } else {
      notifications.show({
        color: "red",
        message: res.message || "Could not close the case.",
      });
    }
    setClosing(false);
  };

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    // Owners read via /tickets; a 404 there for an admin falls through to the
    // admin endpoint (admins may open tickets they don't own).
    let admin = false;
    let res = await getTicket(reference);
    if (!res.success && isAdmin) {
      admin = true;
      res = await getTicket(reference, { admin: true });
    }
    if (res.success && res.data) {
      setTicket(res.data.ticket);
      setActions(res.data.actions);
      if (res.data.ticket.clickup_task_id) {
        void getTicketUpdates(reference, { admin }).then((u) => {
          if (u.success && u.data) {
            setUpdates(u.data.updates);
            setTaskStatus(u.data.task_status?.status ?? null);
          }
        });
      }
    } else {
      setError(res.message || "Ticket not found.");
    }
    setLoading(false);
  }, [reference, isAdmin]);

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

  if (loading)
    return (
      <Group justify="center" py={60}>
        <Loader size="sm" color="#8c7451" />
        <Text fz={13} c="#52514e">
          Loading the ticket…
        </Text>
      </Group>
    );

  if (error || !ticket)
    return (
      <Box
        p={14}
        style={{
          background: "#fdeceb",
          border: "1px solid #f3c6c4",
          borderRadius: 12,
        }}
      >
        <Text fz={13} c="#7a1f1f">
          <b>Couldn't open this ticket.</b> {error}
        </Text>
      </Box>
    );

  return (
    <Stack gap={14}>
      <Card padding={18} radius={14} withBorder>
        <Group gap={10}>
          <Text ff="monospace" fz={13} c="#8c7451">
            {ticket.reference}
          </Text>
          <Badge size="sm" radius="xl" variant="light">
            {ticket.status}
          </Badge>
          {ticket.category && (
            <Text fz={12} c="#898781">
              {ticket.category}
            </Text>
          )}
        </Group>
        <Text fz={14} mt={8}>
          {ticket.summary || "No summary yet."}
        </Text>
        <Group justify="space-between" mt={6}>
          <Text fz={12} c="#898781">
            Opened by {ticket.concierge_email} ·{" "}
            {new Date(ticket.created_at).toLocaleString("en-GB")}
            {ticket.clickup_task_id && (
              <>
                {" "}
                · Case #{ticket.clickup_task_id}
                {taskStatus && <> · team status: {taskStatus}</>}
              </>
            )}
          </Text>
          <Group gap={8}>
            {ticket.status === "OPEN" && (
              <Button
                size="xs"
                radius="xl"
                variant="default"
                loading={closing}
                onClick={() => void doClose()}
              >
                Close case
              </Button>
            )}
            <Button
              component={Link}
              to={`/admin/guru/chat?ticket=${ticket.reference}`}
              size="xs"
              radius="xl"
              color="#0d0c0a"
              leftSection={<IconMessageCircle size={14} />}
            >
              Continue this chat
            </Button>
          </Group>
        </Group>
      </Card>

      {updates && updates.length > 0 && (
        <Card padding={18} radius={14} withBorder>
          <Text fz={14.5} fw={600} mb={2}>
            Case updates
          </Text>
          <Text fz={12} c="#898781" mb={10}>
            Conversation log and team updates, newest first
          </Text>
          <Stack gap={10}>
            {updates.map((u, i) => (
              <Box
                key={i}
                p={10}
                style={{
                  background: "#faf8f4",
                  borderRadius: 10,
                  border: "1px solid rgba(11,11,11,.06)",
                }}
              >
                <Text fz={11.5} c="#898781">
                  {u.by}
                  {u.at &&
                    ` · ${new Date(u.at).toLocaleString("en-GB", {
                      day: "numeric",
                      month: "short",
                      hour: "2-digit",
                      minute: "2-digit",
                    })}`}
                </Text>
                <Text fz={12.5} mt={4} style={{ whiteSpace: "pre-wrap" }} lineClamp={12}>
                  {u.text}
                </Text>
              </Box>
            ))}
          </Stack>
        </Card>
      )}

      {actions.length > 0 && (
        <Card padding={18} radius={14} withBorder>
          <Text fz={14.5} fw={600} mb={10}>
            Proposed actions
          </Text>
          <Stack gap={8}>
            {actions.map((a) => (
              <Group key={a.id} justify="space-between" wrap="nowrap">
                <Text fz={13} miw={0} lineClamp={1}>
                  {a.summary}
                </Text>
                <Badge size="xs" radius="xl" variant="light">
                  {a.status}
                </Badge>
              </Group>
            ))}
          </Stack>
        </Card>
      )}
    </Stack>
  );
};

export default GuruTicketDetailClientPage;
