"use client";

import { useState, useEffect, useCallback } from "react";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  Plus,
  Search,
  Edit2,
  Trash2,
  Eye,
  EyeOff,
  ChevronDown,
  ChevronUp,
  RefreshCw,
  Save,
  X,
  BookOpen,
  DollarSign,
  Wrench,
  MessageSquare,
  Clock,
  GripVertical,
} from "lucide-react";

interface FAQ {
  id: string;
  category: string;
  question: string;
  questionAr: string;
  answer: string;
  answerAr: string;
  order: number;
  isPublished: boolean;
  createdAt: string;
  updatedAt: string;
}

interface FAQStats {
  total: number;
  published: number;
  draft: number;
  byCategory: Record<string, number>;
}

interface StaffUser {
  id: string;
  role: string;
  name?: string;
}

interface FAQManagementProps {
  user: StaffUser;
}

const CATEGORIES = [
  {
    value: "GETTING_STARTED",
    label: "Getting Started",
    labelAr: "البدء",
    icon: BookOpen,
  },
  {
    value: "BILLING",
    label: "Billing & Plans",
    labelAr: "الفواتير والباقات",
    icon: DollarSign,
  },
  { value: "TECHNICAL", label: "Technical", labelAr: "تقني", icon: Wrench },
  {
    value: "WHATSAPP",
    label: "WhatsApp Integration",
    labelAr: "تكامل واتساب",
    icon: MessageSquare,
  },
  {
    value: "APPOINTMENTS",
    label: "Appointments",
    labelAr: "المواعيد",
    icon: Clock,
  },
] as const;

export default function FAQManagement({ user }: FAQManagementProps) {
  const canManage = user.role === "ADMIN" || user.role === "SUPER_ADMIN";

  const [faqs, setFaqs] = useState<FAQ[]>([]);
  const [stats, setStats] = useState<FAQStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [categoryFilter, setCategoryFilter] = useState<string>("");
  const [publishedFilter, setPublishedFilter] = useState<string>("");

  // Modal state
  const [showModal, setShowModal] = useState(false);
  const [editingFaq, setEditingFaq] = useState<FAQ | null>(null);
  const [submitting, setSubmitting] = useState(false);

  // Form state
  const [formData, setFormData] = useState({
    category: "GETTING_STARTED",
    question: "",
    questionAr: "",
    answer: "",
    answerAr: "",
    isPublished: false,
  });

  // Expanded FAQs for preview
  const [expandedId, setExpandedId] = useState<string | null>(null);

  // Fetch FAQs
  const fetchFaqs = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (categoryFilter) params.set("category", categoryFilter);
      if (publishedFilter) params.set("published", publishedFilter);
      if (searchQuery) params.set("search", searchQuery);

      const res = await fetch(`/api/staff/dashboard/support/faqs?${params}`);
      if (res.ok) {
        const data = await res.json();
        setFaqs(data.faqs || []);
        setStats(data.stats || null);
      }
    } catch (error) {
      console.error("Failed to fetch FAQs:", error);
    } finally {
      setLoading(false);
    }
  }, [categoryFilter, publishedFilter, searchQuery]);

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

  // Open modal for create/edit
  const openModal = (faq?: FAQ) => {
    if (faq) {
      setEditingFaq(faq);
      setFormData({
        category: faq.category,
        question: faq.question,
        questionAr: faq.questionAr,
        answer: faq.answer,
        answerAr: faq.answerAr,
        isPublished: faq.isPublished,
      });
    } else {
      setEditingFaq(null);
      setFormData({
        category: "GETTING_STARTED",
        question: "",
        questionAr: "",
        answer: "",
        answerAr: "",
        isPublished: false,
      });
    }
    setShowModal(true);
  };

  // Close modal
  const closeModal = () => {
    setShowModal(false);
    setEditingFaq(null);
  };

  // Handle form submit
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);

    try {
      const url = editingFaq
        ? `/api/staff/dashboard/support/faqs/${editingFaq.id}`
        : "/api/staff/dashboard/support/faqs";

      const res = await fetchWithCSRF(url, {
        method: editingFaq ? "PUT" : "POST",
        body: JSON.stringify(formData),
      });

      if (res.ok) {
        closeModal();
        fetchFaqs();
      } else {
        const err = await res.json();
        alert(err.error || "Failed to save FAQ");
      }
    } catch (error) {
      console.error("Failed to save FAQ:", error);
      alert("Failed to save FAQ");
    } finally {
      setSubmitting(false);
    }
  };

  // Toggle publish status
  const togglePublish = async (faq: FAQ) => {
    try {
      const res = await fetch(`/api/staff/dashboard/support/faqs/${faq.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ isPublished: !faq.isPublished }),
      });

      if (res.ok) {
        fetchFaqs();
      }
    } catch (error) {
      console.error("Failed to toggle publish:", error);
    }
  };

  // Delete FAQ
  const deleteFaq = async (faq: FAQ) => {
    if (!confirm(`Delete FAQ: "${faq.question}"?`)) return;

    try {
      const res = await fetch(`/api/staff/dashboard/support/faqs/${faq.id}`, {
        method: "DELETE",
      });

      if (res.ok) {
        fetchFaqs();
      }
    } catch (error) {
      console.error("Failed to delete FAQ:", error);
    }
  };

  // Get category info
  const getCategoryInfo = (category: string) => {
    return CATEGORIES.find((c) => c.value === category) || CATEGORIES[0];
  };

  return (
    <div className="space-y-6">
      {/* Stats */}
      {stats && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="bg-white rounded-xl border border-slate-200 p-4">
            <p className="text-sm text-slate-500">Total FAQs</p>
            <p className="text-2xl font-bold text-slate-900">{stats.total}</p>
          </div>
          <div className="bg-white rounded-xl border border-slate-200 p-4">
            <p className="text-sm text-slate-500">Published</p>
            <p className="text-2xl font-bold text-green-600">
              {stats.published}
            </p>
          </div>
          <div className="bg-white rounded-xl border border-slate-200 p-4">
            <p className="text-sm text-slate-500">Draft</p>
            <p className="text-2xl font-bold text-amber-600">{stats.draft}</p>
          </div>
          <div className="bg-white rounded-xl border border-slate-200 p-4">
            <p className="text-sm text-slate-500">Categories</p>
            <p className="text-2xl font-bold text-slate-900">
              {Object.keys(stats.byCategory).length}
            </p>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="flex flex-col md:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search FAQs..."
            className="w-full pl-10 pr-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
          />
        </div>
        <select
          value={categoryFilter}
          onChange={(e) => setCategoryFilter(e.target.value)}
          className="px-4 py-2.5 border border-slate-200 rounded-xl bg-white focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
        >
          <option value="">All Categories</option>
          {CATEGORIES.map((cat) => (
            <option key={cat.value} value={cat.value}>
              {cat.label}
            </option>
          ))}
        </select>
        <select
          value={publishedFilter}
          onChange={(e) => setPublishedFilter(e.target.value)}
          className="px-4 py-2.5 border border-slate-200 rounded-xl bg-white focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
        >
          <option value="">All Status</option>
          <option value="true">Published</option>
          <option value="false">Draft</option>
        </select>
        <button
          onClick={fetchFaqs}
          disabled={loading}
          className="px-4 py-2.5 border border-slate-200 rounded-xl hover:bg-slate-50 transition-colors"
        >
          <RefreshCw className={`w-5 h-5 ${loading ? "animate-spin" : ""}`} />
        </button>
        {canManage && (
          <button
            onClick={() => openModal()}
            className="flex items-center gap-2 px-4 py-2.5 bg-brand-green text-white rounded-xl font-semibold hover:bg-brand-greenHover transition-colors"
          >
            <Plus className="w-5 h-5" />
            Add FAQ
          </button>
        )}
      </div>

      {/* FAQ List */}
      <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden">
        {loading ? (
          <div className="p-12 text-center">
            <RefreshCw className="w-8 h-8 animate-spin mx-auto text-slate-400" />
            <p className="text-slate-500 mt-3">Loading FAQs...</p>
          </div>
        ) : faqs.length === 0 ? (
          <div className="p-12 text-center">
            <BookOpen className="w-12 h-12 mx-auto text-slate-300" />
            <p className="font-semibold text-slate-700 mt-4">No FAQs found</p>
            <p className="text-slate-500 text-sm mt-1">
              {canManage
                ? 'Click "Add FAQ" to create one'
                : "No FAQs have been created yet"}
            </p>
          </div>
        ) : (
          <div className="divide-y divide-slate-100">
            {faqs.map((faq) => {
              const catInfo = getCategoryInfo(faq.category);
              const CatIcon = catInfo.icon;
              const isExpanded = expandedId === faq.id;

              return (
                <div
                  key={faq.id}
                  className="hover:bg-slate-50 transition-colors"
                >
                  <div className="p-4 flex items-start gap-4">
                    {canManage && (
                      <div className="text-slate-300 cursor-grab">
                        <GripVertical className="w-5 h-5" />
                      </div>
                    )}
                    <div
                      className={`p-2 rounded-lg ${faq.isPublished ? "bg-brand-green/10 text-brand-green" : "bg-slate-100 text-slate-500"}`}
                    >
                      <CatIcon className="w-5 h-5" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <h4 className="font-semibold text-slate-900">
                          {faq.question}
                        </h4>
                        {faq.isPublished ? (
                          <span className="px-2 py-0.5 bg-green-100 text-green-700 text-xs font-medium rounded-full">
                            Published
                          </span>
                        ) : (
                          <span className="px-2 py-0.5 bg-amber-100 text-amber-700 text-xs font-medium rounded-full">
                            Draft
                          </span>
                        )}
                      </div>
                      <p
                        className="text-sm text-slate-500 mt-1 line-clamp-1"
                        dir="rtl"
                      >
                        {faq.questionAr}
                      </p>
                      <p className="text-xs text-slate-400 mt-2">
                        {catInfo.label} • Order: {faq.order}
                      </p>
                    </div>
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() =>
                          setExpandedId(isExpanded ? null : faq.id)
                        }
                        className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-colors"
                        title="Preview"
                      >
                        {isExpanded ? (
                          <ChevronUp className="w-5 h-5" />
                        ) : (
                          <ChevronDown className="w-5 h-5" />
                        )}
                      </button>
                      {canManage && (
                        <>
                          <button
                            onClick={() => togglePublish(faq)}
                            className={`p-2 rounded-lg transition-colors ${
                              faq.isPublished
                                ? "text-green-600 hover:bg-green-50"
                                : "text-slate-400 hover:bg-slate-100"
                            }`}
                            title={faq.isPublished ? "Unpublish" : "Publish"}
                          >
                            {faq.isPublished ? (
                              <Eye className="w-5 h-5" />
                            ) : (
                              <EyeOff className="w-5 h-5" />
                            )}
                          </button>
                          <button
                            onClick={() => openModal(faq)}
                            className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                            title="Edit"
                          >
                            <Edit2 className="w-5 h-5" />
                          </button>
                          <button
                            onClick={() => deleteFaq(faq)}
                            className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                            title="Delete"
                          >
                            <Trash2 className="w-5 h-5" />
                          </button>
                        </>
                      )}
                    </div>
                  </div>
                  {/* Expanded Preview */}
                  {isExpanded && (
                    <div className="px-4 pb-4 ml-14">
                      <div className="grid md:grid-cols-2 gap-4">
                        <div className="p-4 bg-slate-50 rounded-xl">
                          <p className="text-xs font-medium text-slate-500 mb-2">
                            Answer (English)
                          </p>
                          <p className="text-sm text-slate-700 whitespace-pre-line">
                            {faq.answer}
                          </p>
                        </div>
                        <div className="p-4 bg-slate-50 rounded-xl" dir="rtl">
                          <p className="text-xs font-medium text-slate-500 mb-2">
                            الإجابة (عربي)
                          </p>
                          <p className="text-sm text-slate-700 whitespace-pre-line">
                            {faq.answerAr}
                          </p>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Create/Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto">
            <div className="sticky top-0 bg-white border-b border-slate-200 p-4 flex items-center justify-between">
              <h3 className="text-lg font-bold text-slate-900">
                {editingFaq ? "Edit FAQ" : "Create New FAQ"}
              </h3>
              <button
                onClick={closeModal}
                className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleSubmit} className="p-6 space-y-6">
              {/* Category */}
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2">
                  Category
                </label>
                <select
                  value={formData.category}
                  onChange={(e) =>
                    setFormData((f) => ({ ...f, category: e.target.value }))
                  }
                  className="w-full px-4 py-3 border border-slate-200 rounded-xl bg-white focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
                  required
                >
                  {CATEGORIES.map((cat) => (
                    <option key={cat.value} value={cat.value}>
                      {cat.label}
                    </option>
                  ))}
                </select>
              </div>

              {/* Question English */}
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2">
                  Question (English)
                </label>
                <input
                  type="text"
                  value={formData.question}
                  onChange={(e) =>
                    setFormData((f) => ({ ...f, question: e.target.value }))
                  }
                  placeholder="Enter question in English..."
                  className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
                  required
                  minLength={5}
                />
              </div>

              {/* Question Arabic */}
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2">
                  Question (Arabic)
                </label>
                <input
                  type="text"
                  value={formData.questionAr}
                  onChange={(e) =>
                    setFormData((f) => ({ ...f, questionAr: e.target.value }))
                  }
                  placeholder="أدخل السؤال بالعربية..."
                  className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
                  dir="rtl"
                  required
                  minLength={5}
                />
              </div>

              {/* Answer English */}
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2">
                  Answer (English)
                </label>
                <textarea
                  value={formData.answer}
                  onChange={(e) =>
                    setFormData((f) => ({ ...f, answer: e.target.value }))
                  }
                  placeholder="Enter detailed answer in English..."
                  className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green resize-none"
                  rows={5}
                  required
                  minLength={10}
                />
                <p className="text-xs text-slate-500 mt-1">
                  Use numbered lists (1. 2. 3.) or bullet points for steps
                </p>
              </div>

              {/* Answer Arabic */}
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2">
                  Answer (Arabic)
                </label>
                <textarea
                  value={formData.answerAr}
                  onChange={(e) =>
                    setFormData((f) => ({ ...f, answerAr: e.target.value }))
                  }
                  placeholder="أدخل الإجابة المفصلة بالعربية..."
                  className="w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green resize-none"
                  rows={5}
                  dir="rtl"
                  required
                  minLength={10}
                />
              </div>

              {/* Publish Toggle */}
              <div className="flex items-center gap-3">
                <input
                  type="checkbox"
                  id="isPublished"
                  checked={formData.isPublished}
                  onChange={(e) =>
                    setFormData((f) => ({
                      ...f,
                      isPublished: e.target.checked,
                    }))
                  }
                  className="w-5 h-5 rounded border-slate-300 text-brand-green focus:ring-brand-green/20"
                />
                <label
                  htmlFor="isPublished"
                  className="text-sm font-medium text-slate-700"
                >
                  Publish immediately (visible to users)
                </label>
              </div>

              {/* Actions */}
              <div className="flex justify-end gap-3 pt-4 border-t border-slate-200">
                <button
                  type="button"
                  onClick={closeModal}
                  className="px-6 py-2.5 border border-slate-200 rounded-xl text-slate-700 font-medium hover:bg-slate-50 transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={submitting}
                  className="flex items-center gap-2 px-6 py-2.5 bg-brand-green text-white rounded-xl font-semibold hover:bg-brand-greenHover transition-colors disabled:opacity-50"
                >
                  {submitting ? (
                    <>
                      <RefreshCw className="w-5 h-5 animate-spin" />
                      Saving...
                    </>
                  ) : (
                    <>
                      <Save className="w-5 h-5" />
                      {editingFaq ? "Update FAQ" : "Create FAQ"}
                    </>
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
