"use client";

import { useState, useEffect } from "react";
import {
  Settings, User, Bot, Bell, Shield, Key, Check, Loader2, Save
} from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { AI_MODELS, type AIProvider } from "@/lib/ai/models";

export default function SettingsPage() {
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);

  // Form states
  const [fullName, setFullName] = useState("");
  const [companyName, setCompanyName] = useState("");
  const [phone, setPhone] = useState("");
  const [googleAdsCustomerId, setGoogleAdsCustomerId] = useState("");
  const [preferredProvider, setPreferredProvider] = useState<AIProvider>("gemini");
  const [preferredModel, setPreferredModel] = useState("gemini-1.5-flash");
  const [ollamaUrl, setOllamaUrl] = useState("http://localhost:11434");
  const [notifyClick, setNotifyClick] = useState(true);
  const [notifyBudget, setNotifyBudget] = useState(true);
  const [notifyReports, setNotifyReports] = useState(true);

  // Premium notification fields
  const [telegramChatId, setTelegramChatId] = useState("");
  const [whatsappPhone, setWhatsappPhone] = useState("");
  const [notifyTelegram, setNotifyTelegram] = useState(false);
  const [notifyWhatsapp, setNotifyWhatsapp] = useState(false);

  const supabase = createClient();
  const availableModels = AI_MODELS.filter((m) => m.provider === preferredProvider);

  async function loadSettings() {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;

      setFullName(user.user_metadata?.full_name || "");

      const { data: profile } = await supabase
        .from("profiles")
        .select("*")
        .eq("id", user.id)
        .single();

      if (profile) {
        setFullName(profile.full_name || "");
        setCompanyName(profile.company_name || "");
        setPhone(profile.phone || "");
      }

      const { data: settings } = await supabase
        .from("user_settings")
        .select("*")
        .eq("id", user.id)
        .single();

      if (settings) {
        setPreferredProvider(settings.preferred_ai_provider as AIProvider);
        setPreferredModel(settings.preferred_ai_model);
        setOllamaUrl(settings.ollama_base_url || "http://localhost:11434");
        setNotifyClick(settings.notify_click_protection);
        setNotifyBudget(settings.notify_budget_alerts);
        setNotifyReports(settings.notify_performance_reports);

        // Premium alert loads
        setTelegramChatId(settings.telegram_chat_id || "");
        setWhatsappPhone(settings.whatsapp_phone || "");
        setNotifyTelegram(settings.notify_via_telegram || false);
        setNotifyWhatsapp(settings.notify_via_whatsapp || false);
      }

      // Load Google Ads Customer ID
      const { data: account } = await supabase
        .from("ad_accounts")
        .select("google_ads_customer_id")
        .eq("user_id", user.id)
        .eq("status", "active")
        .limit(1)
        .maybeSingle();

      if (account) {
        setGoogleAdsCustomerId(account.google_ads_customer_id || "");
      }
    } catch (err) {
      console.error("Error loading user settings, using defaults:", err);
    }
  }

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

  async function handleSaveSettings(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setSuccess(false);

    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) throw new Error("No user found");

      // Update profile
      await supabase
        .from("profiles")
        .update({
          full_name: fullName,
          company_name: companyName,
          phone: phone,
        })
        .eq("id", user.id);

      // Update user metadata in Auth
      await supabase.auth.updateUser({
        data: { full_name: fullName }
      });

      // Update settings
      await supabase
        .from("user_settings")
        .update({
          preferred_ai_provider: preferredProvider,
          preferred_ai_model: preferredModel,
          ollama_base_url: ollamaUrl,
          notify_click_protection: notifyClick,
          notify_budget_alerts: notifyBudget,
          notify_performance_reports: notifyReports,
          // Premium alerts update
          telegram_chat_id: telegramChatId,
          whatsapp_phone: whatsappPhone,
          notify_via_telegram: notifyTelegram,
          notify_via_whatsapp: notifyWhatsapp,
        })
        .eq("id", user.id);

      // Save/Upsert Google Ads Customer ID
      const { data: account } = await supabase
        .from("ad_accounts")
        .select("id")
        .eq("user_id", user.id)
        .limit(1)
        .maybeSingle();

      if (account) {
        await supabase
          .from("ad_accounts")
          .update({ google_ads_customer_id: googleAdsCustomerId })
          .eq("id", account.id);
      } else {
        await supabase
          .from("ad_accounts")
          .insert({
            user_id: user.id,
            google_ads_customer_id: googleAdsCustomerId,
            name: "حساب Google Ads الرئيسي",
            status: "active"
          });
      }

      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    } catch (err) {
      console.error("Error saving settings:", err);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="p-6 max-w-3xl mx-auto space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-white flex items-center gap-2">
          <Settings className="w-6 h-6 text-gray-400" />
          الإعدادات العامة
        </h1>
        <p className="text-[#8a8380] text-sm mt-0.5">
          إدارة حسابك الشخصي، تفضيلات نماذج الذكاء الاصطناعي، وتنبيهات الأمان
        </p>
      </div>

      <form onSubmit={handleSaveSettings} className="space-y-5">
        
        {/* Profile Card */}
        <div className="bg-[#101010] border border-gray-800 rounded-xl p-5 space-y-4">
          <h3 className="text-white font-semibold text-sm flex items-center gap-2">
            <User className="w-4.5 h-4.5 text-emerald-400" />
            المعلومات الشخصية للعميل
          </h3>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-1.5">
              <label className="block text-xs text-[#b8b3b0]">الاسم بالكامل</label>
              <input
                type="text"
                value={fullName}
                onChange={(e) => setFullName(e.target.value)}
                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>
              <input
                type="text"
                value={companyName}
                onChange={(e) => setCompanyName(e.target.value)}
                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 md:col-span-2">
              <label className="block text-xs text-[#b8b3b0]">رقم الجوال</label>
              <input
                type="text"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                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 animate-none"
              />
            </div>
          </div>
        </div>

        {/* Google Ads Connection Card */}
        <div className="bg-[#101010] border border-gray-800 rounded-xl p-5 space-y-4">
          <h3 className="text-white font-semibold text-sm flex items-center gap-2">
            <Key className="w-4.5 h-4.5 text-blue-400" />
            إعدادات ربط Google Ads
          </h3>

          <div className="space-y-1.5">
            <label className="block text-xs text-[#b8b3b0]">معرّف العميل لـ Google Ads (Customer ID)</label>
            <input
              type="text"
              placeholder="مثال: 123-456-7890"
              value={googleAdsCustomerId}
              onChange={(e) => setGoogleAdsCustomerId(e.target.value)}
              className="w-full bg-[#161b27] border border-gray-700 focus:border-blue-500 text-white rounded-xl py-2 px-3 text-xs outline-none transition-colors"
            />
            <p className="text-[10px] text-gray-500">
              مطلوب لتمكين الإطلاق التلقائي للحملات الإعلانية ومتابعة أداء المنافسين. يمكنك العثور عليه في الزاوية العلوية لحساب Google Ads الخاص بك.
            </p>
          </div>
        </div>

        {/* AI Preferences */}
        <div className="bg-[#101010] border border-gray-800 rounded-xl p-5 space-y-4">
          <h3 className="text-white font-semibold text-sm flex items-center gap-2">
            <Bot className="w-4.5 h-4.5 text-purple-400" />
            إعدادات نماذج الـ AI المفضلة
          </h3>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-1.5">
              <label className="block text-xs text-[#b8b3b0]">مزود الـ AI الافتراضي</label>
              <select
                value={preferredProvider}
                onChange={(e) => {
                  const p = e.target.value as AIProvider;
                  setPreferredProvider(p);
                  const firstModel = AI_MODELS.find((m) => m.provider === p);
                  if (firstModel) setPreferredModel(firstModel.id);
                }}
                className="w-full bg-[#161b27] border border-gray-700 text-white rounded-xl py-2.5 px-3 text-xs outline-none cursor-pointer"
              >
                <option value="gemini">Google Gemini</option>
                <option value="openai">OpenAI</option>
                <option value="claude">Anthropic Claude</option>
                <option value="deepseek">DeepSeek</option>
                <option value="qwen">Alibaba Qwen</option>
                <option value="ollama">Ollama (سيرفر خاص)</option>
              </select>
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs text-[#b8b3b0]">النموذج الافتراضي</label>
              <select
                value={preferredModel}
                onChange={(e) => setPreferredModel(e.target.value)}
                className="w-full bg-[#161b27] border border-gray-700 text-white rounded-xl py-2.5 px-3 text-xs outline-none cursor-pointer"
              >
                {availableModels.map((m) => (
                  <option key={m.id} value={m.id}>
                    {m.name}
                  </option>
                ))}
              </select>
            </div>

            {preferredProvider === "ollama" && (
              <div className="space-y-1.5 md:col-span-2">
                <label className="block text-xs text-[#b8b3b0]">رابط سيرفر Ollama الخاص بك</label>
                <input
                  type="text"
                  value={ollamaUrl}
                  onChange={(e) => setOllamaUrl(e.target.value)}
                  className="w-full bg-[#161b27] border border-gray-700 focus:border-purple-500 text-white rounded-xl py-2 px-3 text-xs outline-none transition-colors"
                />
                <p className="text-[10px] text-gray-500">
                  مثال: http://your-server-ip:11434. تأكد من إعداد الـ CORS ليرتبط بشكل صحيح.
                </p>
              </div>
            )}
          </div>
        </div>

        {/* Notifications and Alerts */}
        <div className="bg-[#101010] border border-gray-800 rounded-xl p-5 space-y-4">
          <h3 className="text-white font-semibold text-sm flex items-center gap-2">
            <Bell className="w-4.5 h-4.5 text-blue-400" />
            التنبيهات والبريد الإلكتروني
          </h3>

          <div className="space-y-3">
            {[
              { label: "تنبيهات حماية النقرات الوهمية اليومية", desc: "تلقي تقرير يومي بعدد عناوين الـ IP المحظورة وتوفير الميزانية.", state: notifyClick, setState: setNotifyClick },
              { label: "تنبيهات تخطي حدود الميزانية المقررة", desc: "تلقي تحذيرات عند اقتراب حملاتك من استهلاك كامل ميزانيتها.", state: notifyBudget, setState: setNotifyBudget },
              { label: "التقارير التحليلية الأسبوعية والشهرية", desc: "تقارير أداء شاملة مع توصيات ذكاء اصطناعي مرسلة لبريدك الإلكتروني.", state: notifyReports, setState: setNotifyReports },
            ].map((item, idx) => (
              <div key={idx} className="flex items-start justify-between p-2.5 rounded-lg hover:bg-[#161b27]/30 transition-colors">
                <div className="space-y-0.5">
                  <p className="text-xs font-semibold text-white">{item.label}</p>
                  <p className="text-[10px] text-gray-500">{item.desc}</p>
                </div>
                <button
                  type="button"
                  onClick={() => item.setState(!item.state)}
                  className={`w-10 h-5.5 flex items-center rounded-full p-1 cursor-pointer transition-all ${
                    item.state ? "bg-emerald-500 justify-end" : "bg-gray-800 justify-start"
                  }`}
                >
                  <div className="bg-white w-3.5 h-3.5 rounded-full shadow-sm" />
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Premium Instant Alerts (Telegram & WhatsApp) */}
        <div className="bg-[#101010] border border-gray-800 rounded-xl p-5 space-y-5">
          <div className="flex items-center justify-between border-b border-gray-800 pb-3">
            <h3 className="text-white font-semibold text-sm flex items-center gap-2">
              <Shield className="w-4.5 h-4.5 text-indigo-400" />
              <span>مركز التنبيهات الفورية (Telegram & WhatsApp Alerts)</span>
            </h3>
            <span className="text-[9px] font-bold bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 px-2 py-0.5 rounded-full">
              عضوية ممتازة برو ✨
            </span>
          </div>

          <p className="text-xs text-[#8a8380] leading-relaxed">
            احصل على إشعارات وقاية فورية بالملي ثانية على هاتفك مباشرة عند رصد وحجب أي نقرة احتيالية، أو عند تفعيل قواعد التشغيل الآلية لحملاتك لتبقى على علم دائم بكل ما يخص ميزانيتك.
          </p>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-5 pt-1">
            {/* Telegram Setup Card */}
            <div className="bg-[#161b27]/40 border border-gray-850 p-4 rounded-xl space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-xs font-bold text-white flex items-center gap-1.5">
                  <span className="text-lg">✈️</span> تنبيهات Telegram
                </span>
                <button
                  type="button"
                  onClick={() => setNotifyTelegram(!notifyTelegram)}
                  className={`w-10 h-5.5 flex items-center rounded-full p-1 cursor-pointer transition-all ${
                    notifyTelegram ? "bg-indigo-500 justify-end" : "bg-gray-800 justify-start"
                  }`}
                >
                  <div className="bg-white w-3.5 h-3.5 rounded-full shadow-sm" />
                </button>
              </div>

              <div className="space-y-1.5">
                <label className="block text-[10px] text-gray-500">معرّف المحادثة الخاص بك (Chat ID)</label>
                <input
                  type="text"
                  placeholder="مثال: 987654321"
                  value={telegramChatId}
                  disabled={!notifyTelegram}
                  onChange={(e) => setTelegramChatId(e.target.value)}
                  className="w-full bg-[#101010] border border-gray-800 disabled:opacity-40 text-white rounded-lg py-2 px-3 text-xs outline-none focus:border-indigo-500 transition-colors"
                />
              </div>

              <div className="text-[9px] text-[#8a8380] leading-relaxed space-y-1 bg-[#101010]/30 p-2.5 rounded border border-gray-850">
                <p className="font-bold text-white">طريقة التفعيل السريعة:</p>
                <p>1. ابحث في تليجرام عن البوت المعتمد: <code className="bg-gray-850 text-indigo-400 px-1 py-0.5 rounded">@ProCodeAdsAlertsBot</code></p>
                <p>2. أرسل له رسالة <code className="bg-gray-850 text-indigo-400 px-1 py-0.5 rounded">/start</code> ليقوم بإنشاء الـ Chat ID الخاص بك فوراً.</p>
              </div>
            </div>

            {/* WhatsApp Setup Card */}
            <div className="bg-[#161b27]/40 border border-gray-850 p-4 rounded-xl space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-xs font-bold text-white flex items-center gap-1.5">
                  <span className="text-lg">💬</span> تنبيهات WhatsApp
                </span>
                <button
                  type="button"
                  onClick={() => setNotifyWhatsapp(!notifyWhatsapp)}
                  className={`w-10 h-5.5 flex items-center rounded-full p-1 cursor-pointer transition-all ${
                    notifyWhatsapp ? "bg-emerald-500 justify-end" : "bg-gray-800 justify-start"
                  }`}
                >
                  <div className="bg-white w-3.5 h-3.5 rounded-full shadow-sm" />
                </button>
              </div>

              <div className="space-y-1.5">
                <label className="block text-[10px] text-gray-500">رقم الهاتف المرتبط بالواتساب (مع كود الدولة)</label>
                <input
                  type="text"
                  placeholder="مثال: 966500000000"
                  value={whatsappPhone}
                  disabled={!notifyWhatsapp}
                  onChange={(e) => setWhatsappPhone(e.target.value)}
                  className="w-full bg-[#101010] border border-gray-800 disabled:opacity-40 text-white rounded-lg py-2 px-3 text-xs outline-none focus:border-emerald-500 transition-colors"
                />
              </div>

              <div className="text-[9px] text-[#8a8380] leading-relaxed flex items-center gap-3 bg-[#101010]/30 p-2 rounded border border-gray-850">
                <div className="w-12 h-12 bg-white p-1 rounded flex-shrink-0 flex items-center justify-center" title="امسح الرمز لربط التنبيهات">
                  {/* Stylized Simulated QR code */}
                  <div className="w-full h-full bg-[repeating-concentric-gradient(black,black_2px,white_2px,white_4px)] opacity-85" />
                </div>
                <div>
                  <p className="font-bold text-white">ربط سريع عبر مسح الرمز:</p>
                  <p>قم بمسح رمز الاستجابة السريع (QR Code) بكاميرا الهاتف لربط حساب واتساب وتفعيل التنبيهات اللحظية فوراً.</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Action Button */}
        <div className="flex items-center gap-3 justify-end">
          {success && (
            <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={loading}
            className="flex items-center gap-2 bg-emerald-500 hover:bg-emerald-400 disabled:opacity-40 text-white font-semibold px-6 py-2.5 rounded-xl text-xs transition-colors cursor-pointer"
          >
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
            حفظ التغييرات
          </button>
        </div>

      </form>
    </div>
  );
}
