"use client";

import {
  Alert,
  Anchor,
  Badge,
  Button,
  Card,
  Divider,
  Grid,
  Group,
  Loader,
  Modal,
  Select,
  Stack,
  TagsInput,
  Text,
  Textarea,
  TextInput,
  Timeline,
  Title,
  Tooltip,
} from "@mantine/core";
import { useForm } from "@mantine/form";
import { notifications } from "@mantine/notifications";
import {
  IconArrowLeft,
  IconBook2,
  IconCheck,
  IconCopy,
  IconExternalLink,
  IconMessage,
  IconPencil,
  IconSend,
  IconX,
} from "@tabler/icons-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Link } from "react-router";
import { getConversation, getFlag } from "@/lib/features/kevo/query";
import {
  approveKnowledge,
  createKnowledge,
  routeFlagToClickUp,
  updateFlag,
} from "@/lib/features/kevo/action";
import type {
  KevoConversation,
  KevoFlagDetail,
} from "@/lib/features/kevo/types";
import type { AccessScope } from "@/lib/features/types";
import {
  CategoryBadge,
  formatDate,
  KARMA,
  SOURCE_LABEL,
  StatusBadge,
  timeAgo,
} from "../../_components/kevo.constants";

const FieldRow = ({ label, value }: { label: string; value: string | null }) =>
  value ? (
    <div>
      <Text size="xs" c="dimmed" fw={600} tt="uppercase">
        {label}
      </Text>
      <Text size="sm" style={{ whiteSpace: "pre-wrap" }}>
        {value}
      </Text>
    </div>
  ) : null;

export default function KevoFlagDetailClientPage({
  reference,
  accessScope,
}: {
  reference: string;
  accessScope: AccessScope;
}) {
  const [detail, setDetail] = useState<KevoFlagDetail | null>(null);
  const [notFound, setNotFound] = useState(false);
  const [conversation, setConversation] = useState<KevoConversation | null>(
    null,
  );
  const [convLoading, setConvLoading] = useState(false);
  const [convError, setConvError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [correctionOpen, setCorrectionOpen] = useState(false);
  const [notes, setNotes] = useState("");

  const canReview = accessScope.update || accessScope.superAdmin;
  const canWrite = accessScope.create || accessScope.superAdmin;

  const load = useCallback(async () => {
    const res = await getFlag(reference);
    if (res.success) {
      setDetail(res.data);
      setNotes(res.data.flag.reviewer_notes ?? "");
    } else {
      setNotFound(true);
    }
  }, [reference]);

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

  const flag = detail?.flag;

  const correctionForm = useForm({
    initialValues: {
      entity: "",
      aliases: [] as string[],
      property: "",
      category: "correction",
      verified_text: "",
    },
    validate: {
      entity: (v) => (v.trim() ? null : "Entity is required"),
      verified_text: (v) =>
        v.trim() ? null : "Write the verified statement",
    },
  });

  useEffect(() => {
    if (flag) {
      correctionForm.setFieldValue("entity", flag.entity ?? "");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [flag?.entity]);

  const loadConversation = useCallback(async () => {
    if (!flag) return;
    setConvLoading(true);
    setConvError(null);
    const res = await getConversation(flag.conversation_id);
    if (res.success) setConversation(res.data);
    else setConvError(res.message || "Could not fetch the conversation");
    setConvLoading(false);
  }, [flag]);

  /** The turn to highlight: the flag_issue tool call, else a question match. */
  const highlightIndex = useMemo(() => {
    if (!conversation || !flag) return -1;
    const toolIdx = conversation.turns.findIndex((t) =>
      t.tool_calls.some((tc) => tc.tool_name === "flag_issue"),
    );
    if (toolIdx !== -1) return toolIdx;
    const probe = (flag.member_question ?? "").slice(0, 60).toLowerCase();
    if (!probe) return -1;
    return conversation.turns.findIndex((t) =>
      (t.message ?? "").toLowerCase().includes(probe),
    );
  }, [conversation, flag]);

  const act = async (fn: () => Promise<{ success: boolean; message: string }>) => {
    setBusy(true);
    const res = await fn();
    notifications.show({
      message: res.message,
      color: res.success ? "teal" : "red",
    });
    if (res.success) await load();
    setBusy(false);
    return res.success;
  };

  const setStatus = (status: Parameters<typeof updateFlag>[1]["status"]) =>
    act(() => updateFlag(reference, { status, reviewer_notes: notes || undefined }));

  const submitCorrection = correctionForm.onSubmit(async (values) => {
    if (!flag) return;
    const created = await createKnowledge({
      flag_id: flag.id,
      entity: values.entity.trim(),
      aliases: values.aliases,
      property: values.property.trim() || undefined,
      category: values.category,
      verified_text: values.verified_text.trim(),
    });
    if (!created.success) {
      notifications.show({ message: created.message, color: "red" });
      return;
    }
    // Approving right away is the common path for a reviewer.
    if (canReview) {
      await approveKnowledge(created.data.id);
    }
    notifications.show({
      message: canReview
        ? "Correction saved and approved — publish it from the Publish tab"
        : "Correction saved as a draft for review",
      color: "teal",
    });
    setCorrectionOpen(false);
    await load();
  });

  if (notFound) {
    return (
      <Alert color="red" title="Flag not found">
        No flag with reference {reference}.{" "}
        <Anchor component={Link} to="/admin/kevo/flags">
          Back to the queue
        </Anchor>
      </Alert>
    );
  }
  if (!flag) {
    return (
      <Group justify="center" py={80}>
        <Loader size="sm" color={KARMA.bronze} />
      </Group>
    );
  }

  const isKnowledgeFlag =
    flag.category === "KNOWLEDGE_GAP" || flag.category === "WRONG_INFO";

  return (
    <Stack gap="lg">
      <Group justify="space-between" wrap="wrap">
        <Group gap="sm">
          <Button
            component={Link}
            to="/admin/kevo/flags"
            variant="subtle"
            color="gray"
            leftSection={<IconArrowLeft size={16} />}
          >
            Flags
          </Button>
          <Title order={2} ff="monospace">
            {flag.reference}
          </Title>
          <CategoryBadge category={flag.category} />
          <StatusBadge status={flag.status} />
        </Group>
        <Group gap="xs">
          <Badge variant="light" color="gray" radius="xl">
            {SOURCE_LABEL[flag.source]}
          </Badge>
          <Text size="xs" c="dimmed">
            {timeAgo(flag.created_at)}
          </Text>
        </Group>
      </Group>

      <Grid gutter="lg">
        <Grid.Col span={{ base: 12, md: 7 }}>
          <Stack gap="lg">
            <Card radius="lg" withBorder>
              <Stack gap="md">
                <FieldRow label="Member question" value={flag.member_question} />
                <FieldRow label="Agent answer" value={flag.agent_answer} />
                <FieldRow
                  label="Member says is correct"
                  value={flag.member_claim}
                />
                <FieldRow label="Entity / topic" value={flag.entity} />
                <FieldRow
                  label="Requested change"
                  value={flag.requested_change}
                />
                <Divider />
                <Group gap="xl">
                  <FieldRow label="Member" value={flag.member_id ?? "unknown"} />
                  <div>
                    <Text size="xs" c="dimmed" fw={600} tt="uppercase">
                      Conversation
                    </Text>
                    <Group gap={6}>
                      <Text size="sm" ff="monospace">
                        {flag.conversation_id}
                      </Text>
                      <Tooltip label="Open in the ElevenLabs dashboard">
                        <Anchor href={detail!.dashboard_url} target="_blank">
                          <IconExternalLink size={14} />
                        </Anchor>
                      </Tooltip>
                    </Group>
                  </div>
                </Group>
              </Stack>
            </Card>

            <Card radius="lg" withBorder>
              <Group justify="space-between" mb="sm">
                <div>
                  <Text fw={600} size="sm">
                    Conversation
                  </Text>
                  <Text c="dimmed" size="xs">
                    Fetched live from ElevenLabs, never stored here
                  </Text>
                </div>
                <Button
                  variant="default"
                  size="xs"
                  leftSection={<IconMessage size={14} />}
                  onClick={() => void loadConversation()}
                  loading={convLoading}
                >
                  {conversation ? "Reload" : "View conversation"}
                </Button>
              </Group>
              {convError && (
                <Alert color="red" variant="light">
                  {convError}
                </Alert>
              )}
              {conversation && (
                <Stack gap={8} mah={420} style={{ overflowY: "auto" }}>
                  {conversation.turns.map((turn, i) => (
                    <Card
                      key={i}
                      padding="xs"
                      radius="md"
                      withBorder={i === highlightIndex}
                      style={{
                        background:
                          i === highlightIndex
                            ? `color-mix(in srgb, ${KARMA.bronzeLt} 18%, transparent)`
                            : turn.role === "agent"
                              ? "color-mix(in srgb, var(--mantine-color-gray-4) 12%, transparent)"
                              : undefined,
                        borderColor:
                          i === highlightIndex ? KARMA.bronze : undefined,
                      }}
                    >
                      <Group gap={6} mb={2}>
                        <Text size="xs" fw={700} c="dimmed" tt="uppercase">
                          {turn.role === "agent" ? "Kevo" : "Member"}
                        </Text>
                        {turn.time_in_call_secs !== null && (
                          <Text size="xs" c="dimmed">
                            {turn.time_in_call_secs}s
                          </Text>
                        )}
                      </Group>
                      {turn.message && <Text size="sm">{turn.message}</Text>}
                      {turn.tool_calls.map((tc, j) => (
                        <Text key={j} size="xs" c={KARMA.bronze} ff="monospace">
                          → {tc.tool_name}({tc.params ?? ""})
                        </Text>
                      ))}
                    </Card>
                  ))}
                </Stack>
              )}
            </Card>
          </Stack>
        </Grid.Col>

        <Grid.Col span={{ base: 12, md: 5 }}>
          <Stack gap="lg">
            <Card radius="lg" withBorder>
              <Text fw={600} size="sm" mb="sm">
                Review
              </Text>
              <Stack gap="sm">
                <Textarea
                  label="Reviewer notes"
                  placeholder="What you checked, what the member was told…"
                  autosize
                  minRows={2}
                  value={notes}
                  onChange={(e) => setNotes(e.currentTarget.value)}
                  disabled={!canReview}
                />
                {isKnowledgeFlag ? (
                  <Group gap="xs" wrap="wrap">
                    <Button
                      leftSection={<IconPencil size={15} />}
                      color={KARMA.black}
                      onClick={() => setCorrectionOpen(true)}
                      disabled={!canWrite}
                    >
                      Write correction
                    </Button>
                    <Button
                      variant="default"
                      leftSection={<IconX size={15} />}
                      onClick={() => void setStatus("REJECTED")}
                      disabled={!canReview}
                      loading={busy}
                    >
                      Reject
                    </Button>
                    <Button
                      variant="default"
                      leftSection={<IconCopy size={15} />}
                      onClick={() => void setStatus("RESOLVED")}
                      disabled={!canReview}
                      loading={busy}
                    >
                      Mark duplicate
                    </Button>
                  </Group>
                ) : (
                  <Group gap="xs" wrap="wrap">
                    {flag.clickup_task_id ? (
                      <Alert
                        color="teal"
                        variant="light"
                        icon={<IconCheck size={16} />}
                        style={{ flex: 1 }}
                      >
                        ClickUp task created —{" "}
                        <Anchor
                          href={flag.clickup_task_url ?? "#"}
                          target="_blank"
                        >
                          open task
                        </Anchor>
                      </Alert>
                    ) : (
                      <Button
                        leftSection={<IconSend size={15} />}
                        color={KARMA.black}
                        onClick={() =>
                          void act(() => routeFlagToClickUp(reference))
                        }
                        disabled={!canReview}
                        loading={busy}
                      >
                        Create ClickUp task
                      </Button>
                    )}
                    <Button
                      variant="default"
                      leftSection={<IconCheck size={15} />}
                      onClick={() => void setStatus("RESOLVED")}
                      disabled={!canReview}
                      loading={busy}
                    >
                      Mark resolved
                    </Button>
                  </Group>
                )}
                {canReview && flag.status === "NEW" && (
                  <Button
                    variant="subtle"
                    size="xs"
                    onClick={() => void setStatus("IN_REVIEW")}
                  >
                    Mark as in review
                  </Button>
                )}
              </Stack>
            </Card>

            <Card radius="lg" withBorder>
              <Text fw={600} size="sm" mb="sm">
                History
              </Text>
              <Timeline
                active={detail!.audit.length - 1}
                bulletSize={18}
                lineWidth={2}
                color={KARMA.bronze}
              >
                {detail!.audit.map((row) => (
                  <Timeline.Item
                    key={row.id}
                    title={row.action.replace(/[._]/g, " ")}
                  >
                    <Text size="xs" c="dimmed">
                      {row.actor_email ?? "system"} · {formatDate(row.created_at)}
                    </Text>
                  </Timeline.Item>
                ))}
              </Timeline>
            </Card>
          </Stack>
        </Grid.Col>
      </Grid>

      <Modal
        opened={correctionOpen}
        onClose={() => setCorrectionOpen(false)}
        title={
          <Group gap={8}>
            <IconBook2 size={18} color={KARMA.bronze} />
            <Text fw={700}>Write correction</Text>
          </Group>
        }
        size="lg"
      >
        <form onSubmit={submitCorrection}>
          <Stack gap="sm">
            <TextInput
              label="Entity"
              placeholder="Karma Beach"
              required
              {...correctionForm.getInputProps("entity")}
            />
            <TagsInput
              label="Aliases"
              placeholder="Type and press Enter — e.g. Karma Beach Bali"
              {...correctionForm.getInputProps("aliases")}
            />
            <TextInput
              label="Property"
              placeholder="Karma Kandara (Bali)"
              description="Which property this belongs to; leave empty for general facts"
              {...correctionForm.getInputProps("property")}
            />
            <Select
              label="Type"
              data={[
                { value: "amenity", label: "Amenity" },
                { value: "policy", label: "Policy" },
                { value: "faq", label: "FAQ" },
                { value: "correction", label: "Correction" },
              ]}
              {...correctionForm.getInputProps("category")}
            />
            <Textarea
              label="Verified statement"
              placeholder="Karma Beach is a private beach club within Karma Kandara. It is an amenity, not a separate property."
              description="Written as a clear standalone fact — this text goes into Kevo's knowledge"
              autosize
              minRows={3}
              required
              {...correctionForm.getInputProps("verified_text")}
            />
            <Group justify="flex-end">
              <Button variant="default" onClick={() => setCorrectionOpen(false)}>
                Cancel
              </Button>
              <Button type="submit" color={KARMA.black}>
                {canReview ? "Save & approve" : "Save draft"}
              </Button>
            </Group>
          </Stack>
        </form>
      </Modal>
    </Stack>
  );
}
