"use client";

import { FileTextIcon, ListOrderedIcon, SearchIcon, SparklesIcon, XIcon } from "lucide-react";
import { useEffect, useState } from "react";

import { ContentStatusBadge } from "@/components/admin/status-badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Spinner } from "@/components/ui/spinner";
import {
  getBlogSummaries,
  previewAutomaticRelated,
  searchBlogs,
  type BlogSearchResult,
} from "@/features/blogs/actions";
import { MAX_RELATED } from "@/features/blogs/schemas";
import { cn } from "@/lib/utils";

import { useBlogEditor } from "./editor-context";
import { ErrorText, SortableList } from "./fields";

export function RelatedSection() {
  const { values, setField, meta, errors } = useBlogEditor();
  const [summaries, setSummaries] = useState<Map<string, BlogSearchResult>>(new Map());
  const [automatic, setAutomatic] = useState<BlogSearchResult[] | null>(null);

  const ids = values.relatedBlogIds;
  const missing = ids.filter((id) => !summaries.has(id));
  const missingKey = missing.join(",");

  useEffect(() => {
    if (!missingKey) return;
    let cancelled = false;
    void getBlogSummaries(missingKey.split(",")).then((result) => {
      if (cancelled || !result.ok) return;
      setSummaries((current) => {
        const next = new Map(current);
        for (const blog of result.data) next.set(blog.id, blog);
        return next;
      });
    });
    return () => {
      cancelled = true;
    };
  }, [missingKey]);

  const tagsKey = values.tags.join("|");
  useEffect(() => {
    if (values.relatedMode !== "AUTOMATIC") return;
    let cancelled = false;
    const timer = setTimeout(async () => {
      const result = await previewAutomaticRelated({
        blogId: meta?.id ?? null,
        categoryId: values.categoryId,
        tags: tagsKey ? tagsKey.split("|") : [],
      });
      if (!cancelled) setAutomatic(result.ok ? result.data : []);
    }, 300);
    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [values.relatedMode, values.categoryId, tagsKey, meta?.id]);

  const selected = ids.map((id) => summaries.get(id) ?? { id, title: "Loading…", slug: "", status: "DRAFT" as const, featuredImage: null, category: null });

  return (
    <div className="grid gap-6">
      <Card>
        <CardHeader>
          <CardTitle>Related articles</CardTitle>
          <CardDescription>Shown at the end of the article to keep readers exploring.</CardDescription>
        </CardHeader>
        <CardContent>
          <RadioGroup
            value={values.relatedMode}
            onValueChange={(mode) => setField("relatedMode", mode as typeof values.relatedMode)}
            className="grid gap-3 sm:grid-cols-2"
          >
            <ModeOption
              value="AUTOMATIC"
              icon={SparklesIcon}
              title="Automatic"
              description="Up to 3 published articles from the same category, then with shared tags."
              selected={values.relatedMode === "AUTOMATIC"}
            />
            <ModeOption
              value="MANUAL"
              icon={ListOrderedIcon}
              title="Manual"
              description={`Pick up to ${MAX_RELATED} articles and put them in order.`}
              selected={values.relatedMode === "MANUAL"}
            />
          </RadioGroup>
        </CardContent>
      </Card>

      {values.relatedMode === "AUTOMATIC" ? (
        <Card>
          <CardHeader>
            <CardTitle>Currently selected automatically</CardTitle>
            <CardDescription>Based on the category and tags in the settings panel.</CardDescription>
          </CardHeader>
          <CardContent>
            {automatic === null ? (
              <div className="flex justify-center py-6">
                <Spinner />
              </div>
            ) : automatic.length === 0 ? (
              <p className="py-4 text-sm text-muted-foreground">
                No published articles match yet. Pick a category or add tags, or choose articles manually.
              </p>
            ) : (
              <ul className="divide-y">
                {automatic.map((blog) => (
                  <li key={blog.id} className="py-2.5">
                    <ArticleRow blog={blog} />
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardHeader className="flex flex-row items-start justify-between gap-4">
            <div>
              <CardTitle>Chosen articles</CardTitle>
              <CardDescription>Drag to reorder. Unpublished articles stay hidden until they go live.</CardDescription>
            </div>
            <ArticlePicker
              excludeIds={[...ids, ...(meta ? [meta.id] : [])]}
              disabled={ids.length >= MAX_RELATED}
              onPick={(blog) => {
                setSummaries((current) => new Map(current).set(blog.id, blog));
                setField("relatedBlogIds", [...ids, blog.id]);
              }}
            />
          </CardHeader>
          <CardContent>
            {selected.length === 0 ? (
              <p className="rounded-xl border border-dashed py-10 text-center text-sm text-muted-foreground">
                No articles chosen yet.
              </p>
            ) : (
              <SortableList
                items={selected}
                onReorder={(next) => setField("relatedBlogIds", next.map((blog) => blog.id))}
                className="space-y-2"
                renderItem={(blog, _index, handle) => (
                  <div className="flex items-center gap-2 rounded-lg border bg-card p-2">
                    {handle}
                    <ArticleRow blog={blog} />
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon-sm"
                      aria-label={`Remove ${blog.title}`}
                      onClick={() => setField("relatedBlogIds", ids.filter((id) => id !== blog.id))}
                    >
                      <XIcon />
                    </Button>
                  </div>
                )}
              />
            )}
            <ErrorText message={errors.relatedBlogIds} />
          </CardContent>
        </Card>
      )}
    </div>
  );
}

function ModeOption({
  value,
  icon: Icon,
  title,
  description,
  selected,
}: {
  value: string;
  icon: typeof SparklesIcon;
  title: string;
  description: string;
  selected: boolean;
}) {
  return (
    <label
      className={cn(
        "flex cursor-pointer gap-3 rounded-xl border p-4 transition-colors hover:bg-muted/40",
        selected && "border-primary/40 bg-accent/60 hover:bg-accent/60",
      )}
    >
      <RadioGroupItem value={value} className="mt-0.5" />
      <span>
        <span className="flex items-center gap-1.5 text-sm font-medium">
          <Icon className="size-4 text-primary" />
          {title}
        </span>
        <span className="mt-1 block text-sm text-muted-foreground">{description}</span>
      </span>
    </label>
  );
}

function ArticleRow({ blog }: { blog: BlogSearchResult }) {
  return (
    <div className="flex min-w-0 flex-1 items-center gap-3">
      <div className="grid size-10 shrink-0 place-items-center overflow-hidden rounded-md bg-muted">
        {blog.featuredImage ? (
          // eslint-disable-next-line @next/next/no-img-element -- thumbnail of an uploaded image
          <img src={blog.featuredImage} alt="" className="size-full object-cover" />
        ) : (
          <FileTextIcon className="size-4 text-muted-foreground" />
        )}
      </div>
      <div className="min-w-0 flex-1">
        <p className="truncate text-sm font-medium">{blog.title}</p>
        <p className="truncate text-xs text-muted-foreground">
          {blog.category ?? "Uncategorized"}
          {blog.slug && ` · /blog/${blog.slug}/`}
        </p>
      </div>
      {blog.status !== "PUBLISHED" && <ContentStatusBadge status={blog.status} size="sm" />}
    </div>
  );
}

function ArticlePicker({
  excludeIds,
  disabled,
  onPick,
}: {
  excludeIds: string[];
  disabled: boolean;
  onPick: (blog: BlogSearchResult) => void;
}) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<BlogSearchResult[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    const timer = setTimeout(async () => {
      setLoading(true);
      const result = await searchBlogs(query);
      if (!cancelled) {
        setResults(result.ok ? result.data : []);
        setLoading(false);
      }
    }, 200);
    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [query, open]);

  const visible = results.filter((blog) => !excludeIds.includes(blog.id));

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button type="button" variant="outline" disabled={disabled}>
          <SearchIcon />
          Add article
        </Button>
      </PopoverTrigger>
      <PopoverContent align="end" className="w-96 p-0">
        <Command shouldFilter={false}>
          <CommandInput value={query} onValueChange={setQuery} placeholder="Search articles…" />
          <CommandList>
            {loading && visible.length === 0 ? (
              <div className="flex justify-center py-6">
                <Spinner />
              </div>
            ) : (
              <CommandEmpty>No articles found.</CommandEmpty>
            )}
            {visible.length > 0 && (
              <CommandGroup>
                {visible.map((blog) => (
                  <CommandItem
                    key={blog.id}
                    value={blog.id}
                    onSelect={() => {
                      onPick(blog);
                      setOpen(false);
                      setQuery("");
                    }}
                  >
                    <ArticleRow blog={blog} />
                  </CommandItem>
                ))}
              </CommandGroup>
            )}
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
