"use client";

import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import { Plus, Pencil, Trash2, X, ChevronUp, ChevronDown, Eye, EyeOff, GripVertical } from "lucide-react";
import { cn } from "@/lib/utils";

interface FaqItem {
  id: string;
  question: string;
  answer: string;
  order: number;
  showOnHomepage: boolean;
}

interface FaqForm {
  question: string;
  answer: string;
  showOnHomepage: boolean;
}

const emptyForm: FaqForm = {
  question: "",
  answer: "",
  showOnHomepage: true,
};

export default function FaqAdminPage() {
  const [faqs, setFaqs] = useState<FaqItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<FaqForm>(emptyForm);
  const [saving, setSaving] = useState(false);
  const [dragIndex, setDragIndex] = useState<number | null>(null);
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);

  const loadFaqs = async () => {
    try {
      const data = await api.getAllFaqs();
      setFaqs(data);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadFaqs();
  }, []);

  const openCreate = () => {
    setForm(emptyForm);
    setEditingId(null);
    setShowForm(true);
  };

  const openEdit = (faq: FaqItem) => {
    setForm({
      question: faq.question,
      answer: faq.answer,
      showOnHomepage: faq.showOnHomepage,
    });
    setEditingId(faq.id);
    setShowForm(true);
  };

  const handleSave = async () => {
    if (!form.question.trim() || !form.answer.trim()) return;
    setSaving(true);
    setError("");
    try {
      if (editingId) {
        await api.updateFaq(editingId, form);
      } else {
        await api.createFaq(form);
      }
      setShowForm(false);
      setEditingId(null);
      await loadFaqs();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this FAQ?")) return;
    try {
      await api.deleteFaq(id);
      await loadFaqs();
    } catch (err: any) {
      setError(err.message);
    }
  };

  const handleToggleHomepage = async (faq: FaqItem) => {
    try {
      await api.updateFaq(faq.id, { showOnHomepage: !faq.showOnHomepage });
      setFaqs((prev) =>
        prev.map((f) =>
          f.id === faq.id ? { ...f, showOnHomepage: !faq.showOnHomepage } : f
        )
      );
    } catch (err: any) {
      setError(err.message);
    }
  };

  const moveItem = async (index: number, direction: "up" | "down") => {
    const newFaqs = [...faqs];
    const targetIndex = direction === "up" ? index - 1 : index + 1;
    if (targetIndex < 0 || targetIndex >= newFaqs.length) return;

    [newFaqs[index], newFaqs[targetIndex]] = [newFaqs[targetIndex], newFaqs[index]];
    const reordered = newFaqs.map((f, i) => ({ ...f, order: i }));
    setFaqs(reordered);

    try {
      await api.reorderFaqs(reordered.map((f) => ({ id: f.id, order: f.order })));
    } catch (err: any) {
      setError(err.message);
      await loadFaqs();
    }
  };

  // Drag-and-drop handlers
  const handleDragStart = (index: number) => {
    setDragIndex(index);
  };

  const handleDragEnter = (index: number) => {
    setDragOverIndex(index);
  };

  const handleDragEnd = async () => {
    if (dragIndex === null || dragOverIndex === null || dragIndex === dragOverIndex) {
      setDragIndex(null);
      setDragOverIndex(null);
      return;
    }

    const newFaqs = [...faqs];
    const [moved] = newFaqs.splice(dragIndex, 1);
    newFaqs.splice(dragOverIndex, 0, moved);
    const reordered = newFaqs.map((f, i) => ({ ...f, order: i }));
    setFaqs(reordered);
    setDragIndex(null);
    setDragOverIndex(null);

    try {
      await api.reorderFaqs(reordered.map((f) => ({ id: f.id, order: f.order })));
    } catch (err: any) {
      setError(err.message);
      await loadFaqs();
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-on-surface/50">Loading FAQs...</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-on-surface">FAQ Management</h1>
          <p className="text-on-surface/50 text-sm mt-1">
            Drag to reorder · toggle visibility on homepage
          </p>
        </div>
        <button
          onClick={openCreate}
          className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-sm hover:opacity-90 transition-opacity"
        >
          <Plus size={16} />
          Add FAQ
        </button>
      </div>

      {error && <p className="text-error text-sm">{error}</p>}

      {showForm && (
        <div className="bg-surface-container-low rounded-xl p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-on-surface">
              {editingId ? "Edit FAQ" : "Add FAQ"}
            </h2>
            <button
              onClick={() => setShowForm(false)}
              className="text-on-surface/50 hover:text-on-surface"
            >
              <X size={20} />
            </button>
          </div>
          <div className="space-y-4">
            <input
              placeholder="Question"
              value={form.question}
              onChange={(e) => setForm({ ...form, question: e.target.value })}
              className="bg-surface-container-highest text-on-surface rounded-lg px-4 py-3 w-full focus:outline-none focus:ring-1 focus:ring-primary/40"
            />
            <textarea
              placeholder="Answer"
              value={form.answer}
              onChange={(e) => setForm({ ...form, answer: e.target.value })}
              rows={4}
              className="bg-surface-container-highest text-on-surface rounded-lg px-4 py-3 w-full focus:outline-none focus:ring-1 focus:ring-primary/40 resize-none"
            />
            <label className="flex items-center gap-3 cursor-pointer select-none">
              <div
                onClick={() => setForm({ ...form, showOnHomepage: !form.showOnHomepage })}
                className={cn(
                  "w-11 h-6 rounded-full relative transition-colors",
                  form.showOnHomepage ? "bg-primary" : "bg-surface-container-highest"
                )}
              >
                <div
                  className={cn(
                    "absolute top-1 w-4 h-4 rounded-full bg-white shadow transition-transform",
                    form.showOnHomepage ? "translate-x-6" : "translate-x-1"
                  )}
                />
              </div>
              <span className="text-on-surface/80 text-sm">Show on homepage</span>
            </label>
          </div>
          <div className="flex gap-3 mt-4">
            <button
              onClick={handleSave}
              disabled={saving || !form.question.trim() || !form.answer.trim()}
              className="px-6 py-2 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-sm hover:opacity-90 transition-opacity disabled:opacity-50"
            >
              {saving ? "Saving..." : "Save"}
            </button>
            <button
              onClick={() => setShowForm(false)}
              className="px-6 py-2 rounded-lg bg-surface-container-highest text-on-surface font-semibold text-sm hover:bg-surface-container-high transition-colors"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      <div className="space-y-2">
        {faqs.length === 0 ? (
          <div className="bg-surface-container-low rounded-xl p-12 text-center">
            <p className="text-on-surface/40 text-sm">No FAQs yet. Add one to get started.</p>
          </div>
        ) : (
          faqs.map((faq, index) => (
            <div
              key={faq.id}
              draggable
              onDragStart={() => handleDragStart(index)}
              onDragEnter={() => handleDragEnter(index)}
              onDragEnd={handleDragEnd}
              onDragOver={(e) => e.preventDefault()}
              className={cn(
                "bg-surface-container-low rounded-xl p-5 flex items-start gap-4 transition-all",
                dragOverIndex === index && dragIndex !== index
                  ? "ring-2 ring-primary/50 bg-surface-container"
                  : "",
                dragIndex === index ? "opacity-50" : ""
              )}
            >
              {/* Drag handle */}
              <div className="mt-1 cursor-grab active:cursor-grabbing text-on-surface/30 hover:text-on-surface/60 shrink-0">
                <GripVertical size={18} />
              </div>

              {/* Content */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-1">
                  <p className="text-on-surface font-semibold truncate">{faq.question}</p>
                  {faq.showOnHomepage ? (
                    <span className="shrink-0 text-xs bg-green-900/30 text-green-400 rounded-full px-2 py-0.5 font-medium">
                      Homepage
                    </span>
                  ) : (
                    <span className="shrink-0 text-xs bg-surface-container-highest text-on-surface/40 rounded-full px-2 py-0.5 font-medium">
                      Hidden
                    </span>
                  )}
                </div>
                <p className="text-on-surface/50 text-sm line-clamp-2">{faq.answer}</p>
              </div>

              {/* Actions */}
              <div className="flex items-center gap-1 shrink-0">
                <button
                  onClick={() => moveItem(index, "up")}
                  disabled={index === 0}
                  className="p-2 rounded-lg hover:bg-surface-container-high text-on-surface/40 hover:text-on-surface disabled:opacity-20 transition-colors"
                  title="Move up"
                >
                  <ChevronUp size={16} />
                </button>
                <button
                  onClick={() => moveItem(index, "down")}
                  disabled={index === faqs.length - 1}
                  className="p-2 rounded-lg hover:bg-surface-container-high text-on-surface/40 hover:text-on-surface disabled:opacity-20 transition-colors"
                  title="Move down"
                >
                  <ChevronDown size={16} />
                </button>
                <button
                  onClick={() => handleToggleHomepage(faq)}
                  className={cn(
                    "p-2 rounded-lg transition-colors",
                    faq.showOnHomepage
                      ? "hover:bg-surface-container-high text-green-400 hover:text-on-surface"
                      : "hover:bg-surface-container-high text-on-surface/40 hover:text-on-surface"
                  )}
                  title={faq.showOnHomepage ? "Hide from homepage" : "Show on homepage"}
                >
                  {faq.showOnHomepage ? <Eye size={16} /> : <EyeOff size={16} />}
                </button>
                <button
                  onClick={() => openEdit(faq)}
                  className="p-2 rounded-lg hover:bg-surface-container-high text-on-surface/40 hover:text-on-surface transition-colors"
                  title="Edit"
                >
                  <Pencil size={16} />
                </button>
                <button
                  onClick={() => handleDelete(faq.id)}
                  className="p-2 rounded-lg hover:bg-error-container/30 text-on-surface/40 hover:text-error transition-colors"
                  title="Delete"
                >
                  <Trash2 size={16} />
                </button>
              </div>
            </div>
          ))
        )}
      </div>

      {faqs.length > 0 && (
        <p className="text-on-surface/30 text-xs text-center">
          {faqs.filter((f) => f.showOnHomepage).length} of {faqs.length} shown on homepage
        </p>
      )}
    </div>
  );
}
