"use client";

import {
  Alert,
  Button,
  Card,
  Group,
  Radio,
  Select,
  Stack,
  Text,
  Textarea,
  TextInput,
  Title,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { IconFlagPlus, IconSearch } from "@tabler/icons-react";
import { useState } from "react";
import { useNavigate } from "react-router";
import { getConversation } from "@/lib/features/kevo/query";
import { createManualFlag } from "@/lib/features/kevo/action";
import type {
  KevoConversation,
  KevoFlagCategory,
} from "@/lib/features/kevo/types";
import { CATEGORY_LABEL, KARMA } from "../_components/kevo.constants";

/**
 * Manual flagging: paste a conversation id, pick the member turn that went
 * wrong, categorise it. The agent's reply (the next Kevo turn) is attached
 * automatically.
 */
export default function KevoManualFlagClientPage() {
  const navigate = useNavigate();
  const [conversationId, setConversationId] = useState("");
  const [conversation, setConversation] = useState<KevoConversation | null>(
    null,
  );
  const [loadError, setLoadError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [selectedTurn, setSelectedTurn] = useState<string | null>(null);
  const [category, setCategory] = useState<string>("KNOWLEDGE_GAP");
  const [entity, setEntity] = useState("");
  const [notesQuestion, setNotesQuestion] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const fetchConversation = async () => {
    const id = conversationId.trim();
    if (!id) return;
    setLoading(true);
    setLoadError(null);
    setConversation(null);
    setSelectedTurn(null);
    const res = await getConversation(id);
    if (res.success) setConversation(res.data);
    else setLoadError(res.message || "Conversation not found");
    setLoading(false);
  };

  const memberTurns =
    conversation?.turns
      .map((turn, index) => ({ turn, index }))
      .filter(({ turn }) => turn.role !== "agent" && turn.message) ?? [];

  const agentReplyFor = (index: number): string | undefined =>
    conversation?.turns
      .slice(index + 1)
      .find((t) => t.role === "agent" && t.message)?.message ?? undefined;

  const submit = async () => {
    if (!conversation) return;
    const turnIndex = selectedTurn ? Number(selectedTurn) : -1;
    const memberQuestion =
      turnIndex >= 0
        ? (conversation.turns[turnIndex]?.message ?? "")
        : notesQuestion.trim();
    if (!memberQuestion) {
      notifications.show({
        message: "Pick a message or describe the issue",
        color: "red",
      });
      return;
    }
    setSubmitting(true);
    const res = await createManualFlag({
      category: category as KevoFlagCategory,
      member_question: memberQuestion,
      agent_answer: turnIndex >= 0 ? agentReplyFor(turnIndex) : undefined,
      entity: entity.trim() || undefined,
      conversation_id: conversation.conversation_id,
    });
    setSubmitting(false);
    notifications.show({
      message: res.message,
      color: res.success ? "teal" : "red",
    });
    if (res.success) {
      navigate(`/admin/kevo/flags/${res.data.flag.reference}`);
    }
  };

  return (
    <Stack gap="lg" maw={860}>
      <div>
        <Title order={2}>Flag a conversation</Title>
        <Text c="dimmed" size="sm">
          Paste a conversation id from the ElevenLabs dashboard, pick the
          message that went wrong, and flag it for review.
        </Text>
      </div>

      <Card radius="lg" withBorder>
        <Group align="flex-end" wrap="wrap">
          <TextInput
            label="Conversation ID"
            placeholder="conv_…"
            value={conversationId}
            onChange={(e) => setConversationId(e.currentTarget.value)}
            style={{ flex: 1, minWidth: 260 }}
            ff="monospace"
          />
          <Button
            leftSection={<IconSearch size={16} />}
            variant="default"
            onClick={() => void fetchConversation()}
            loading={loading}
          >
            Load conversation
          </Button>
        </Group>
        {loadError && (
          <Alert color="red" variant="light" mt="sm">
            {loadError}
          </Alert>
        )}
      </Card>

      {conversation && (
        <Card radius="lg" withBorder>
          <Text fw={600} size="sm" mb={2}>
            Which member message is the problem?
          </Text>
          <Text c="dimmed" size="xs" mb="md">
            Kevo's reply right after it is attached automatically.
          </Text>
          {memberTurns.length === 0 ? (
            <Text c="dimmed" size="sm">
              No member messages in this conversation — describe the issue
              below instead.
            </Text>
          ) : (
            <Radio.Group value={selectedTurn} onChange={setSelectedTurn}>
              <Stack gap={8} mah={340} style={{ overflowY: "auto" }}>
                {memberTurns.map(({ turn, index }) => (
                  <Radio
                    key={index}
                    value={String(index)}
                    styles={{ label: { width: "100%" } }}
                    label={
                      <Stack gap={2}>
                        <Text size="sm">{turn.message}</Text>
                        {agentReplyFor(index) && (
                          <Text size="xs" c="dimmed" lineClamp={2}>
                            Kevo: {agentReplyFor(index)}
                          </Text>
                        )}
                      </Stack>
                    }
                  />
                ))}
              </Stack>
            </Radio.Group>
          )}
          {!selectedTurn && (
            <Textarea
              mt="sm"
              label="Or describe the issue"
              placeholder="What went wrong in this conversation…"
              autosize
              minRows={2}
              value={notesQuestion}
              onChange={(e) => setNotesQuestion(e.currentTarget.value)}
            />
          )}
        </Card>
      )}

      {conversation && (
        <Card radius="lg" withBorder>
          <Stack gap="sm">
            <Select
              label="Category"
              data={Object.entries(CATEGORY_LABEL).map(([value, label]) => ({
                value,
                label,
              }))}
              value={category}
              onChange={(v) => v && setCategory(v)}
              allowDeselect={false}
            />
            <TextInput
              label="Entity / topic"
              placeholder="Karma Beach"
              value={entity}
              onChange={(e) => setEntity(e.currentTarget.value)}
            />
            <Group justify="flex-end">
              <Button
                leftSection={<IconFlagPlus size={16} />}
                color={KARMA.black}
                onClick={() => void submit()}
                loading={submitting}
              >
                Create flag
              </Button>
            </Group>
          </Stack>
        </Card>
      )}
    </Stack>
  );
}
