import { Check, RotateCcw } from "lucide-react";
import { useEffect, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { contentApi } from "../../shared/api/endpoints";
import { normalizeContentList } from "../../shared/api/normalize";
import { queryKeys } from "../../shared/api/queryKeys";
import { Badge } from "../../shared/ui/Badge";
import { Button } from "../../shared/ui/Button";
import { Textarea } from "../../shared/ui/Field";
import { EmptyState, ErrorState, Skeleton } from "../../shared/ui/States";

const moderationParams = { status: "moderation" };

function paragraphs(content = "") {
  if (Array.isArray(content)) return content;
  return String(content).split(/\n{2,}/).filter(Boolean);
}

export function ModeratorPage() {
  const [selectedId, setSelectedId] = useState(null);
  const [message, setMessage] = useState("");
  const queryClient = useQueryClient();
  const materialsQuery = useQuery({
    queryKey: queryKeys.content(moderationParams),
    queryFn: () => contentApi.list(moderationParams),
  });
  const materials = normalizeContentList(materialsQuery.data);
  const selected = materials.find((item) => item.id === selectedId) ?? materials[0];

  useEffect(() => {
    if (!selectedId && materials[0]?.id) {
      setSelectedId(materials[0].id);
    }
  }, [materials, selectedId]);

  const reviewMutation = useMutation({
    mutationFn: ({ id, payload }) => contentApi.update(id, payload),
    onSuccess: () => {
      setMessage("");
      queryClient.invalidateQueries({ queryKey: queryKeys.content(moderationParams) });
    },
  });

  const approve = () => {
    if (!selected?.id) return;
    reviewMutation.mutate({ id: selected.id, payload: { status: "published", moderatorComment: message.trim() } });
  };

  const returnToAuthor = () => {
    if (!selected?.id || !message.trim()) return;
    reviewMutation.mutate({ id: selected.id, payload: { status: "returned", moderatorComment: message.trim() } });
  };

  return (
    <div>
      <p className="text-xs font-bold uppercase tracking-widest text-accent">Контроль качества</p>
      <h1 className="mt-2 font-serif text-4xl">Очередь модерации</h1>
      <div className="mt-8 grid gap-6 xl:grid-cols-[minmax(18rem,1fr)_minmax(0,3fr)]">
        <aside className="overflow-hidden rounded-lg border border-line bg-surface">
          <div className="border-b border-line p-4">
            <b>Ожидают проверки</b>
            <Badge className="ml-2" tone="warning">{materials.length}</Badge>
          </div>
          {materialsQuery.isLoading && (
            <div className="space-y-3 p-4">
              <Skeleton className="h-20" />
              <Skeleton className="h-20" />
            </div>
          )}
          {materialsQuery.isError && (
            <div className="p-4">
              <ErrorState retry={() => materialsQuery.refetch()} />
            </div>
          )}
          {materialsQuery.isSuccess && materials.length === 0 && (
            <div className="p-4">
              <EmptyState title="Очередь пуста" text="Материалы со статусом модерации появятся здесь после ответа backend." />
            </div>
          )}
          {materials.map((material) => (
            <button
              key={material.id}
              type="button"
              onClick={() => setSelectedId(material.id)}
              className={`block w-full border-b border-line p-4 text-left last:border-0 ${
                selected?.id === material.id ? "bg-accent-soft" : "hover:bg-paper"
              }`}
            >
              <span className="text-xs text-muted">{material.type ?? "Материал"} · {material.author}</span>
              <span className="mt-2 block font-serif text-lg leading-snug">{material.title}</span>
            </button>
          ))}
        </aside>
        <section className="rounded-lg border border-line bg-surface p-5 sm:p-7">
          {!selected && materialsQuery.isSuccess && (
            <EmptyState title="Материал не выбран" text="Выберите запись из очереди модерации." />
          )}
          {selected && (
            <>
              <div className="flex flex-wrap items-center gap-3">
                <Badge tone="warning">На модерации</Badge>
                <span className="text-sm text-muted">{selected.author}</span>
              </div>
              <h2 className="mt-5 font-serif text-3xl">{selected.title}</h2>
              <p className="mt-4 text-lg leading-8 text-muted">{selected.excerpt}</p>
              <div className="mt-7 border-y border-line py-6">
                {paragraphs(selected.content ?? selected.body).map((paragraph) => (
                  <p key={paragraph} className="mb-4 leading-7 last:mb-0">{paragraph}</p>
                ))}
              </div>
              <Textarea
                className="mt-6"
                label="Комментарий редактору"
                value={message}
                onChange={(event) => setMessage(event.target.value)}
                placeholder="Обязателен при возврате на доработку"
              />
              <div className="mt-6 flex flex-wrap gap-3">
                <Button icon={<Check className="size-4" />} loading={reviewMutation.isPending} onClick={approve}>
                  Одобрить
                </Button>
                <Button
                  variant="danger"
                  icon={<RotateCcw className="size-4" />}
                  loading={reviewMutation.isPending}
                  disabled={!message.trim()}
                  onClick={returnToAuthor}
                >
                  Вернуть на доработку
                </Button>
              </div>
            </>
          )}
        </section>
      </div>
    </div>
  );
}
