"use client";

import { MessageCircleQuestionIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { useEffect, useRef } from "react";
import { toast } from "sonner";

import { EmptyState } from "@/components/admin/empty-state";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { MAX_FAQS } from "@/features/blogs/schemas";
import { cn } from "@/lib/utils";

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

export function FaqSection() {
  const { values, setField, errors } = useBlogEditor();
  const faqs = values.faqs;
  const latest = useRef(faqs);
  useEffect(() => {
    latest.current = faqs;
  });

  const add = () => {
    const id = `new-${crypto.randomUUID()}`;
    setField("faqs", [...faqs, { id, question: "", answer: "" }]);
    requestAnimationFrame(() => document.getElementById(`faq-question-${id}`)?.focus());
  };

  const update = (id: string, change: Partial<(typeof faqs)[number]>) =>
    setField(
      "faqs",
      faqs.map((faq) => (faq.id === id ? { ...faq, ...change } : faq)),
    );

  const remove = (index: number) => {
    const removed = faqs[index];
    const next = faqs.filter((_, i) => i !== index);
    setField("faqs", next);
    toast("Question removed", {
      action: {
        label: "Undo",
        onClick: () => {
          const current = latest.current;
          setField("faqs", [...current.slice(0, index), removed, ...current.slice(index)]);
        },
      },
    });
  };

  return (
    <div className="grid gap-6">
      <Card>
        <CardHeader className="flex flex-row items-start justify-between gap-4">
          <div>
            <CardTitle>Frequently asked questions</CardTitle>
            <CardDescription>
              Shown as an FAQ section near the end of the article. Drag questions to reorder them.
            </CardDescription>
          </div>
          {faqs.length > 0 && (
            <Button type="button" variant="outline" onClick={add} disabled={faqs.length >= MAX_FAQS}>
              <PlusIcon />
              Add question
            </Button>
          )}
        </CardHeader>
        <CardContent>
          {faqs.length === 0 ? (
            <EmptyState
              icon={MessageCircleQuestionIcon}
              title="No FAQs yet"
              description="Answer common questions readers ask. FAQs can also appear as rich results in Google."
              action={
                <Button type="button" onClick={add}>
                  <PlusIcon />
                  Add question
                </Button>
              }
              className="py-10"
            />
          ) : (
            <SortableList
              items={faqs}
              onReorder={(next) => setField("faqs", next)}
              className="space-y-3"
              renderItem={(faq, index, handle) => {
                const questionError = errors[`faqs.${index}.question`];
                const answerError = errors[`faqs.${index}.answer`];
                return (
                  <div
                    className={cn(
                      "flex gap-2 rounded-xl border bg-card p-3",
                      (questionError || answerError) && "border-destructive/50",
                    )}
                  >
                    <div className="flex flex-col items-center gap-1 pt-1">
                      {handle}
                      <span className="text-xs font-medium text-muted-foreground tabular-nums">{index + 1}</span>
                    </div>
                    <div className="min-w-0 flex-1 space-y-2">
                      <div>
                        <label htmlFor={`faq-question-${faq.id}`} className="sr-only">
                          Question {index + 1}
                        </label>
                        <Input
                          id={`faq-question-${faq.id}`}
                          value={faq.question}
                          maxLength={300}
                          placeholder="Question"
                          aria-invalid={Boolean(questionError) || undefined}
                          className="font-medium"
                          onChange={(event) => update(faq.id, { question: event.target.value })}
                          onKeyDown={(event) => {
                            if (event.key === "Enter") {
                              event.preventDefault();
                              document.getElementById(`faq-answer-${faq.id}`)?.focus();
                            }
                          }}
                        />
                        <ErrorText message={questionError} />
                      </div>
                      <div>
                        <label htmlFor={`faq-answer-${faq.id}`} className="sr-only">
                          Answer {index + 1}
                        </label>
                        <Textarea
                          id={`faq-answer-${faq.id}`}
                          value={faq.answer}
                          maxLength={5000}
                          rows={3}
                          placeholder="Answer. Leave a blank line between paragraphs."
                          aria-invalid={Boolean(answerError) || undefined}
                          onChange={(event) => update(faq.id, { answer: event.target.value })}
                        />
                        <div className="mt-1 flex justify-between">
                          <ErrorText message={answerError} />
                          <CharCounter value={faq.answer} max={5000} className="ml-auto" />
                        </div>
                      </div>
                    </div>
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon-sm"
                      aria-label={`Remove question ${index + 1}`}
                      className="text-muted-foreground hover:text-destructive"
                      onClick={() => remove(index)}
                    >
                      <Trash2Icon />
                    </Button>
                  </div>
                );
              }}
            />
          )}
        </CardContent>
      </Card>

      <Card size="sm">
        <CardContent>
          <label className="flex items-center justify-between gap-4 text-sm">
            <span>
              <span className="block font-medium">FAQ structured data</span>
              <span className="text-muted-foreground">
                Adds FAQPage schema so search engines can show these questions as rich results.
              </span>
            </span>
            <Switch
              checked={values.faqSchemaEnabled}
              onCheckedChange={(checked) => setField("faqSchemaEnabled", checked)}
            />
          </label>
        </CardContent>
      </Card>
    </div>
  );
}
