"use client";

import {
  Alert,
  Badge,
  Button,
  Card,
  Code,
  Group,
  Loader,
  Modal,
  ScrollArea,
  Stack,
  Table,
  Text,
  Title,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import {
  IconCheck,
  IconCloudUpload,
  IconInfoCircle,
} from "@tabler/icons-react";
import { useCallback, useEffect, useState } from "react";
import { getPublishLog, getPublishPreview } from "@/lib/features/kevo/query";
import { publishKnowledge } from "@/lib/features/kevo/action";
import type {
  KevoPublishLogRow,
  KevoPublishPreview,
} from "@/lib/features/kevo/types";
import type { AccessScope } from "@/lib/features/types";
import { formatDate, KARMA } from "../_components/kevo.constants";

export default function KevoPublishClientPage({
  publishScope,
}: {
  publishScope: AccessScope;
}) {
  const [preview, setPreview] = useState<KevoPublishPreview | null>(null);
  const [log, setLog] = useState<KevoPublishLogRow[]>([]);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [publishing, setPublishing] = useState(false);

  const canPublish = publishScope.update || publishScope.superAdmin;

  const load = useCallback(async () => {
    const [p, l] = await Promise.all([getPublishPreview(), getPublishLog()]);
    if (p.success) setPreview(p.data);
    if (l.success) setLog(l.data);
  }, []);

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

  const doPublish = async () => {
    setPublishing(true);
    const res = await publishKnowledge();
    notifications.show({
      message: res.message,
      color: res.success ? "teal" : "red",
      autoClose: 6000,
    });
    setPublishing(false);
    setConfirmOpen(false);
    if (res.success) await load();
  };

  if (!preview) {
    return (
      <Group justify="center" py={80}>
        <Loader size="sm" color={KARMA.bronze} />
      </Group>
    );
  }

  return (
    <Stack gap="lg">
      <Group justify="space-between" wrap="wrap">
        <div>
          <Title order={2}>Publish to Kevo</Title>
          <Text c="dimmed" size="sm">
            One managed document — "Kevo – Verified Corrections & Amenity Map"
            — generated from every approved entry.
          </Text>
        </div>
        <Button
          leftSection={<IconCloudUpload size={16} />}
          color={KARMA.black}
          disabled={!canPublish || preview.unchanged || preview.entries_count === 0}
          onClick={() => setConfirmOpen(true)}
        >
          Publish {preview.entries_count} entries
        </Button>
      </Group>

      {!canPublish && (
        <Alert
          color="yellow"
          variant="light"
          icon={<IconInfoCircle size={16} />}
        >
          You can preview the document, but publishing needs the Kevo
          Publishing role.
        </Alert>
      )}
      {preview.unchanged && (
        <Alert color="teal" variant="light" icon={<IconCheck size={16} />}>
          The document is identical to the last publish (
          {formatDate(preview.last_published_at)}) — nothing to send.
        </Alert>
      )}

      <Card radius="lg" withBorder>
        <Group justify="space-between" mb="sm">
          <div>
            <Text fw={600} size="sm">
              Preview
            </Text>
            <Text c="dimmed" size="xs">
              Exactly what Kevo's knowledge base will contain
            </Text>
          </div>
          <Group gap="xs">
            <Badge variant="light" color={KARMA.bronze} radius="xl">
              {preview.entries_count} entries
            </Badge>
            <Badge
              variant="light"
              color={preview.unchanged ? KARMA.good : KARMA.gold}
              radius="xl"
            >
              {preview.unchanged ? "Unchanged" : "Changed since last publish"}
            </Badge>
          </Group>
        </Group>
        <ScrollArea.Autosize mah={420}>
          <Code block style={{ whiteSpace: "pre-wrap" }}>
            {preview.content}
          </Code>
        </ScrollArea.Autosize>
      </Card>

      <Card radius="lg" withBorder p={0}>
        <Text fw={600} size="sm" p="md" pb={0}>
          Publish history
        </Text>
        {log.length === 0 ? (
          <Text c="dimmed" size="sm" p="md">
            Never published yet.
          </Text>
        ) : (
          <Table verticalSpacing="sm" mt="xs">
            <Table.Thead>
              <Table.Tr>
                <Table.Th>When</Table.Th>
                <Table.Th>By</Table.Th>
                <Table.Th>Entries</Table.Th>
                <Table.Th>Result</Table.Th>
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>
              {log.map((row) => (
                <Table.Tr key={row.id}>
                  <Table.Td>
                    <Text size="sm">{formatDate(row.published_at)}</Text>
                  </Table.Td>
                  <Table.Td>
                    <Text size="sm">{row.published_by}</Text>
                  </Table.Td>
                  <Table.Td>
                    <Text size="sm">{row.entries_count}</Text>
                  </Table.Td>
                  <Table.Td>
                    <Badge
                      variant="light"
                      radius="xl"
                      size="sm"
                      color={
                        row.result === "succeeded" ? KARMA.good : KARMA.crit
                      }
                    >
                      {row.result === "succeeded" ? "Succeeded" : "Failed"}
                    </Badge>
                    {row.result !== "succeeded" && (
                      <Text size="xs" c="dimmed" lineClamp={1}>
                        {row.result}
                      </Text>
                    )}
                  </Table.Td>
                </Table.Tr>
              ))}
            </Table.Tbody>
          </Table>
        )}
      </Card>

      <Modal
        opened={confirmOpen}
        onClose={() => setConfirmOpen(false)}
        title={<Text fw={700}>Publish to the live agent?</Text>}
      >
        <Stack gap="sm">
          <Text size="sm">
            This updates Kevo's knowledge base document with{" "}
            {preview.entries_count} verified entries. Members get answers based
            on this content immediately after re-indexing.
          </Text>
          <Group justify="flex-end">
            <Button variant="default" onClick={() => setConfirmOpen(false)}>
              Cancel
            </Button>
            <Button
              color={KARMA.black}
              loading={publishing}
              onClick={() => void doPublish()}
            >
              Publish
            </Button>
          </Group>
        </Stack>
      </Modal>
    </Stack>
  );
}
