"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { HelpCircle, Search, ChevronDown, ChevronUp, Mail, MessageSquare, Phone, Check, Loader2 } from "lucide-react";

interface FAQ {
  q: string;
  a: string;
  category: string;
}

const faqs: FAQ[] = [
  {
    category: "general",
    q: "ما هي منصة برو كود ادز وكيف تساعدني؟",
    a: "منصة برو كود ادز هي أداة متكاملة مدعومة بالذكاء الاصطناعي لتخطيط وإطلاق وإدارة حملات جوجل الإعلانية، مع توفير نظام حماية تلقائي ضد النقرات الوهمية لتفادي إهدار ميزانية إعلاناتك."
  },
  {
    category: "campaigns",
    q: "كيف يمكنني إطلاق حملة جديدة بالذكاء الاصطناعي؟",
    a: "توجه إلى تبويب 'مولّد AI' في القائمة الجانبية، املأ معلومات عملك، حدد الجمهور والميزانية ونموذج الـ AI المفضل، وسيقوم الذكاء الاصطناعي بإنشاء الكلمات المفتاحية ونصوص الإعلانات الاستراتيجية بضغطة زر واحدة."
  },
  {
    category: "protection",
    q: "كيف يعمل نظام حماية النقرات الوهمية؟",
    a: "يقوم النظام بفحص وتحليل كافة النقرات الواردة من إعلانات جوجل بشكل فوري. في حال تم رصد سلوك احتيالي (كالبوتات أو النقرات المتكررة من منافسيك)، يقوم النظام تلقائياً بإضافة عنوان الـ IP إلى قائمة الحظر في حملاتك لمنع ظهور إعلاناتك لهم مرة أخرى."
  },
  {
    category: "integrations",
    q: "هل يتوجب علي امتلاك حساب Google Ads Developer؟",
    a: "لا، المنصة مجهزة للربط المباشر مع حسابك الإعلاني القياسي عبر الـ OAuth الآمن دون الحاجة لأي متطلبات تقنية معقدة."
  },
  {
    category: "billing",
    q: "ما هي خطة الحسابات الموثقة (Managed Accounts)؟",
    a: "هي خدمة نقدمها لإدارة إعلاناتك بالكامل عبر حساباتنا الموثقة لدى جوجل لتفادي الحظر أو التعليق مقابل عمولة 20% فقط من الميزانية الإعلانية، وهي مثالية للشركات التي تركز على النتائج الفورية."
  }
];

export default function HelpPage() {
  const [searchTerm, setSearchTerm] = useState("");
  const [activeCategory, setActiveCategory] = useState("all");
  const [expandedIndex, setExpandedIndex] = useState<number | null>(null);

  // Form states
  const [subject, setSubject] = useState("");
  const [message, setMessage] = useState("");
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);

  function toggleExpand(idx: number) {
    setExpandedIndex(expandedIndex === idx ? null : idx);
  }

  function handleSendTicket(e: React.FormEvent) {
    e.preventDefault();
    if (!message.trim()) return;

    setSending(true);
    setTimeout(() => {
      setSending(false);
      setSent(true);
      setSubject("");
      setMessage("");
      setTimeout(() => setSent(false), 3000);
    }, 800);
  }

  const filteredFaqs = faqs.filter((faq) => {
    const matchesSearch = faq.q.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          faq.a.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = activeCategory === "all" || faq.category === activeCategory;
    return matchesSearch && matchesCategory;
  });

  return (
    <div className="p-6 max-w-4xl mx-auto space-y-6">
      {/* Header */}
      <div className="text-center space-y-2 max-w-lg mx-auto py-4">
        <h1 className="text-2xl font-bold text-white flex items-center justify-center gap-2">
          <HelpCircle className="w-6 h-6 text-emerald-400" />
          مركز المساعدة والدعم
        </h1>
        <p className="text-[#8a8380] text-sm">
          ابحث عن إجابات لاستفساراتك الشائعة أو تواصل مع فريق الدعم الفني
        </p>

        {/* Search */}
        <div className="relative pt-2">
          <Search className="absolute right-3 top-5 w-4 h-4 text-gray-500" />
          <input
            type="text"
            placeholder="ابحث عن حل للمشكلة..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full bg-[#101010] border border-gray-800 focus:border-emerald-500 text-white rounded-xl py-2.5 pr-10 pl-4 text-xs outline-none transition-colors"
          />
        </div>
      </div>

      {/* Category Tabs */}
      <div className="flex gap-2 justify-center overflow-x-auto pb-1">
        {[
          { id: "all", label: "الكل" },
          { id: "general", label: "عام" },
          { id: "campaigns", label: "الحملات والـ AI" },
          { id: "protection", label: "حماية النقرات" },
          { id: "integrations", label: "التكاملات والربط" },
          { id: "billing", label: "الاشتراكات والمدفوعات" },
        ].map((cat) => (
          <button
            key={cat.id}
            onClick={() => {
              setActiveCategory(cat.id);
              setExpandedIndex(null);
            }}
            className={`px-3 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap transition-all ${
              activeCategory === cat.id
                ? "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20"
                : "text-gray-500 hover:text-white"
            }`}
          >
            {cat.label}
          </button>
        ))}
      </div>

      {/* FAQs List */}
      <div className="bg-[#101010] border border-gray-800 rounded-xl p-5 space-y-3">
        <h3 className="text-white font-semibold text-sm mb-4">الأسئلة الشائعة</h3>
        
        {filteredFaqs.length === 0 ? (
          <p className="text-xs text-gray-500 text-center py-6">لم يتم العثور على أي نتائج مطابقة للبحث.</p>
        ) : (
          <div className="space-y-2">
            {filteredFaqs.map((faq, idx) => {
              const isExpanded = expandedIndex === idx;
              return (
                <div key={idx} className="border border-gray-850 rounded-xl overflow-hidden">
                  <button
                    onClick={() => toggleExpand(idx)}
                    className="w-full flex items-center justify-between p-3.5 bg-[#161b27]/30 text-right text-xs font-semibold text-white hover:bg-[#161b27]/50 transition-colors"
                  >
                    <span>{faq.q}</span>
                    {isExpanded ? <ChevronUp className="w-4 h-4 text-gray-500" /> : <ChevronDown className="w-4 h-4 text-gray-500" />}
                  </button>

                  <AnimatePresence>
                    {isExpanded && (
                      <motion.div
                        initial={{ height: 0 }}
                        animate={{ height: "auto" }}
                        exit={{ height: 0 }}
                        className="overflow-hidden bg-[#161b27]/10"
                      >
                        <p className="p-4 text-xs text-[#b8b3b0] leading-relaxed border-t border-gray-850">
                          {faq.a}
                        </p>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Contact Support Ticket Form */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 bg-[#101010] border border-gray-800 rounded-xl p-5 items-start">
        
        {/* Support channels info */}
        <div className="space-y-4 md:col-span-1">
          <h3 className="text-white font-semibold text-sm">قنوات التواصل المباشر</h3>
          <p className="text-xs text-[#8a8380] leading-relaxed">
            إذا لم تجد إجابة لسؤالك، يمكنك فتح تذكرة دعم وسيقوم خبراؤنا بالرد عليك خلال أقل من ساعتين.
          </p>

          <div className="space-y-2.5 text-xs text-[#b8b3b0]">
            <div className="flex items-center gap-2 p-2 bg-[#161b27]/50 rounded-lg">
              <Mail className="w-4 h-4 text-emerald-400" />
              <span>support@procode.ads</span>
            </div>
            <div className="flex items-center gap-2 p-2 bg-[#161b27]/50 rounded-lg">
              <MessageSquare className="w-4 h-4 text-purple-400" />
              <span>المحادثة الحية في المنصة</span>
            </div>
          </div>
        </div>

        {/* Support ticket submission form */}
        <div className="space-y-3 md:col-span-2">
          <h3 className="text-white font-semibold text-sm">فتح تذكرة دعم فني</h3>
          
          <form onSubmit={handleSendTicket} className="space-y-3">
            <div className="space-y-1.5">
              <label className="block text-xs text-[#b8b3b0]">عنوان التذكرة / المشكلة</label>
              <input
                type="text"
                required
                value={subject}
                onChange={(e) => setSubject(e.target.value)}
                placeholder="مثال: استفسار حول حظر IP معين"
                className="w-full bg-[#161b27] border border-gray-700 focus:border-emerald-500 text-white rounded-xl py-2 px-3 text-xs outline-none transition-colors"
              />
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs text-[#b8b3b0]">تفاصيل الرسالة أو الاستفسار</label>
              <textarea
                required
                rows={3}
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                placeholder="يرجى وصف المشكلة بالتفصيل لمساعدتك بشكل أسرع..."
                className="w-full bg-[#161b27] border border-gray-700 focus:border-emerald-500 text-white rounded-xl py-2 px-3 text-xs outline-none transition-colors resize-none"
              />
            </div>

            <div className="flex items-center justify-end gap-2">
              {sent && (
                <span className="text-xs text-emerald-400 flex items-center gap-1">
                  <Check className="w-3.5 h-3.5" />
                  تم إرسال تذكرتك بنجاح!
                </span>
              )}
              <button
                type="submit"
                disabled={sending}
                className="flex items-center gap-1.5 bg-emerald-500 hover:bg-emerald-400 disabled:opacity-40 text-white font-semibold px-5 py-2 rounded-xl text-xs transition-colors cursor-pointer"
              >
                {sending ? (
                  <>
                    <Loader2 className="w-3.5 h-3.5 animate-spin" />
                    جاري الإرسال...
                  </>
                ) : (
                  <>
                    <Mail className="w-3.5 h-3.5" />
                    إرسال التذكرة للخبراء
                  </>
                )}
              </button>
            </div>
          </form>
        </div>

      </div>
    </div>
  );
}
