import {
  ActionIcon,
  Badge,
  Box,
  Button,
  Group,
  Loader,
  ScrollArea,
  Stack,
  Text,
  Textarea,
  Tooltip,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import {
  IconArrowUp,
  IconCircleCheck,
  IconMessagePlus,
  IconPaperclip,
  IconPlayerStop,
  IconTicket,
} from "@tabler/icons-react";
import { ConversationProvider, useConversation } from "@elevenlabs/react";
import { motion, useReducedMotion } from "framer-motion";
import { useCallback, useEffect, useRef, useState } from "react";
import { Link, useSearchParams } from "react-router";
import {
  bindConversation,
  closeTicket,
  confirmGuruAction,
  createTicket,
  declineGuruAction,
  startChatSession,
  uploadAttachment,
} from "@/lib/features/guru/action";
import {
  getTicketTranscript,
  listMyTickets,
  listTicketActions,
  type GuruTranscriptConversation,
} from "@/lib/features/guru/query";
import type {
  GuruPendingAction,
  GuruTicket,
} from "@/lib/features/guru/types";

type ChatMessage = { id: number; role: "user" | "agent"; text: string };

const STATUS_DOT: Record<string, string> = {
  OPEN: "#8c7451",
  RESOLVED: "#1e7a43",
  ESCALATED: "#d03b3b",
};

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

const bubbleStyle = (role: "user" | "agent") =>
  role === "user"
    ? {
        background: "#0d0c0a",
        color: "#c2a878",
        borderRadius: "14px 14px 4px 14px",
      }
    : {
        background: "#fff",
        color: "#0b0b0b",
        border: "1px solid rgba(11,11,11,.08)",
        borderRadius: "14px 14px 14px 4px",
      };

/**
 * Messenger-style chat. Selecting a past case loads its history into the
 * SAME pane, scrolled to the last message; typing just continues the case —
 * the session connects automatically on the first keystroke. No modes.
 */
const GuruChat = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const reducedMotion = useReducedMotion();

  // sidebar
  const [tickets, setTickets] = useState<GuruTicket[]>([]);
  const [ticketsLoading, setTicketsLoading] = useState(true);

  // active case
  const [ticketRef, setTicketRef] = useState<string | null>(null);
  const [history, setHistory] = useState<GuruTranscriptConversation[] | null>(
    null,
  );
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [draft, setDraft] = useState("");
  const [connecting, setConnecting] = useState(false);
  const [awaitingAgent, setAwaitingAgent] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // confirmation cards
  const [pendingActions, setPendingActions] = useState<GuruPendingAction[]>([]);
  const [cardBusy, setCardBusy] = useState<string | null>(null);
  const [cardNotes, setCardNotes] = useState<Record<string, string>>({});
  const [closing, setClosing] = useState(false);
  const [uploading, setUploading] = useState(false);

  const nextId = useRef(1);
  const ticketRefBox = useRef<string | null>(null);
  const viewportRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const append = (role: ChatMessage["role"], text: string) =>
    setMessages((m) => [...m, { id: nextId.current++, role, text }]);

  const refreshTickets = useCallback(async () => {
    const res = await listMyTickets({ page: 1, limit: 30 });
    if (res.success && res.data) setTickets(res.data.tickets);
    setTicketsLoading(false);
  }, []);

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

  const conversation = useConversation({
    textOnly: true,
    onConnect: ({ conversationId }) => {
      setConnecting(false);
      const ref = ticketRefBox.current;
      if (ref) {
        void bindConversation(ref, conversationId).then((res) => {
          if (!res.success)
            setError(res.message || "Could not link the chat to its ticket.");
        });
      }
    },
    onMessage: ({ message, role }) => {
      if (role === "agent") {
        setAwaitingAgent(false);
        append("agent", message);
      }
    },
    onError: (msg) => {
      setConnecting(false);
      setAwaitingAgent(false);
      setError(typeof msg === "string" ? msg : "The chat connection failed.");
    },
    onDisconnect: () => {
      setAwaitingAgent(false);
      setConnecting(false);
    },
  });
  const connected = conversation.status === "connected";

  const scrollToEnd = useCallback(
    (smooth = true) =>
      viewportRef.current?.scrollTo({
        top: viewportRef.current.scrollHeight,
        behavior: smooth && !reducedMotion ? "smooth" : "auto",
      }),
    [reducedMotion],
  );

  useEffect(() => {
    scrollToEnd();
  }, [messages.length, awaitingAgent, pendingActions.length, scrollToEnd]);

  // History loaded → jump straight to the last message.
  useEffect(() => {
    if (history !== null) requestAnimationFrame(() => scrollToEnd(false));
  }, [history, scrollToEnd]);

  // Poll confirmation cards while connected.
  useEffect(() => {
    if (!connected || !ticketRef) return;
    let stop = false;
    const poll = async () => {
      const res = await listTicketActions(ticketRef);
      if (!stop && res.success && res.data)
        setPendingActions(
          res.data.actions.filter((a) => a.status === "PENDING"),
        );
    };
    void poll();
    const t = setInterval(poll, 4000);
    return () => {
      stop = true;
      clearInterval(t);
    };
  }, [connected, ticketRef]);

  const resetPane = () => {
    setMessages([]);
    setCardNotes({});
    setPendingActions([]);
    setError(null);
    setDraft("");
  };

  /** Connect the active case's session (new conversation each time). */
  const connect = useCallback(
    async (ref: string) => {
      if (connecting) return;
      setConnecting(true);
      setError(null);
      try {
        const session = await startChatSession(ref);
        if (!session.success || !session.data)
          throw new Error(session.message || "Could not start the chat.");
        conversation.startSession({
          signedUrl: session.data.signed_url,
          connectionType: "websocket",
          textOnly: true,
          dynamicVariables: session.data.dynamic_variables,
        });
      } catch (e) {
        setConnecting(false);
        setError(e instanceof Error ? e.message : "Could not start the chat.");
      }
    },
    [connecting, conversation],
  );

  /** New case: fresh ticket + connect immediately (greeting arrives first). */
  const openNewChat = useCallback(async () => {
    if (connected) conversation.endSession();
    resetPane();
    setHistory(null);
    setTicketRef(null);
    try {
      const created = await createTicket({});
      if (!created.success || !created.data)
        throw new Error(created.message || "Could not open a ticket.");
      const ref = created.data.ticket.reference;
      setTicketRef(ref);
      ticketRefBox.current = ref;
      setHistory([]);
      await connect(ref);
      void refreshTickets();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Could not start the chat.");
    }
  }, [connected, conversation, connect, refreshTickets]);

  /** Select a past case: load history, land at the last message. */
  const selectTicket = useCallback(
    async (ref: string, autoConnect = false) => {
      if (ref === ticketRefBox.current && (connected || connecting)) return;
      if (connected) conversation.endSession();
      resetPane();
      setTicketRef(ref);
      ticketRefBox.current = ref;
      setHistory(null);
      const res = await getTicketTranscript(ref);
      // Ignore stale loads if the user clicked elsewhere meanwhile.
      if (ticketRefBox.current !== ref) return;
      setHistory(res.success && res.data ? res.data.conversations : []);
      if (autoConnect) void connect(ref);
    },
    [connected, connecting, conversation, connect],
  );

  // ?ticket=GRU-x deep link (from the ticket page).
  useEffect(() => {
    const ref = searchParams.get("ticket");
    if (ref) {
      setSearchParams({}, { replace: true });
      void selectTicket(ref, true);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /** Typing continues the case: connect lazily on first input. */
  const ensureConnected = useCallback(() => {
    if (ticketRef && !connected && !connecting) void connect(ticketRef);
  }, [ticketRef, connected, connecting, connect]);

  const send = useCallback(() => {
    const text = draft.trim();
    if (!text || !connected) return;
    setDraft("");
    append("user", text);
    conversation.sendUserMessage(text);
    setAwaitingAgent(true);
  }, [draft, connected, conversation]);

  const handleAttachment = useCallback(
    async (file: File) => {
      if (!ticketRef) return;
      setUploading(true);
      const res = await uploadAttachment(ticketRef, file);
      if (res.success && res.data) {
        setCardNotes((n) => ({
          ...n,
          [`att-${Date.now()}`]: `Done — screenshot "${res.data!.title}" attached to the case.`,
        }));
        // Give the agent the context without triggering a response.
        if (connected)
          conversation.sendContextualUpdate(
            `The concierge attached a screenshot named "${res.data.title}" to the ClickUp task for this case.`,
          );
      } else {
        notifications.show({
          color: "red",
          message: res.message || "Could not attach the file.",
        });
      }
      setUploading(false);
    },
    [ticketRef, connected, conversation],
  );

  const endChat = useCallback(() => {
    conversation.endSession();
    setAwaitingAgent(false);
    void refreshTickets();
  }, [conversation, refreshTickets]);

  const activeTicket = tickets.find((t) => t.reference === ticketRef);

  const handleClose = useCallback(async () => {
    if (!ticketRef) return;
    setClosing(true);
    if (connected) conversation.endSession();
    const res = await closeTicket(ticketRef);
    if (res.success) {
      notifications.show({
        message: `${ticketRef} closed — ClickUp and the member log are updated.`,
      });
      void refreshTickets();
    } else {
      notifications.show({
        color: "red",
        message: res.message || "Could not close the case.",
      });
    }
    setClosing(false);
  }, [ticketRef, connected, conversation, refreshTickets]);

  const bubble = (m: ChatMessage) => (
    <motion.div
      key={m.id}
      initial={reducedMotion ? false : { opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.35, ease: [0.2, 0.7, 0.2, 1] }}
      style={{
        display: "flex",
        justifyContent: m.role === "user" ? "flex-end" : "flex-start",
      }}
    >
      <Box px={16} py={10} maw="72%" style={bubbleStyle(m.role)}>
        <Text fz={13.5} style={{ whiteSpace: "pre-wrap" }}>
          {m.text}
        </Text>
      </Box>
    </motion.div>
  );

  return (
    <Group
      align="stretch"
      gap={0}
      wrap="nowrap"
      style={{
        height: "calc(100vh - 170px)",
        minHeight: 480,
        background: "#faf8f4",
        border: "1px solid rgba(11,11,11,.08)",
        borderRadius: 14,
        overflow: "hidden",
      }}
    >
      {/* ---- sidebar ---- */}
      <Stack
        gap={0}
        w={264}
        miw={264}
        style={{
          borderRight: "1px solid rgba(11,11,11,.08)",
          background: "#fff",
          height: "100%",
        }}
      >
        <Box p={12}>
          <Button
            fullWidth
            radius="xl"
            color="#0d0c0a"
            leftSection={<IconMessagePlus size={16} />}
            onClick={() => void openNewChat()}
            loading={connecting && history?.length === 0 && messages.length === 0}
          >
            New chat
          </Button>
        </Box>
        <Text fz={11} tt="uppercase" lts=".08em" c="#898781" px={16} pb={6}>
          My cases
        </Text>
        <ScrollArea style={{ flex: 1 }}>
          <Stack gap={2} px={8} pb={8}>
            {ticketsLoading && (
              <Group justify="center" py={20}>
                <Loader size="xs" color="#8c7451" />
              </Group>
            )}
            {!ticketsLoading && tickets.length === 0 && (
              <Text fz={12.5} c="#898781" ta="center" py={16}>
                No cases yet
              </Text>
            )}
            {tickets.map((t) => {
              const active = t.reference === ticketRef;
              return (
                <Box
                  key={t.id}
                  px={10}
                  py={8}
                  onClick={() => void selectTicket(t.reference)}
                  style={{
                    cursor: "pointer",
                    borderRadius: 10,
                    background: active ? "#f6f1e8" : "transparent",
                    border: active
                      ? "1px solid #c2a878"
                      : "1px solid transparent",
                  }}
                >
                  <Group gap={6} wrap="nowrap">
                    <Box
                      w={7}
                      h={7}
                      style={{
                        borderRadius: "50%",
                        flex: "none",
                        background: STATUS_DOT[t.status] ?? "#8c7451",
                      }}
                    />
                    <Text ff="monospace" fz={11.5} c="#8c7451">
                      {t.reference}
                    </Text>
                    <Text fz={11} c="#898781" ml="auto" style={{ flex: "none" }}>
                      {fmtShort(t.created_at)}
                    </Text>
                  </Group>
                  <Text fz={12.5} lineClamp={1} mt={2} c="#0b0b0b">
                    {t.summary || t.category || "New case"}
                  </Text>
                </Box>
              );
            })}
          </Stack>
        </ScrollArea>
        <Box p={10} style={{ borderTop: "1px solid rgba(11,11,11,.06)" }}>
          <Text
            component={Link}
            to="/admin/guru/tickets"
            fz={12}
            c="#8c7451"
            td="underline"
          >
            All my tickets →
          </Text>
        </Box>
      </Stack>

      {/* ---- main pane ---- */}
      <Stack gap={0} style={{ flex: 1, height: "100%", minWidth: 0 }}>
        {/* header */}
        <Group
          px={16}
          py={10}
          justify="space-between"
          style={{
            borderBottom: "1px solid rgba(11,11,11,.08)",
            background: "#fff",
          }}
        >
          <Group gap={8}>
            {ticketRef ? (
              <>
                <Text ff="monospace" fz={12.5} c="#8c7451">
                  {ticketRef}
                </Text>
                <Badge size="xs" radius="xl" variant="light" color="#8c7451">
                  {connected ? "Live" : connecting ? "Connecting" : "Paused"}
                </Badge>
                {activeTicket?.category && (
                  <Text fz={12} c="#898781">
                    {activeTicket.category}
                  </Text>
                )}
              </>
            ) : (
              <Text fz={13.5} fw={600}>
                Karma Subito AI Guru
              </Text>
            )}
          </Group>
          <Group gap={8}>
            {ticketRef && (
              <Tooltip label="Open the full ticket">
                <ActionIcon
                  component={Link}
                  to={`/admin/guru/tickets/${ticketRef}`}
                  variant="subtle"
                  radius="xl"
                  color="#8c7451"
                  aria-label="Open the full ticket"
                >
                  <IconTicket size={16} />
                </ActionIcon>
              </Tooltip>
            )}
            {ticketRef && activeTicket?.status === "OPEN" && (
              <Button
                size="compact-xs"
                radius="xl"
                variant="default"
                leftSection={<IconCircleCheck size={13} color="#1e7a43" />}
                loading={closing}
                onClick={() => void handleClose()}
              >
                Close case
              </Button>
            )}
            {connected && (
              <Button
                size="compact-xs"
                radius="xl"
                variant="default"
                leftSection={<IconPlayerStop size={13} />}
                onClick={endChat}
              >
                End chat
              </Button>
            )}
          </Group>
        </Group>

        {/* body */}
        <ScrollArea style={{ flex: 1 }} viewportRef={viewportRef}>
          <Stack gap={10} p={20} justify="flex-end" mih="100%">
            {!ticketRef && (
              <Box ta="center" py={80}>
                <Text ff="serif" fz={26} fw={600} c="#0b0b0b">
                  Member trouble? Ask the Guru.
                </Text>
                <Text fz={13} c="#52514e" mt={6} maw={420} mx="auto">
                  Start a new chat and describe the issue — include the
                  member's email or number and which app they use. Or pick an
                  earlier case on the left to continue it.
                </Text>
                <Button
                  mt={16}
                  radius="xl"
                  color="#0d0c0a"
                  leftSection={<IconMessagePlus size={16} />}
                  onClick={() => void openNewChat()}
                >
                  New chat
                </Button>
              </Box>
            )}

            {ticketRef && history === null && (
              <Group justify="center" py={40}>
                <Loader size="sm" color="#8c7451" />
                <Text fz={12.5} c="#52514e">
                  Loading the conversation…
                </Text>
              </Group>
            )}

            {history?.map((conv) => (
              <Stack key={conv.conversation_id} gap={10}>
                <Group gap={8} justify="center">
                  <Box h={1} style={{ flex: 1, background: "#ebe8e1" }} />
                  <Text fz={11} c="#898781">
                    {conv.started_at
                      ? new Date(conv.started_at).toLocaleString("en-GB", {
                          day: "numeric",
                          month: "short",
                          hour: "2-digit",
                          minute: "2-digit",
                        })
                      : "Earlier conversation"}
                    {conv.unavailable && " · transcript unavailable"}
                  </Text>
                  <Box h={1} style={{ flex: 1, background: "#ebe8e1" }} />
                </Group>
                {conv.turns.map((t, i) => (
                  <Box
                    key={i}
                    style={{
                      display: "flex",
                      justifyContent:
                        t.role === "user" ? "flex-end" : "flex-start",
                    }}
                  >
                    <Box px={16} py={10} maw="72%" style={bubbleStyle(t.role)}>
                      <Text fz={13.5} style={{ whiteSpace: "pre-wrap" }}>
                        {t.text}
                      </Text>
                    </Box>
                  </Box>
                ))}
              </Stack>
            ))}

            {connecting && messages.length === 0 && (
              <Group justify="center" py={14}>
                <Loader size="sm" color="#8c7451" />
                <Text fz={12.5} c="#52514e">
                  Waking the Guru…
                </Text>
              </Group>
            )}

            {messages.map(bubble)}

            {Object.entries(cardNotes).map(([id, note]) => (
              <Box
                key={id}
                p={10}
                style={{
                  background: note.startsWith("Done")
                    ? "#e9f6ee"
                    : note.startsWith("Cancelled")
                      ? "#f6f1e8"
                      : "#fdeceb",
                  borderRadius: 10,
                  border: "1px solid rgba(11,11,11,.08)",
                }}
              >
                <Text fz={12.5} style={{ wordBreak: "break-word" }}>
                  {note}
                </Text>
              </Box>
            ))}

            {pendingActions.map((a) => (
              <Box
                key={a.id}
                p={14}
                style={{
                  background: "#fff",
                  border: "1px solid #8c7451",
                  borderRadius: 14,
                }}
              >
                <Text fz={11} tt="uppercase" lts=".1em" c="#8c7451" fw={700}>
                  Confirmation needed
                </Text>
                <Text fz={13.5} fw={600} mt={6}>
                  {a.summary}
                </Text>
                <Text fz={12} c="#52514e" mt={2}>
                  Member {a.member_ref} ·{" "}
                  {a.action_type.replaceAll("_", " ").toLowerCase()}
                </Text>
                <Group gap={8} mt={10}>
                  <Button
                    size="xs"
                    radius="xl"
                    color="#0d0c0a"
                    loading={cardBusy === a.id}
                    onClick={() => void resolveCard(a, true)}
                  >
                    Confirm
                  </Button>
                  <Button
                    size="xs"
                    radius="xl"
                    variant="default"
                    disabled={cardBusy === a.id}
                    onClick={() => void resolveCard(a, false)}
                  >
                    Cancel
                  </Button>
                </Group>
              </Box>
            ))}

            {awaitingAgent && (
              <Group gap={8} pl={4}>
                <Loader size={14} color="#8c7451" type="dots" />
                <Text fz={12} c="#898781">
                  The Guru is thinking…
                </Text>
              </Group>
            )}
          </Stack>
        </ScrollArea>

        {/* error + input */}
        {error && (
          <Box
            mx={16}
            mb={8}
            p={10}
            style={{
              background: "#fdeceb",
              border: "1px solid #f3c6c4",
              borderRadius: 10,
            }}
          >
            <Text fz={12.5} c="#7a1f1f">
              <b>Something went wrong.</b> {error}{" "}
              <Text
                component="span"
                fz={12}
                td="underline"
                style={{ cursor: "pointer" }}
                onClick={() => ticketRef && void connect(ticketRef)}
              >
                Reconnect
              </Text>
            </Text>
          </Box>
        )}
        <Group
          p={12}
          gap={10}
          style={{
            borderTop: "1px solid rgba(11,11,11,.08)",
            background: "#fff",
          }}
          wrap="nowrap"
        >
          <input
            ref={fileInputRef}
            type="file"
            accept="image/png,image/jpeg,image/webp,image/gif,application/pdf"
            hidden
            onChange={(e) => {
              const f = e.currentTarget.files?.[0];
              e.currentTarget.value = "";
              if (f) void handleAttachment(f);
            }}
          />
          <Tooltip label="Attach a screenshot (goes on the case)">
            <ActionIcon
              size={38}
              radius="xl"
              variant="default"
              disabled={!ticketRef || uploading}
              loading={uploading}
              onClick={() => fileInputRef.current?.click()}
              aria-label="Attach a screenshot"
            >
              <IconPaperclip size={17} />
            </ActionIcon>
          </Tooltip>
          <Textarea
            autosize
            minRows={1}
            maxRows={5}
            radius="xl"
            placeholder={
              !ticketRef
                ? "Press “New chat” to begin"
                : connected
                  ? "Type your message…"
                  : connecting
                    ? "Connecting…"
                    : "Type to continue this case — the Guru connects automatically"
            }
            value={draft}
            disabled={!ticketRef}
            onFocus={ensureConnected}
            onChange={(e) => {
              setDraft(e.currentTarget.value);
              ensureConnected();
            }}
            onKeyDown={(e) => {
              if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                send();
              }
            }}
            style={{ flex: 1 }}
          />
          <ActionIcon
            size={38}
            radius="xl"
            variant="filled"
            color="#0d0c0a"
            onClick={send}
            disabled={!draft.trim() || !connected}
            aria-label="Send message"
          >
            <IconArrowUp size={18} />
          </ActionIcon>
        </Group>
      </Stack>
    </Group>
  );

  async function resolveCard(action: GuruPendingAction, confirm: boolean) {
    setCardBusy(action.id);
    const res = confirm
      ? await confirmGuruAction(action.id)
      : await declineGuruAction(action.id);
    let note: string;
    if (confirm && res.success) {
      const otp = (res.data as { one_time_password?: string } | undefined)
        ?.one_time_password;
      note = otp
        ? `Done. One-time password (shown only once): ${otp}`
        : "Done — the change was applied.";
    } else if (!confirm && res.success) {
      note = "Cancelled — nothing was changed.";
    } else {
      note = res.message || "The action could not be completed.";
    }
    setCardNotes((n) => ({ ...n, [action.id]: note }));
    setPendingActions((list) => list.filter((a) => a.id !== action.id));
    setCardBusy(null);
    if (connected) {
      conversation.sendUserMessage(
        confirm
          ? res.success
            ? `I confirmed the action: ${action.summary} It was applied successfully.`
            : `I tried to confirm the action but it failed: ${res.message || "unknown error"}`
          : `I declined the action: ${action.summary}`,
      );
      setAwaitingAgent(true);
    }
  }
};

const GuruChatClientPage = () => (
  <ConversationProvider>
    <GuruChat />
  </ConversationProvider>
);

export default GuruChatClientPage;
