"use client"

import { useState, useEffect, useCallback } from "react"
import { Plus, Pencil, Trash2, HelpCircle, X, GripVertical } from "lucide-react"

interface FAQ {
  id: string
  questionAr: string
  questionEn: string
  answerAr: string
  answerEn: string
  category: string
  order: number
  isActive: boolean
}

interface FAQFormData {
  questionAr: string
  questionEn: string
  answerAr: string
  answerEn: string
  category: string
  order: string
  isActive: string
}

const emptyForm: FAQFormData = {
  questionAr: "",
  questionEn: "",
  answerAr: "",
  answerEn: "",
  category: "",
  order: "0",
  isActive: "true",
}

export default function FAQsManagement() {
  const [faqs, setFaqs] = useState<FAQ[]>([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [editingFaq, setEditingFaq] = useState<FAQ | null>(null)
  const [form, setForm] = useState<FAQFormData>(emptyForm)
  const [submitting, setSubmitting] = useState(false)
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null)

  const fetchFaqs = useCallback(async () => {
    try {
      setLoading(true)
      const res = await fetch("/api/admin/faqs")
      const json = await res.json()
      setFaqs(json.data ?? json.faqs ?? [])
    } catch {
      setFaqs([])
    } finally {
      setLoading(false)
    }
  }, [])

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

  const openAddModal = () => {
    setEditingFaq(null)
    setForm(emptyForm)
    setShowModal(true)
  }

  const openEditModal = (faq: FAQ) => {
    setEditingFaq(faq)
    setForm({
      questionAr: faq.questionAr,
      questionEn: faq.questionEn,
      answerAr: faq.answerAr,
      answerEn: faq.answerEn,
      category: faq.category,
      order: String(faq.order),
      isActive: String(faq.isActive),
    })
    setShowModal(true)
  }

  const closeModal = () => {
    setShowModal(false)
    setEditingFaq(null)
    setForm(emptyForm)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSubmitting(true)

    try {
      const payload: Record<string, unknown> = {
        questionAr: form.questionAr,
        questionEn: form.questionEn,
        answerAr: form.answerAr,
        answerEn: form.answerEn,
        category: form.category,
        order: Number(form.order) || 0,
        isActive: form.isActive === "true",
      }

      if (editingFaq) {
        await fetch(`/api/admin/faqs/${editingFaq.id}`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        })
      } else {
        await fetch("/api/admin/faqs", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        })
      }

      await fetchFaqs()
      closeModal()
    } catch {
      // silently fail
    } finally {
      setSubmitting(false)
    }
  }

  const handleDelete = async (id: string) => {
    try {
      await fetch(`/api/admin/faqs/${id}`, { method: "DELETE" })
      setDeleteConfirmId(null)
      await fetchFaqs()
    } catch {
      // silently fail
    }
  }

  const handleFieldChange = (field: keyof FAQFormData, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }))
  }

  const categories = [...new Set(faqs.map((f) => f.category).filter(Boolean))]

  return (
    <div className="space-y-6 dark:bg-[#0b1120] min-h-screen p-6">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div className="flex items-center gap-3">
           <HelpCircle className="w-8 h-8 text-blue-600 dark:text-[#60a5fa]" />
          <div>
            <h1 className="text-2xl font-bold text-gray-800 dark:text-[#f1f5f9]">إدارة الأسئلة الشائعة</h1>
            <p className="text-sm text-gray-500 dark:text-[#94a3b8]">إدارة الأسئلة المتكررة</p>
          </div>
        </div>
        <button
          onClick={openAddModal}
          className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium"
        >
          <Plus className="w-4 h-4" />
          إضافة سؤال
        </button>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden dark:bg-[#1a2332] dark:border-[#2a3d56]">
        {loading ? (
          <div className="flex items-center justify-center py-20 text-gray-400 dark:text-[#94a3b8]">
            <HelpCircle className="h-5 w-5 animate-spin mr-2 dark:text-[#60a5fa]" />
            جاري تحميل الأسئلة...
          </div>
        ) : faqs.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-gray-400 dark:text-[#94a3b8]">
            <HelpCircle className="h-12 w-12 mb-3 opacity-40 dark:text-[#60a5fa]" />
            <p className="text-sm">لا توجد أسئلة</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-100 bg-gray-50/60 dark:bg-[#111927] dark:border-[#2a3d56]">
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider w-8 dark:text-[#94a3b8]">
                    <GripVertical className="h-4 w-4 text-gray-400 dark:text-[#94a3b8]" />
                  </th>
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider dark:text-[#94a3b8]">
                    السؤال بالعربية
                  </th>
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider dark:text-[#94a3b8]">
                    التصنيف
                  </th>
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider dark:text-[#94a3b8]">
                    الترتيب
                  </th>
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider dark:text-[#94a3b8]">
                    الحالة
                  </th>
                  <th className="px-6 py-3.5 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider dark:text-[#94a3b8]">
                    الإجراءات
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 dark:divide-[#253347]">
                {faqs.map((faq) => (
                  <tr
                    key={faq.id}
                    className="hover:bg-gray-50/50 transition-colors dark:hover:bg-[#1e2d42]"
                  >
                    <td className="px-6 py-4">
                      <GripVertical className="h-4 w-4 text-gray-300 cursor-grab dark:text-[#94a3b8]" />
                    </td>
                    <td className="px-6 py-4">
                      <div className="max-w-md">
                        <p className="font-medium text-gray-900 text-sm line-clamp-2 dark:text-[#f1f5f9]">{faq.questionAr}</p>
                        <p className="text-xs text-gray-400 mt-0.5 line-clamp-1 dark:text-[#94a3b8]">{faq.questionEn}</p>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      {faq.category ? (
                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700 border border-gray-200 dark:bg-[#111927] dark:text-[#cbd5e1] dark:border-[#2a3d56]">
                          {faq.category}
                        </span>
                      ) : (
                        <span className="text-gray-400 text-xs">-</span>
                      )}
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-600 dark:text-[#cbd5e1]">
                      {faq.order}
                    </td>
                    <td className="px-6 py-4">
                      <span
                        className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                          faq.isActive
                            ? "bg-green-100 text-green-800 border border-green-200 dark:bg-[#0d2818] dark:text-[#34d399] dark:border-[#1a3a2a]"
                            : "bg-gray-100 text-gray-600 border border-gray-200 dark:bg-[#111927] dark:text-[#94a3b8] dark:border-[#2a3d56]"
                        }`}
                      >
                        {faq.isActive ? "نشط" : "غير نشط"}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center justify-end gap-1">
                        <button
                          onClick={() => openEditModal(faq)}
                           className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors dark:text-[#60a5fa] dark:hover:bg-[#2a3d56]"
                           title="تعديل"
                        >
                           <Pencil className="h-4 w-4 dark:text-[#60a5fa]" />
                        </button>
                        {deleteConfirmId === faq.id ? (
                          <div className="flex items-center gap-1">
                            <button
                              onClick={() => handleDelete(faq.id)}
                               className="px-2.5 py-1 bg-red-600 text-white text-xs rounded-md hover:bg-red-700 transition-colors dark:hover:bg-red-800"
                            >
                               تأكيد
                            </button>
                            <button
                              onClick={() => setDeleteConfirmId(null)}
                               className="px-2.5 py-1 bg-gray-200 text-gray-600 text-xs rounded-md hover:bg-gray-300 transition-colors dark:bg-[#2a3d56] dark:text-[#cbd5e1] dark:hover:bg-[#3b4f6b]"
                            >
                                 إلغاء
                            </button>
                          </div>
                        ) : (
                          <button
                            onClick={() => setDeleteConfirmId(faq.id)}
                             className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition-colors dark:text-[#f87171] dark:hover:bg-[#2a3d56]"
                             title="حذف"
                          >
                             <Trash2 className="h-4 w-4 dark:text-[#f87171]" />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div
            className="absolute inset-0 bg-black/50 backdrop-blur-sm dark:bg-black/70"
            onClick={closeModal}
          />
          <div className="relative bg-white rounded-2xl shadow-2xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto dark:bg-[#1a2332]">
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100 dark:border-[#2a3d56]">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-[#f1f5f9]">
                {editingFaq ? "تعديل سؤال" : "إضافة سؤال جديد"}
              </h2>
              <button
                onClick={closeModal}
                className="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors dark:text-[#94a3b8] dark:hover:text-[#f1f5f9] dark:hover:bg-[#2a3d56]"
              >
                <X className="h-5 w-5 dark:text-[#94a3b8]" />
              </button>
            </div>

            <form onSubmit={handleSubmit} className="px-6 py-5 space-y-5">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1 dark:text-[#94a3b8]">
                   السؤال بالعربية *
                 </label>
                <input
                  type="text"
                  required
                  dir="rtl"
                  value={form.questionAr}
                  onChange={(e) => handleFieldChange("questionAr", e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all dark:bg-[#111927] dark:border-[#3b4f6b] dark:text-[#f1f5f9]"
                  placeholder="السؤال بالعربية"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1 dark:text-[#94a3b8]">
                   السؤال بالإنجليزية *
                 </label>
                <input
                  type="text"
                  required
                  value={form.questionEn}
                  onChange={(e) => handleFieldChange("questionEn", e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all dark:bg-[#111927] dark:border-[#3b4f6b] dark:text-[#f1f5f9]"
                  placeholder="السؤال بالإنجليزية"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1 dark:text-[#94a3b8]">
                   الجواب بالعربية *
                 </label>
                <textarea
                  rows={4}
                  required
                  dir="rtl"
                  value={form.answerAr}
                  onChange={(e) => handleFieldChange("answerAr", e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all resize-none dark:bg-[#111927] dark:border-[#3b4f6b] dark:text-[#f1f5f9]"
                  placeholder="الإجابة بالعربية"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1 dark:text-[#94a3b8]">
                   الجواب بالإنجليزية *
                 </label>
                <textarea
                  rows={4}
                  required
                  value={form.answerEn}
                  onChange={(e) => handleFieldChange("answerEn", e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all resize-none dark:bg-[#111927] dark:border-[#3b4f6b] dark:text-[#f1f5f9]"
                  placeholder="الجواب بالإنجليزية"
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 dark:text-[#94a3b8]">
                     التصنيف *
                   </label>
                  <input
                    type="text"
                    required
                    value={form.category}
                    onChange={(e) => handleFieldChange("category", e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all dark:bg-[#111927] dark:border-[#3b4f6b] dark:text-[#f1f5f9]"
                    placeholder="مثال: عام"
                    list="category-suggestions"
                  />
                  {categories.length > 0 && (
                    <datalist id="category-suggestions">
                      {categories.map((cat) => (
                        <option key={cat} value={cat} />
                      ))}
                    </datalist>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 dark:text-[#94a3b8]">
                     الترتيب
                   </label>
                  <input
                    type="number"
                    min="0"
                    value={form.order}
                    onChange={(e) => handleFieldChange("order", e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all dark:bg-[#111927] dark:border-[#3b4f6b] dark:text-[#f1f5f9]"
                    placeholder="0"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 dark:text-[#94a3b8]">
                     الحالة
                   </label>
                  <select
                    value={form.isActive}
                    onChange={(e) => handleFieldChange("isActive", e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all bg-white dark:bg-[#111927] dark:border-[#3b4f6b] dark:text-[#f1f5f9]"
                  >
                    <option value="true">نشط</option>
                    <option value="false">غير نشط</option>
                  </select>
                </div>
              </div>

              <div className="flex items-center justify-end gap-3 pt-3 border-t border-gray-100 dark:border-[#2a3d56]">
                <button
                  type="button"
                  onClick={closeModal}
                   className="px-4 py-2 text-sm font-medium text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors dark:text-[#cbd5e1] dark:bg-[#2a3d56] dark:hover:bg-[#3b4f6b]"
                >
                   إلغاء
                 </button>
                 <button
                   type="submit"
                   disabled={submitting}
                   className="px-5 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed dark:hover:bg-blue-800"
                 >
                   {submitting
                     ? "جاري الحفظ..."
                     : editingFaq
                       ? "تحديث السؤال"
                       : "إنشاء سؤال"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}
