/**
 * FAQ Editor Modal
 * Create or edit FAQ entries
 */

"use client";

import { Fragment, useState, useEffect } from "react";
import { Dialog, Transition } from "@headlessui/react";
import type { Lang } from "@/lib/config";
import { X, Save, AlertCircle, Loader2 } from "lucide-react";
import { DOCUMENT_CATEGORIES } from "@/lib/types/knowledge-base.types";
import type { KnowledgeBaseFAQ } from "@/lib/types/knowledge-base.types";

interface FAQEditorModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  lang: Lang;
  csrfToken: string;
  faq?: KnowledgeBaseFAQ | null;
}

export default function FAQEditorModal({
  isOpen,
  onClose,
  onSuccess,
  lang,
  csrfToken,
  faq,
}: FAQEditorModalProps) {
  const isAr = lang === "ar";
  const isEditing = !!faq;

  const [questionEn, setQuestionEn] = useState("");
  const [questionAr, setQuestionAr] = useState("");
  const [answerEn, setAnswerEn] = useState("");
  const [answerAr, setAnswerAr] = useState("");
  const [category, setCategory] = useState("general");
  const [priority, setPriority] = useState(0);
  const [isActive, setIsActive] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Populate form when editing
  useEffect(() => {
    if (faq) {
      setQuestionEn(faq.questionEn);
      setQuestionAr(faq.questionAr || "");
      setAnswerEn(faq.answerEn);
      setAnswerAr(faq.answerAr || "");
      setCategory(faq.category);
      setPriority(faq.priority);
      setIsActive(faq.isActive);
    } else {
      // Reset form for new FAQ
      setQuestionEn("");
      setQuestionAr("");
      setAnswerEn("");
      setAnswerAr("");
      setCategory("general");
      setPriority(0);
      setIsActive(true);
    }
    setError(null);
  }, [faq, isOpen]);

  // Handle save
  const handleSave = async () => {
    // Validation
    if (!questionEn.trim()) {
      setError(
        isAr ? "السؤال بالإنجليزية مطلوب" : "Question (English) is required",
      );
      return;
    }

    if (!answerEn.trim()) {
      setError(
        isAr ? "الإجابة بالإنجليزية مطلوبة" : "Answer (English) is required",
      );
      return;
    }

    setSaving(true);
    setError(null);

    try {
      const url = isEditing
        ? `/api/dashboard/knowledge-base/faqs/${faq.id}`
        : "/api/dashboard/knowledge-base/faqs";

      const response = await fetch(url, {
        method: isEditing ? "PATCH" : "POST",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          questionEn: questionEn.trim(),
          questionAr: questionAr.trim() || null,
          answerEn: answerEn.trim(),
          answerAr: answerAr.trim() || null,
          category,
          priority,
          isActive,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to save FAQ");
      }

      onSuccess();
    } catch (err: any) {
      setError(err.message || (isAr ? "فشل حفظ السؤال" : "Failed to save FAQ"));
    } finally {
      setSaving(false);
    }
  };

  const handleClose = () => {
    if (!saving) {
      onClose();
    }
  };

  return (
    <Transition appear show={isOpen} as={Fragment}>
      <Dialog
        as="div"
        className="relative z-50"
        onClose={handleClose}
        dir={isAr ? "rtl" : "ltr"}
      >
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black/50 backdrop-blur-sm" />
        </Transition.Child>

        <div className="fixed inset-0 overflow-y-auto">
          <div className="flex min-h-full items-center justify-center p-4">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <Dialog.Panel className="w-full max-w-2xl transform overflow-hidden rounded-2xl bg-white shadow-2xl transition-all">
                {/* Header */}
                <div className="flex items-center justify-between border-b border-slate-100 px-6 py-4">
                  <Dialog.Title className="text-lg font-semibold text-slate-900">
                    {isEditing
                      ? isAr
                        ? "تعديل السؤال الشائع"
                        : "Edit FAQ"
                      : isAr
                        ? "إضافة سؤال شائع"
                        : "Add FAQ"}
                  </Dialog.Title>
                  <button
                    onClick={handleClose}
                    disabled={saving}
                    className="rounded-lg p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors disabled:opacity-50"
                  >
                    <X className="h-5 w-5" />
                  </button>
                </div>

                {/* Content */}
                <div className="px-6 py-4 space-y-4 max-h-[60vh] overflow-y-auto">
                  {/* Question English */}
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                      {isAr ? "السؤال (إنجليزي) *" : "Question (English) *"}
                    </label>
                    <input
                      type="text"
                      value={questionEn}
                      onChange={(e) => setQuestionEn(e.target.value)}
                      placeholder={
                        isAr
                          ? "مثال: ما هي ساعات العمل؟"
                          : "e.g., What are your working hours?"
                      }
                      className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm placeholder-slate-400 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none"
                      disabled={saving}
                      dir="ltr"
                    />
                  </div>

                  {/* Question Arabic */}
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                      {isAr ? "السؤال (عربي)" : "Question (Arabic)"}
                    </label>
                    <input
                      type="text"
                      value={questionAr}
                      onChange={(e) => setQuestionAr(e.target.value)}
                      placeholder={
                        isAr
                          ? "مثال: ما هي ساعات العمل؟"
                          : "e.g., ما هي ساعات العمل؟"
                      }
                      className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm placeholder-slate-400 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none"
                      disabled={saving}
                      dir="rtl"
                    />
                  </div>

                  {/* Answer English */}
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                      {isAr ? "الإجابة (إنجليزي) *" : "Answer (English) *"}
                    </label>
                    <textarea
                      value={answerEn}
                      onChange={(e) => setAnswerEn(e.target.value)}
                      placeholder={
                        isAr
                          ? "اكتب الإجابة هنا..."
                          : "Write your answer here..."
                      }
                      rows={3}
                      className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm placeholder-slate-400 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none resize-none"
                      disabled={saving}
                      dir="ltr"
                    />
                  </div>

                  {/* Answer Arabic */}
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                      {isAr ? "الإجابة (عربي)" : "Answer (Arabic)"}
                    </label>
                    <textarea
                      value={answerAr}
                      onChange={(e) => setAnswerAr(e.target.value)}
                      placeholder={
                        isAr ? "اكتب الإجابة هنا..." : "اكتب الإجابة هنا..."
                      }
                      rows={3}
                      className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm placeholder-slate-400 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none resize-none"
                      disabled={saving}
                      dir="rtl"
                    />
                  </div>

                  {/* Category and Priority */}
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-slate-700 mb-1">
                        {isAr ? "الفئة" : "Category"}
                      </label>
                      <select
                        value={category}
                        onChange={(e) => setCategory(e.target.value)}
                        className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none"
                        disabled={saving}
                      >
                        {DOCUMENT_CATEGORIES.map((cat) => (
                          <option key={cat.value} value={cat.value}>
                            {isAr ? cat.labelAr : cat.labelEn}
                          </option>
                        ))}
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-slate-700 mb-1">
                        {isAr ? "الأولوية" : "Priority"}
                      </label>
                      <select
                        value={priority}
                        onChange={(e) => setPriority(Number(e.target.value))}
                        className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none"
                        disabled={saving}
                      >
                        <option value={0}>{isAr ? "عادي" : "Normal"}</option>
                        <option value={1}>{isAr ? "مرتفع" : "High"}</option>
                        <option value={2}>
                          {isAr ? "مهم جدا" : "Very Important"}
                        </option>
                      </select>
                    </div>
                  </div>

                  {/* Active toggle (only show when editing) */}
                  {isEditing && (
                    <div className="flex items-center gap-3">
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={isActive}
                          onChange={(e) => setIsActive(e.target.checked)}
                          className="sr-only peer"
                          disabled={saving}
                        />
                        <div className="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-brand-green/20 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand-green"></div>
                      </label>
                      <span className="text-sm text-slate-700">
                        {isAr ? "نشط" : "Active"}
                      </span>
                    </div>
                  )}

                  {/* Error */}
                  {error && (
                    <div className="flex items-center gap-2 rounded-lg bg-red-50 px-4 py-3 text-sm text-red-600">
                      <AlertCircle className="h-4 w-4 flex-shrink-0" />
                      <span>{error}</span>
                    </div>
                  )}
                </div>

                {/* Footer */}
                <div className="flex items-center justify-end gap-3 border-t border-slate-100 px-6 py-4">
                  <button
                    onClick={handleClose}
                    disabled={saving}
                    className="rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors disabled:opacity-50"
                  >
                    {isAr ? "إلغاء" : "Cancel"}
                  </button>
                  <button
                    onClick={handleSave}
                    disabled={saving || !questionEn.trim() || !answerEn.trim()}
                    className="inline-flex items-center gap-2 rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {saving ? (
                      <>
                        <Loader2 className="h-4 w-4 animate-spin" />
                        {isAr ? "جاري الحفظ..." : "Saving..."}
                      </>
                    ) : (
                      <>
                        <Save className="h-4 w-4" />
                        {isAr ? "حفظ" : "Save"}
                      </>
                    )}
                  </button>
                </div>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition>
  );
}
