"use client";

import { useMemo } from "react";
import {
  DndContext,
  KeyboardSensor,
  PointerSensor,
  closestCenter,
  type DragEndEvent,
  useSensor,
  useSensors,
} from "@dnd-kit/core";
import {
  SortableContext,
  arrayMove,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { GripVertical, Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";

export type FaqDraft = { id: string; question: string; answer: string };

type Props = {
  faqs: FaqDraft[];
  onChange: (faqs: FaqDraft[]) => void;
};

function newFaqId() {
  if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
  return `faq-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}

export function createEmptyFaq(): FaqDraft {
  return { id: newFaqId(), question: "", answer: "" };
}

function SortableFaqCard({
  faq,
  onChange,
  onRemove,
}: {
  faq: FaqDraft;
  onChange: (next: FaqDraft) => void;
  onRemove: () => void;
}) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id: faq.id,
  });
  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={`rounded-lg border bg-white p-4 ${isDragging ? "z-10 shadow-md" : ""}`}
    >
      <div className="mb-3 flex items-center justify-between gap-2">
        <button
          type="button"
          className="inline-flex cursor-grab items-center rounded-md border px-2 py-1 text-slate-500 hover:bg-slate-50 active:cursor-grabbing"
          aria-label="Drag to reorder FAQ"
          {...attributes}
          {...listeners}
        >
          <GripVertical className="size-4" />
        </button>
        <Button type="button" variant="outline" size="icon" onClick={onRemove} aria-label="Remove FAQ">
          <Trash2 className="size-4 text-red-600" />
        </Button>
      </div>
      <div className="grid gap-3">
        <div className="grid gap-1.5">
          <Label className="text-xs">Question</Label>
          <Input
            value={faq.question}
            placeholder="e.g. What is included in the box?"
            onChange={(e) => onChange({ ...faq, question: e.target.value })}
          />
        </div>
        <div className="grid gap-1.5">
          <Label className="text-xs">Answer</Label>
          <Textarea
            rows={3}
            value={faq.answer}
            placeholder="Short, clear answer for the product page and FAQ schema."
            onChange={(e) => onChange({ ...faq, answer: e.target.value })}
          />
        </div>
      </div>
    </div>
  );
}

export default function ProductFaqEditor({ faqs, onChange }: Props) {
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
  );
  const ids = useMemo(() => faqs.map((f) => f.id), [faqs]);

  const onDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (!over || active.id === over.id) return;
    const oldIndex = faqs.findIndex((f) => f.id === active.id);
    const newIndex = faqs.findIndex((f) => f.id === over.id);
    if (oldIndex < 0 || newIndex < 0) return;
    onChange(arrayMove(faqs, oldIndex, newIndex));
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between gap-2">
        <div>
          <p className="text-sm font-medium text-slate-800">FAQs</p>
          <p className="text-xs text-slate-500">
            Shown as an accordion on the product page and emitted as FAQ schema.
          </p>
        </div>
        <Button type="button" variant="outline" size="sm" onClick={() => onChange([...faqs, createEmptyFaq()])}>
          <Plus className="mr-1 size-4" />
          Add FAQ
        </Button>
      </div>
      {faqs.length === 0 ? (
        <p className="rounded-lg border border-dashed bg-slate-50 px-4 py-8 text-center text-sm text-slate-500">
          No FAQs yet. Add questions customers actually search for.
        </p>
      ) : (
        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
          <SortableContext items={ids} strategy={verticalListSortingStrategy}>
            <div className="space-y-3">
              {faqs.map((faq, index) => (
                <SortableFaqCard
                  key={faq.id}
                  faq={faq}
                  onChange={(next) => {
                    const nextFaqs = [...faqs];
                    nextFaqs[index] = next;
                    onChange(nextFaqs);
                  }}
                  onRemove={() => onChange(faqs.filter((f) => f.id !== faq.id))}
                />
              ))}
            </div>
          </SortableContext>
        </DndContext>
      )}
    </div>
  );
}
