"use client";

import type { Dispatch, FormEvent, SetStateAction } from "react";
import {
  CircleHelp,
  Edit3,
  FolderPlus,
  GripVertical,
  Loader2,
  Plus,
  Trash2,
  X,
} from "lucide-react";
import type { FaqCategory, FaqFormState, FaqItem } from "./types";

type FaqAdminIntroProps = {
  hasCategories: boolean;
  onAddCategory: () => void;
  onAddFaq: () => void;
};

export function FaqAdminIntro({ hasCategories, onAddCategory, onAddFaq }: FaqAdminIntroProps) {
  return (
    <div className="flex flex-col gap-4 rounded-lg border border-border bg-white p-5 shadow-sm lg:flex-row lg:items-center lg:justify-between">
      <div className="flex items-center gap-3">
        <div className="grid h-11 w-11 place-items-center rounded-md bg-primary/10 text-primary">
          <CircleHelp className="h-5 w-5" />
        </div>
        <div>
          <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
            FAQ content
          </p>
          <h2 className="mt-1 text-xl font-black tracking-tight text-foreground">
            Add categories, then place FAQs inside them
          </h2>
        </div>
      </div>
      <div className="flex flex-col gap-2 sm:flex-row">
        <button
          type="button"
          onClick={onAddCategory}
          className="inline-flex items-center justify-center gap-2 rounded-md border border-border px-4 py-2.5 text-sm font-black text-foreground transition hover:border-primary/30 hover:text-primary"
        >
          <FolderPlus className="h-4 w-4" />
          Add category
        </button>
        <button
          type="button"
          onClick={onAddFaq}
          disabled={!hasCategories}
          className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2.5 text-sm font-black text-primary-foreground transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-60"
        >
          <Plus className="h-4 w-4" />
          Add FAQ
        </button>
      </div>
    </div>
  );
}

export function FaqErrorMessage({ message }: { message: string }) {
  if (!message) {
    return null;
  }

  return (
    <div className="rounded-lg border border-primary/20 bg-primary/5 p-4 text-sm font-bold text-primary">
      {message}
    </div>
  );
}

export function FaqLoadingState() {
  return (
    <div className="flex min-h-48 items-center justify-center rounded-lg border border-border bg-white">
      <Loader2 className="h-6 w-6 animate-spin text-primary" />
    </div>
  );
}

export function EmptyFaqCategoriesState() {
  return (
    <div className="rounded-lg border border-dashed border-border bg-white p-10 text-center">
      <p className="text-lg font-black text-foreground">No FAQ categories yet</p>
      <p className="mt-2 text-sm font-semibold text-muted-foreground">
        Add a category first, then you can add questions under it.
      </p>
    </div>
  );
}

type FaqContentPanelProps = {
  categories: FaqCategory[];
  activeCategory: string;
  activeFaqs: FaqItem[];
  deletingCategoryId: number | null;
  deletingId: number | null;
  draggingCategoryId: number | null;
  draggingId: number | null;
  onDeleteFaq: (faq: FaqItem) => void;
  onDropCategory: (targetId: number) => void;
  onDropFaq: (targetId: number) => void;
  onEditFaq: (faq: FaqItem) => void;
  onSelectCategory: (categoryName: string) => void;
  setDraggingCategoryId: Dispatch<SetStateAction<number | null>>;
  setDraggingId: Dispatch<SetStateAction<number | null>>;
  setPendingDeleteCategory: Dispatch<SetStateAction<FaqCategory | null>>;
  getCategoryFaqCount: (categoryName: string) => number;
};

export function FaqContentPanel({
  categories,
  activeCategory,
  activeFaqs,
  deletingCategoryId,
  deletingId,
  draggingCategoryId,
  draggingId,
  onDeleteFaq,
  onDropCategory,
  onDropFaq,
  onEditFaq,
  onSelectCategory,
  setDraggingCategoryId,
  setDraggingId,
  setPendingDeleteCategory,
  getCategoryFaqCount,
}: FaqContentPanelProps) {
  return (
    <div className="rounded-lg border border-border bg-white shadow-sm">
      <div className="flex gap-2 overflow-x-auto border-b border-border px-4 py-3">
        {categories.map((category) => {
          const isActive = category.name === activeCategory;
          const count = getCategoryFaqCount(category.name);

          return (
            <div
              key={category.id}
              draggable
              onDragStart={() => setDraggingCategoryId(category.id)}
              onDragEnd={() => setDraggingCategoryId(null)}
              onDragOver={(event) => event.preventDefault()}
              onDrop={() => onDropCategory(category.id)}
              className={`flex shrink-0 items-center overflow-hidden rounded-md text-sm font-black transition ${
                draggingCategoryId === category.id
                  ? "ring-2 ring-primary/25"
                  : isActive
                    ? "bg-primary text-primary-foreground"
                    : "text-muted-foreground hover:bg-slate-100 hover:text-foreground"
              }`}
            >
              <button
                type="button"
                onClick={() => onSelectCategory(category.name)}
                className="flex h-10 items-center whitespace-nowrap px-4"
              >
                {category.name}
                <span
                  className={`ml-2 rounded-full px-2 py-0.5 text-[11px] ${
                    isActive ? "bg-white/20" : "bg-slate-100"
                  }`}
                >
                  {count}
                </span>
              </button>
              <button
                type="button"
                onClick={() => setPendingDeleteCategory(category)}
                disabled={deletingCategoryId === category.id}
                className={`grid h-10 w-10 place-items-center border-l transition disabled:cursor-not-allowed disabled:opacity-60 ${
                  isActive
                    ? "border-white/15 hover:bg-white/10"
                    : "border-border hover:bg-primary/5 hover:text-primary"
                }`}
                aria-label={`Delete ${category.name} category`}
              >
                {deletingCategoryId === category.id ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Trash2 className="h-4 w-4" />
                )}
              </button>
            </div>
          );
        })}
      </div>

      {activeFaqs.length === 0 ? (
        <div className="p-10 text-center">
          <p className="text-lg font-black text-foreground">No FAQs in this category</p>
          <p className="mt-2 text-sm font-semibold text-muted-foreground">
            Add a FAQ and it will appear inside the selected category tab.
          </p>
        </div>
      ) : (
        <div className="divide-y divide-border">
          {activeFaqs.map((faq) => (
            <FaqListItem
              key={faq.id}
              faq={faq}
              deletingId={deletingId}
              draggingId={draggingId}
              onDelete={onDeleteFaq}
              onDrop={onDropFaq}
              onEdit={onEditFaq}
              setDraggingId={setDraggingId}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function FaqListItem({
  faq,
  deletingId,
  draggingId,
  onDelete,
  onDrop,
  onEdit,
  setDraggingId,
}: {
  faq: FaqItem;
  deletingId: number | null;
  draggingId: number | null;
  onDelete: (faq: FaqItem) => void;
  onDrop: (targetId: number) => void;
  onEdit: (faq: FaqItem) => void;
  setDraggingId: Dispatch<SetStateAction<number | null>>;
}) {
  return (
    <article
      draggable
      onDragStart={() => setDraggingId(faq.id)}
      onDragEnd={() => setDraggingId(null)}
      onDragOver={(event) => event.preventDefault()}
      onDrop={() => onDrop(faq.id)}
      className={`grid cursor-grab gap-4 p-5 transition lg:grid-cols-[auto_1fr_auto] ${
        draggingId === faq.id ? "bg-primary/5" : "bg-white"
      }`}
    >
      <div className="pt-1 text-muted-foreground">
        <GripVertical className="h-5 w-5" />
      </div>
      <div>
        <div className="flex flex-wrap items-center gap-2">
          <span
            className={`rounded-full px-2.5 py-1 text-xs font-black ${
              faq.isActive ? "bg-emerald-50 text-emerald-700" : "bg-slate-100 text-muted-foreground"
            }`}
          >
            {faq.isActive ? "Active" : "Hidden"}
          </span>
          <span className="text-xs font-black uppercase tracking-[0.12em] text-muted-foreground">
            Drag to reorder
          </span>
        </div>
        <h4 className="mt-3 text-base font-black text-foreground">{faq.question}</h4>
        <p className="mt-2 whitespace-pre-line text-sm font-medium leading-relaxed text-muted-foreground">
          {faq.answer}
        </p>
      </div>
      <div className="flex items-start gap-2">
        <button
          type="button"
          onClick={() => onEdit(faq)}
          className="inline-flex items-center gap-2 rounded-md border border-border px-3 py-2 text-sm font-black text-foreground transition hover:border-primary/30 hover:text-primary"
        >
          <Edit3 className="h-4 w-4" />
          Edit
        </button>
        <button
          type="button"
          onClick={() => onDelete(faq)}
          disabled={deletingId === faq.id}
          className="inline-flex items-center gap-2 rounded-md border border-primary/20 px-3 py-2 text-sm font-black text-primary transition hover:bg-primary/5 disabled:cursor-not-allowed disabled:opacity-60"
        >
          {deletingId === faq.id ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <Trash2 className="h-4 w-4" />
          )}
          Delete
        </button>
      </div>
    </article>
  );
}

type CategoryDialogProps = {
  categoryName: string;
  isSaving: boolean;
  onClose: () => void;
  onSave: (event: FormEvent<HTMLFormElement>) => void;
  setCategoryName: Dispatch<SetStateAction<string>>;
};

export function CategoryFormDialog({
  categoryName,
  isSaving,
  onClose,
  onSave,
  setCategoryName,
}: CategoryDialogProps) {
  return (
    <div className="fixed inset-0 z-[70] grid place-items-center bg-slate-950/45 px-4">
      <div className="w-full max-w-lg rounded-lg border border-border bg-white p-5 shadow-2xl">
        <DialogHeader
          eyebrow="Add category"
          title="Create a tab for FAQ questions"
          onClose={onClose}
          closeLabel="Close category form"
        />

        <form onSubmit={onSave} className="mt-5 space-y-4">
          <label className="block">
            <span className="text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
              Category name
            </span>
            <input
              required
              minLength={2}
              maxLength={100}
              value={categoryName}
              onChange={(event) => setCategoryName(event.target.value)}
              className="mt-2 h-11 w-full rounded-md border border-input bg-white px-3 text-sm font-bold text-foreground outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10"
              placeholder="Booking and service"
            />
          </label>

          <DialogActions
            cancelLabel="Cancel"
            submitLabel="Save category"
            isSaving={isSaving}
            onCancel={onClose}
          />
        </form>
      </div>
    </div>
  );
}

type FaqFormDialogProps = {
  categories: FaqCategory[];
  form: FaqFormState;
  isSaving: boolean;
  onClose: () => void;
  onSave: (event: FormEvent<HTMLFormElement>) => void;
  setForm: Dispatch<SetStateAction<FaqFormState>>;
};

export function FaqFormDialog({
  categories,
  form,
  isSaving,
  onClose,
  onSave,
  setForm,
}: FaqFormDialogProps) {
  return (
    <div className="fixed inset-0 z-[70] grid place-items-center bg-slate-950/45 px-4">
      <div className="max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-lg border border-border bg-white p-5 shadow-2xl">
        <DialogHeader
          eyebrow={form.id ? "Edit FAQ" : "Add FAQ"}
          title="Select the category tab for this question"
          onClose={onClose}
          closeLabel="Close FAQ form"
        />

        <form onSubmit={onSave} className="mt-5 space-y-4">
          <label className="block">
            <span className="text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
              Category
            </span>
            <select
              required
              value={form.category}
              onChange={(event) => setForm({ ...form, category: event.target.value })}
              className="mt-2 h-11 w-full rounded-md border border-input bg-white px-3 text-sm font-bold text-foreground outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10"
            >
              {categories.map((category) => (
                <option key={category.id} value={category.name}>
                  {category.name}
                </option>
              ))}
            </select>
          </label>

          <label className="block">
            <span className="text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
              Question
            </span>
            <input
              required
              value={form.question}
              onChange={(event) => setForm({ ...form, question: event.target.value })}
              className="mt-2 h-11 w-full rounded-md border border-input bg-white px-3 text-sm font-bold text-foreground outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10"
              placeholder="How do I book a doorstep service?"
            />
          </label>

          <label className="block">
            <span className="text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
              Answer
            </span>
            <textarea
              required
              value={form.answer}
              onChange={(event) => setForm({ ...form, answer: event.target.value })}
              className="mt-2 min-h-36 w-full rounded-md border border-input bg-white px-3 py-3 text-sm font-bold leading-relaxed text-foreground outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10"
              placeholder="Write the answer customers should see."
            />
          </label>

          <label className="flex h-11 items-center gap-3 rounded-md border border-border px-3">
            <input
              type="checkbox"
              checked={form.isActive}
              onChange={(event) => setForm({ ...form, isActive: event.target.checked })}
              className="h-4 w-4 accent-primary"
            />
            <span className="text-sm font-black text-foreground">Show on public page</span>
          </label>

          <DialogActions
            cancelLabel="Cancel"
            submitLabel="Save FAQ"
            isSaving={isSaving}
            onCancel={onClose}
          />
        </form>
      </div>
    </div>
  );
}

type DeleteCategoryDialogProps = {
  category: FaqCategory;
  count: number;
  deletingCategoryId: number | null;
  onCancel: () => void;
  onConfirm: (category: FaqCategory) => void;
};

export function DeleteCategoryDialog({
  category,
  count,
  deletingCategoryId,
  onCancel,
  onConfirm,
}: DeleteCategoryDialogProps) {
  const isDeleting = deletingCategoryId === category.id;

  return (
    <div className="fixed inset-0 z-[80] grid place-items-center bg-slate-950/45 px-4">
      <div className="w-full max-w-lg rounded-lg border border-border bg-white p-5 shadow-2xl">
        <div className="flex items-start gap-4">
          <div className="grid h-11 w-11 shrink-0 place-items-center rounded-md bg-primary/10 text-primary">
            <Trash2 className="h-5 w-5" />
          </div>
          <div>
            <p className="text-xs font-black uppercase tracking-[0.16em] text-primary">
              Delete category
            </p>
            <h2 className="mt-1 text-xl font-black tracking-tight text-foreground">
              Delete {category.name}?
            </h2>
            <p className="mt-3 text-sm font-semibold leading-relaxed text-muted-foreground">
              {count > 0
                ? `This will also remove ${count} FAQ${count === 1 ? "" : "s"} inside this category.`
                : "This category has no FAQs inside it."}
            </p>
          </div>
        </div>

        <div className="mt-6 flex justify-end gap-3">
          <button
            type="button"
            onClick={onCancel}
            disabled={isDeleting}
            className="rounded-md border border-border px-4 py-2.5 text-sm font-black text-foreground transition hover:bg-slate-100 disabled:cursor-not-allowed disabled:opacity-60"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={() => onConfirm(category)}
            disabled={isDeleting}
            className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2.5 text-sm font-black text-primary-foreground transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-70"
          >
            {isDeleting ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Trash2 className="h-4 w-4" />
            )}
            Delete category
          </button>
        </div>
      </div>
    </div>
  );
}

function DialogHeader({
  eyebrow,
  title,
  closeLabel,
  onClose,
}: {
  eyebrow: string;
  title: string;
  closeLabel: string;
  onClose: () => void;
}) {
  return (
    <div className="flex items-start justify-between gap-4">
      <div>
        <p className="text-xs font-black uppercase tracking-[0.16em] text-primary">{eyebrow}</p>
        <h2 className="mt-1 text-xl font-black tracking-tight text-foreground">{title}</h2>
      </div>
      <button
        type="button"
        onClick={onClose}
        className="grid h-9 w-9 place-items-center rounded-md text-muted-foreground hover:bg-slate-100"
        aria-label={closeLabel}
      >
        <X className="h-5 w-5" />
      </button>
    </div>
  );
}

function DialogActions({
  cancelLabel,
  submitLabel,
  isSaving,
  onCancel,
}: {
  cancelLabel: string;
  submitLabel: string;
  isSaving: boolean;
  onCancel: () => void;
}) {
  return (
    <div className="flex justify-end gap-3 pt-2">
      <button
        type="button"
        onClick={onCancel}
        className="rounded-md border border-border px-4 py-2.5 text-sm font-black text-foreground transition hover:bg-slate-100"
      >
        {cancelLabel}
      </button>
      <button
        type="submit"
        disabled={isSaving}
        className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2.5 text-sm font-black text-primary-foreground transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-70"
      >
        {isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
        {submitLabel}
      </button>
    </div>
  );
}
