"use client";
import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Cpu, Plus, Play, Pause, Trash2, Eye, ShieldAlert, AlertCircle,
  CheckCircle, Loader2, Sparkles, Sliders, ChevronDown, RefreshCw, Info, Database
} from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { usePlatform, PLATFORMS, type PlatformType } from "@/lib/context/PlatformContext";
import { formatCurrency } from "@/lib/utils";

interface AutopilotRule {
  id: string;
  name: string;
  platform: string;
  campaign_id?: string | null;
  campaign_name?: string;
  trigger_type: "cpa_exceeded" | "roas_dropped" | "spend_limit" | "ctr_low";
  condition_operator: ">" | "<" | "=";
  condition_value: number;
  action_type: "pause" | "notify" | "adjust_budget";
  action_value?: string | null;
  status: "active" | "paused";
  last_triggered_at?: string;
  created_at: string;
}

interface CampaignOption {
  id: string;
  name: string;
  platform: string;
}

const triggerTypesMap = {
  cpa_exceeded: { label: "تكلفة التحويل مرتفعة (CPA)", symbol: "🎯", desc: "عندما تزيد تكلفة التحويل عن القيمة" },
  roas_dropped: { label: "العائد الإعلاني منخفض (ROAS)", symbol: "📈", desc: "عندما يقل معدل عائد الإنفاق عن القيمة" },
  spend_limit: { label: "الحد الأقصى للإنفاق اليومي", symbol: "💸", desc: "عندما يتجاوز الإنفاق الإعلاني القيمة" },
  ctr_low: { label: "نسبة النقر للظهور منخفضة (CTR)", symbol: "👁️", desc: "عندما تقل نسبة النقر للظهور عن القيمة" },
};

const actionTypesMap = {
  pause: { label: "إيقاف الحملة مؤقتاً", color: "text-amber-400 bg-amber-500/10 border-amber-500/20" },
  notify: { label: "إرسال تنبيه فوري للهاتف", color: "text-emerald-400 bg-emerald-500/10 border-emerald-500/20" },
  adjust_budget: { label: "تعديل الميزانية تلقائياً", color: "text-purple-400 bg-purple-500/10 border-purple-500/20" },
};

export default function AutopilotPage() {
  const { currentPlatform, config } = usePlatform();
  const [rules, setRules] = useState<AutopilotRule[]>([]);
  const [campaigns, setCampaigns] = useState<CampaignOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);

  // New Rule Form Fields
  const [ruleName, setRuleName] = useState("");
  const [selectedPlatform, setSelectedPlatform] = useState<PlatformType>("all");
  const [selectedCampaignId, setSelectedCampaignId] = useState("");
  const [triggerType, setTriggerType] = useState<"cpa_exceeded" | "roas_dropped" | "spend_limit" | "ctr_low">("cpa_exceeded");
  const [operator, setOperator] = useState<">" | "<" | "=">(">");
  const [conditionValue, setConditionValue] = useState("");
  const [actionType, setActionType] = useState<"pause" | "notify" | "adjust_budget">("pause");
  const [actionValue, setActionValue] = useState("");

  const [user, setUser] = useState<any>(null);
  const supabase = createClient();

  // Logs simulation
  const [logs, setLogs] = useState<any[]>([
    { id: "l1", ruleName: "إيقاف تلقائي عند تجاوز CPA", campaignName: "حملة البحث - منتجات العناية بالبشرة الرياض", action: "تم إيقاف الحملة مؤقتاً", time: new Date(Date.now() - 3600000).toISOString(), status: "success" },
    { id: "l2", ruleName: "تنبيه الهاتف لميزانية سناب", campaignName: "سحب شاشة Snapchat - تطبيق التوصيل الفوري", action: "تم إرسال تنبيه فوري للهاتف", time: new Date(Date.now() - 7200000).toISOString(), status: "success" },
  ]);

  useEffect(() => {
    const handleFallback = () => {
      const devUser = localStorage.getItem("local_developer_user");
      if (devUser) {
        setUser(JSON.parse(devUser));
      } else {
        const defaultUser = { id: "00000000-0000-0000-0000-000000000000", email: "dev@techprocode.com", user_metadata: { full_name: "المطور" } };
        localStorage.setItem("local_developer_user", JSON.stringify(defaultUser));
        setUser(defaultUser);
      }
    };

    supabase.auth.getUser()
      .then(({ data: { user } }) => {
        if (user) {
          setUser(user);
        } else {
          handleFallback();
        }
      })
      .catch((err) => {
        console.warn("Supabase connection failed on autopilot page, using offline developer mode:", err);
        handleFallback();
      });
  }, []);

  useEffect(() => {
    if (user) {
      fetchRules();
      fetchCampaigns();
    }
  }, [user]);

  async function fetchRules() {
    setLoading(true);
    try {
      const isPlaceholder = !process.env.NEXT_PUBLIC_SUPABASE_URL || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL.includes("placeholder") || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL === "your_supabase_project_url";

      if (isPlaceholder) {
        const local = localStorage.getItem("local_autopilot_rules");
        if (local) {
          setRules(JSON.parse(local));
        } else {
          const defaultRules: AutopilotRule[] = [
            { id: "r1", name: "إيقاف تلقائي عند تجاوز CPA لـ Meta", platform: "meta", trigger_type: "cpa_exceeded", condition_operator: ">", condition_value: 25, action_type: "pause", status: "active", created_at: new Date().toISOString() },
            { id: "r2", name: "تعديل ميزانية بحث Google عند انخفاض CTR", platform: "google", trigger_type: "ctr_low", condition_operator: "<", condition_value: 2.5, action_type: "adjust_budget", action_value: "15", status: "active", created_at: new Date().toISOString() },
          ];
          localStorage.setItem("local_autopilot_rules", JSON.stringify(defaultRules));
          setRules(defaultRules);
        }
        setLoading(false);
        return;
      }

      const { data: dbRules, error } = await supabase
        .from("autopilot_rules")
        .select("*")
        .order("created_at", { ascending: false });

      if (error) throw error;

      if (dbRules && dbRules.length > 0) {
        setRules(dbRules);
      } else {
        setRules([]);
      }
    } catch (err) {
      console.error("Error loading rules:", err);
      // fallback
      const local = localStorage.getItem("local_autopilot_rules");
      if (local) setRules(JSON.parse(local));
    } finally {
      setLoading(false);
    }
  }

  async function fetchCampaigns() {
    try {
      const isPlaceholder = !process.env.NEXT_PUBLIC_SUPABASE_URL || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL.includes("placeholder") || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL === "your_supabase_project_url";

      if (isPlaceholder) {
        const local = localStorage.getItem("local_campaigns");
        if (local) {
          const camps = JSON.parse(local);
          setCampaigns(camps.map((c: any) => ({ id: c.id, name: c.name, platform: c.platform })));
        } else {
          setCampaigns([
            { id: "g1", name: "حملة البحث - منتجات العناية بالبشرة الرياض", platform: "google" },
            { id: "m1", name: "حملة التحويلات - فساتين سهرة الخليج (فيس بوك)", platform: "meta" }
          ]);
        }
        return;
      }

      const { data, error } = await supabase
        .from("campaigns")
        .select("id, name, platform");
      if (error) throw error;
      setCampaigns(data || []);
    } catch (err) {
      console.error("Error loading campaigns options:", err);
    }
  }

  async function handleToggleRuleStatus(ruleId: string, currentStatus: string) {
    const newStatus = currentStatus === "active" ? "paused" : "active";
    // Update locally instantly
    setRules(prev => {
      const updated = prev.map(r => r.id === ruleId ? { ...r, status: newStatus as any } : r);
      localStorage.setItem("local_autopilot_rules", JSON.stringify(updated));
      return updated;
    });

    try {
      const isPlaceholder = !process.env.NEXT_PUBLIC_SUPABASE_URL || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL.includes("placeholder") || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL === "your_supabase_project_url";
      if (!isPlaceholder) {
        await supabase
          .from("autopilot_rules")
          .update({ status: newStatus })
          .eq("id", ruleId);
      }
    } catch (err) {
      console.error("Error toggling rule status in DB, kept local storage change:", err);
    }
  }

  async function handleDeleteRule(ruleId: string) {
    if (!confirm("هل أنت متأكد من حذف هذه القاعدة نهائياً؟")) return;
    setRules(prev => {
      const updated = prev.filter(r => r.id !== ruleId);
      localStorage.setItem("local_autopilot_rules", JSON.stringify(updated));
      return updated;
    });

    try {
      const isPlaceholder = !process.env.NEXT_PUBLIC_SUPABASE_URL || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL.includes("placeholder") || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL === "your_supabase_project_url";
      if (!isPlaceholder) {
        await supabase.from("autopilot_rules").delete().eq("id", ruleId);
      }
    } catch (err) {
      console.error("Error deleting rule in DB, kept local storage change:", err);
    }
  }

  async function handleCreateRule(e: React.FormEvent) {
    e.preventDefault();
    if (!ruleName.trim() || !conditionValue) return;

    setSubmitting(true);
    const newRule: AutopilotRule = {
      id: Math.random().toString(),
      name: ruleName.trim(),
      platform: selectedPlatform,
      campaign_id: selectedCampaignId || null,
      trigger_type: triggerType,
      condition_operator: operator,
      condition_value: Number(conditionValue),
      action_type: actionType,
      action_value: actionValue.trim() || null,
      status: "active",
      created_at: new Date().toISOString(),
    };

    const isPlaceholder = !process.env.NEXT_PUBLIC_SUPABASE_URL || 
                          process.env.NEXT_PUBLIC_SUPABASE_URL.includes("placeholder") || 
                          process.env.NEXT_PUBLIC_SUPABASE_URL === "your_supabase_project_url";

    if (isPlaceholder) {
      setRules(prev => {
        const updated = [newRule, ...prev];
        localStorage.setItem("local_autopilot_rules", JSON.stringify(updated));
        return updated;
      });
      setIsModalOpen(false);
      setRuleName("");
      setSelectedCampaignId("");
      setConditionValue("");
      setActionValue("");
      setSubmitting(false);
      return;
    }

    try {
      const payload = {
        user_id: user.id,
        name: ruleName.trim(),
        platform: selectedPlatform,
        campaign_id: selectedCampaignId || null,
        trigger_type: triggerType,
        condition_operator: operator,
        condition_value: Number(conditionValue),
        action_type: actionType,
        action_value: actionValue.trim() || null,
        status: "active",
      };

      const { data, error } = await supabase
        .from("autopilot_rules")
        .insert(payload)
        .select()
        .single();

      if (error) throw error;

      if (data) {
        setRules(prev => [data, ...prev]);
        setIsModalOpen(false);
        setRuleName("");
        setSelectedCampaignId("");
        setConditionValue("");
        setActionValue("");
      }
    } catch (err) {
      console.error("Error creating autopilot rule:", err);
      alert("فشل إضافة القاعدة، يرجى التأكد من تشغيل ملف الهجرة في SQL Editor أولاً!");
    } finally {
      setSubmitting(false);
    }
  }

  async function handleSeedRules() {
    if (!user) return;
    setLoading(true);
    const mockRules: AutopilotRule[] = [
      {
        id: "r1",
        name: "إيقاف الإعلان تلقائياً عند تجاوز تكلفة التحويل",
        platform: "google",
        trigger_type: "cpa_exceeded",
        condition_operator: ">",
        condition_value: 25,
        action_type: "pause",
        status: "active",
        created_at: new Date().toISOString(),
      },
      {
        id: "r2",
        name: "زيادة وتعديل الميزانية عند تحقيق ROAS ممتاز",
        platform: "meta",
        trigger_type: "roas_dropped",
        condition_operator: ">",
        condition_value: 4,
        action_type: "adjust_budget",
        action_value: "15",
        status: "active",
        created_at: new Date().toISOString(),
      },
      {
        id: "r3",
        name: "تنبيه فوري عند تجاوز سقف الإنفاق اليومي لسناب",
        platform: "snapchat",
        trigger_type: "spend_limit",
        condition_operator: ">",
        condition_value: 100,
        action_type: "notify",
        status: "active",
        created_at: new Date().toISOString(),
      }
    ];

    const isPlaceholder = !process.env.NEXT_PUBLIC_SUPABASE_URL || 
                          process.env.NEXT_PUBLIC_SUPABASE_URL.includes("placeholder") || 
                          process.env.NEXT_PUBLIC_SUPABASE_URL === "your_supabase_project_url";

    if (isPlaceholder) {
      localStorage.setItem("local_autopilot_rules", JSON.stringify(mockRules));
      setRules(mockRules);
      setLoading(false);
      return;
    }

    try {
      const { error } = await supabase.from("autopilot_rules").insert(mockRules.map(({ id, ...rest }) => rest));
      if (error) throw error;
      fetchRules();
    } catch (err) {
      console.error("Error seeding rules:", err);
    } finally {
      setLoading(false);
    }
  }

  const filteredRules = rules.filter(r => currentPlatform === "all" || r.platform === currentPlatform);

  return (
    <div className="p-6 space-y-6 text-right" dir="rtl">
      
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-2">
            <Cpu className="w-6 h-6 text-indigo-400 animate-pulse" />
            <span>الأتمتة والقواعد الآلية (Autopilot)</span>
          </h1>
          <p className="text-[#8a8380] text-sm mt-0.5">
            تحكم ذكي في تشغيل حملاتك الإعلانية وميزانيتها 24/7 دون أي تدخل يدوي مستمر.
          </p>
        </div>

        <button
          onClick={() => setIsModalOpen(true)}
          className="flex items-center justify-center gap-2 bg-gradient-to-l from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 text-white font-semibold px-5 py-3 rounded-xl text-sm transition-all shadow-lg shadow-indigo-500/20"
        >
          <Plus className="w-4 h-4" />
          <span>إنشاء قاعدة تشغيل آلية</span>
        </button>
      </div>

      {/* Grid of stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-[#101010] border border-gray-800 p-4 rounded-xl space-y-1">
          <p className="text-xs text-gray-500">القواعد المفعلة</p>
          <p className="text-2xl font-black text-white">{rules.filter(r => r.status === "active").length} <span className="text-xs text-emerald-400 font-medium">نشط الآن</span></p>
        </div>
        <div className="bg-[#101010] border border-gray-800 p-4 rounded-xl space-y-1">
          <p className="text-xs text-gray-500">العمليات الآلية المنجزة</p>
          <p className="text-2xl font-black text-white">{logs.length} <span className="text-xs text-indigo-400 font-medium">عملية حماية</span></p>
        </div>
        <div className="bg-[#101010] border border-gray-800 p-4 rounded-xl space-y-1">
          <p className="text-xs text-gray-500">معدل الاستجابة والتحقق</p>
          <p className="text-2xl font-black text-white">100% <span className="text-xs text-indigo-400 font-medium">لحظي (Real-time)</span></p>
        </div>
      </div>

      {/* Main Content */}
      {loading ? (
        <div className="flex flex-col items-center justify-center py-20 bg-[#101010] border border-gray-800 rounded-xl">
          <Loader2 className="w-8 h-8 text-indigo-400 animate-spin mb-3" />
          <p className="text-[#8a8380] text-sm">جارٍ قراءة القواعد النشطة من قاعدة البيانات...</p>
        </div>
      ) : rules.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 bg-[#101010] border border-gray-800 rounded-xl text-center px-4">
          <Sliders className="w-12 h-12 text-gray-600 mb-4" />
          <h3 className="text-white font-semibold text-base">لا توجد أي قواعد أوتوماتيكية مضافة</h3>
          <p className="text-[#8a8380] text-xs max-w-sm mt-1 mb-5">
            قم بتهيئة القواعد الذكية الجاهزة لتجربتها فوراً في قاعدة بياناتك الحية على Supabase بضغطة زر واحدة!
          </p>
          <div className="flex gap-3">
            <button
              onClick={handleSeedRules}
              className="flex items-center gap-2 bg-[#161b27] border border-gray-800 hover:border-gray-700 text-white font-bold px-4 py-2.5 rounded-xl text-xs transition-all"
            >
              <Database className="w-4 h-4 text-indigo-400" />
              <span>زرع قواعد تشغيل تلقائية جاهزة</span>
            </button>
            <button
              onClick={() => setIsModalOpen(true)}
              className="flex items-center gap-2 bg-indigo-600 hover:bg-indigo-500 text-white font-bold px-4 py-2.5 rounded-xl text-xs transition-all"
            >
              <Plus className="w-4 h-4" />
              <span>إضافة قاعدة يدوياً</span>
            </button>
          </div>
        </div>
      ) : (
        <div className="space-y-6">
          <div className="bg-[#101010] border border-gray-800 rounded-xl overflow-hidden">
            <div className="p-4 border-b border-gray-800/80 bg-[#161b27]/30 flex items-center justify-between">
              <span className="text-xs font-bold text-gray-400">قائمة القواعد الآلية</span>
              <span className="text-[10px] text-gray-500">إجمالي {filteredRules.length} قواعد</span>
            </div>
            
            <div className="divide-y divide-gray-850">
              {filteredRules.map((rule) => {
                const triggerInfo = triggerTypesMap[rule.trigger_type];
                const actionInfo = actionTypesMap[rule.action_type];
                const platformConfig = PLATFORMS[rule.platform as PlatformType];
                const ruleCampaign = campaigns.find(c => c.id === rule.campaign_id);

                return (
                  <div key={rule.id} className="p-4 flex flex-col md:flex-row md:items-center justify-between gap-4 hover:bg-[#161b27]/10 transition-colors">
                    <div className="space-y-1.5">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="text-lg bg-[#161b27] border border-gray-850 w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0" title={platformConfig?.name || "كل المنصات"}>
                          {platformConfig?.logo || "🌐"}
                        </span>
                        <h4 className="text-sm font-semibold text-white">{rule.name}</h4>
                        <span className="text-[9px] font-bold bg-purple-500/10 text-purple-400 border border-purple-500/20 px-1.5 py-0.5 rounded-md flex items-center gap-0.5">
                          <Sparkles className="w-2.5 h-2.5" />
                          أوتوبايلوت
                        </span>
                      </div>
                      
                      <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-gray-400">
                        <div className="flex items-center gap-1">
                          <span className="text-gray-500">الشرط:</span>
                          <span className="text-white font-medium">{triggerInfo?.symbol} {triggerInfo?.label}</span>
                          <span className="text-indigo-400 font-bold">{rule.condition_operator} {rule.condition_value}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <span className="text-gray-500">المستهدف:</span>
                          <span className="text-gray-300 font-medium">{ruleCampaign ? ruleCampaign.name : "جميع حملات المنصة"}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <span className="text-gray-500">الإجراء:</span>
                          <span className={`px-2 py-0.5 rounded text-[10px] font-bold border ${actionInfo?.color}`}>
                            {actionInfo?.label} {rule.action_value ? `(${rule.action_value}%)` : ""}
                          </span>
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center gap-3 self-end md:self-center">
                      <div className="flex flex-col text-left">
                        <span className="text-[10px] text-gray-500">حالة القاعدة</span>
                        <span className={`text-[10px] font-bold ${rule.status === "active" ? "text-emerald-400" : "text-yellow-400"}`}>
                          {rule.status === "active" ? "فعالة وتراقب" : "متوقفة مؤقتاً"}
                        </span>
                      </div>
                      
                      <button
                        onClick={() => handleToggleRuleStatus(rule.id, rule.status)}
                        className={`p-2 rounded-lg border transition-all ${
                          rule.status === "active"
                            ? "border-yellow-500/20 bg-yellow-500/10 text-yellow-400 hover:bg-yellow-500/20"
                            : "border-emerald-500/20 bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20"
                        }`}
                        title={rule.status === "active" ? "إيقاف مؤقت للقاعدة" : "تشغيل القاعدة"}
                      >
                        {rule.status === "active" ? <Pause className="w-3.5 h-3.5" /> : <Play className="w-3.5 h-3.5" />}
                      </button>

                      <button
                        onClick={() => handleDeleteRule(rule.id)}
                        className="p-2 rounded-lg border border-red-500/20 bg-red-500/10 text-red-400 hover:bg-red-500/20 hover:text-red-300 transition-all"
                        title="حذف القاعدة"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Autopilot Logs */}
          <div className="bg-[#101010] border border-gray-800 rounded-xl overflow-hidden">
            <div className="p-4 border-b border-gray-800 bg-[#161b27]/30 flex items-center justify-between">
              <span className="text-xs font-bold text-gray-400 flex items-center gap-1.5">
                <RefreshCw className="w-3.5 h-3.5 text-indigo-400 animate-spin" />
                <span>سجل الأوتوبايلوت للقرارات الآلية</span>
              </span>
              <span className="text-[10px] text-emerald-400 flex items-center gap-1">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-ping" />
                تحليل حقيقي
              </span>
            </div>
            
            <div className="divide-y divide-gray-850 text-xs">
              {logs.map((log) => (
                <div key={log.id} className="p-3.5 flex items-center justify-between gap-4 hover:bg-[#161b27]/5">
                  <div className="space-y-1">
                    <div className="flex items-center gap-2">
                      <span className="text-white font-semibold">{log.ruleName}</span>
                      <span className="text-[10px] text-gray-500">على: {log.campaignName}</span>
                    </div>
                    <p className="text-emerald-400 flex items-center gap-1 text-[10px]">
                      <CheckCircle className="w-3.5 h-3.5" />
                      <span>{log.action}</span>
                    </p>
                  </div>
                  <span className="text-[10px] text-gray-500">{new Date(log.time).toLocaleTimeString("ar-SA")}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Modal for creating a new rule */}
      <AnimatePresence>
        {isModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="bg-[#101010] border border-gray-800 w-full max-w-xl rounded-2xl overflow-hidden shadow-2xl flex flex-col"
            >
              <div className="p-5 border-b border-gray-800 bg-[#161b27]/30 flex items-center justify-between">
                <h3 className="text-white font-bold text-base flex items-center gap-2">
                  <Cpu className="w-5 h-5 text-indigo-400" />
                  <span>توليد قاعدة أوتوماتيكية جديدة</span>
                </h3>
                <button
                  onClick={() => setIsModalOpen(false)}
                  className="text-gray-400 hover:text-white transition-colors"
                >
                  ✕
                </button>
              </div>

              <form onSubmit={handleCreateRule} className="p-6 space-y-4 overflow-y-auto max-h-[75vh]">
                
                {/* Rule Name */}
                <div className="space-y-1.5">
                  <label className="text-xs text-gray-400 font-semibold">اسم القاعدة</label>
                  <input
                    type="text"
                    required
                    placeholder="مثال: إيقاف الحملة إذا تجاوزت التكلفة الحد الأقصى"
                    value={ruleName}
                    onChange={(e) => setRuleName(e.target.value)}
                    className="w-full bg-[#161b27] border border-gray-700/80 focus:border-indigo-500 text-white rounded-xl py-2.5 px-4 text-sm outline-none transition-colors"
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  {/* Platform */}
                  <div className="space-y-1.5">
                    <label className="text-xs text-gray-400 font-semibold">المنصة</label>
                    <select
                      value={selectedPlatform}
                      onChange={(e) => setSelectedPlatform(e.target.value as any)}
                      className="w-full bg-[#161b27] border border-gray-700/80 focus:border-indigo-500 text-white rounded-xl py-2.5 px-3 text-sm outline-none cursor-pointer"
                    >
                      <option value="all">جميع المنصات</option>
                      <option value="google">Google Ads</option>
                      <option value="meta">Meta Ads</option>
                      <option value="tiktok">TikTok Ads</option>
                      <option value="snapchat">Snapchat Ads</option>
                      <option value="linkedin">LinkedIn Ads</option>
                      <option value="x">X Ads</option>
                    </select>
                  </div>

                  {/* Campaign */}
                  <div className="space-y-1.5">
                    <label className="text-xs text-gray-400 font-semibold">الحملة الإعلانية المستهدفة</label>
                    <select
                      value={selectedCampaignId}
                      onChange={(e) => setSelectedCampaignId(e.target.value)}
                      className="w-full bg-[#161b27] border border-gray-700/80 focus:border-indigo-500 text-white rounded-xl py-2.5 px-3 text-sm outline-none cursor-pointer"
                    >
                      <option value="">كل حملات المنصة</option>
                      {campaigns
                        .filter(c => selectedPlatform === "all" || c.platform === selectedPlatform)
                        .map(c => (
                          <option key={c.id} value={c.id}>{c.name}</option>
                        ))
                      }
                    </select>
                  </div>
                </div>

                {/* Trigger Condition */}
                <div className="space-y-1.5 p-4 bg-[#161b27]/30 border border-gray-800 rounded-xl space-y-3">
                  <span className="text-xs font-bold text-indigo-400 flex items-center gap-1">
                    <Info className="w-3.5 h-3.5" />
                    شروط وجدول التحقق الذكي
                  </span>

                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 items-end">
                    <div className="space-y-1.5">
                      <label className="text-[10px] text-gray-400 font-semibold">إذا كانت قيمة</label>
                      <select
                        value={triggerType}
                        onChange={(e) => setTriggerType(e.target.value as any)}
                        className="w-full bg-[#101010] border border-gray-700/80 text-white rounded-lg py-2 px-2 text-xs outline-none cursor-pointer"
                      >
                        <option value="cpa_exceeded">CPA تكلفة التحويل</option>
                        <option value="roas_dropped">ROAS عائد الإنفاق</option>
                        <option value="spend_limit">الإنفاق اليومي</option>
                        <option value="ctr_low">CTR نسبة النقر للظهور</option>
                      </select>
                    </div>

                    <div className="space-y-1.5">
                      <label className="text-[10px] text-gray-400 font-semibold">المعامل المنطقي</label>
                      <select
                        value={operator}
                        onChange={(e) => setOperator(e.target.value as any)}
                        className="w-full bg-[#101010] border border-gray-700/80 text-white rounded-lg py-2 px-2 text-xs outline-none cursor-pointer"
                      >
                        <option value=">">أكبر من (&gt;)</option>
                        <option value="<">أصغر من (&lt;)</option>
                        <option value="=">يساوي (=)</option>
                      </select>
                    </div>

                    <div className="space-y-1.5">
                      <label className="text-[10px] text-gray-400 font-semibold">القيمة المحددة ($)</label>
                      <input
                        type="number"
                        required
                        placeholder="مثال: 50"
                        value={conditionValue}
                        onChange={(e) => setConditionValue(e.target.value)}
                        className="w-full bg-[#101010] border border-gray-700/80 text-white rounded-lg py-2 px-3 text-xs outline-none"
                      />
                    </div>
                  </div>
                </div>

                {/* Actions */}
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-xs text-gray-400 font-semibold">الإجراء المتخذ تلقائياً</label>
                    <select
                      value={actionType}
                      onChange={(e) => setActionType(e.target.value as any)}
                      className="w-full bg-[#161b27] border border-gray-700/80 focus:border-indigo-500 text-white rounded-xl py-2.5 px-3 text-sm outline-none cursor-pointer"
                    >
                      <option value="pause">إيقاف الحملة مؤقتاً</option>
                      <option value="notify">إرسال تنبيه فوري للهاتف</option>
                      <option value="adjust_budget">تعديل الميزانية تلقائياً</option>
                    </select>
                  </div>

                  {actionType === "adjust_budget" && (
                    <div className="space-y-1.5">
                      <label className="text-xs text-gray-400 font-semibold">قيمة النسبة للتعديل (%)</label>
                      <input
                        type="number"
                        required
                        placeholder="مثال: 15 (زيادة/نقصان)"
                        value={actionValue}
                        onChange={(e) => setActionValue(e.target.value)}
                        className="w-full bg-[#161b27] border border-gray-700/80 focus:border-indigo-500 text-white rounded-xl py-2.5 px-4 text-sm outline-none"
                      />
                    </div>
                  )}
                </div>

                {/* Footer Buttons */}
                <div className="pt-4 border-t border-gray-800/80 flex items-center justify-end gap-3">
                  <button
                    type="button"
                    onClick={() => setIsModalOpen(false)}
                    className="bg-[#161b27] hover:bg-gray-850 border border-gray-800 text-white font-semibold px-4 py-2.5 rounded-xl text-xs transition-colors"
                  >
                    إلغاء
                  </button>
                  <button
                    type="submit"
                    disabled={submitting}
                    className="bg-indigo-600 hover:bg-indigo-500 text-white font-semibold px-5 py-2.5 rounded-xl text-xs transition-colors flex items-center gap-1.5"
                  >
                    {submitting ? (
                      <>
                        <Loader2 className="w-3.5 h-3.5 animate-spin" />
                        <span>جاري الحفظ والربط...</span>
                      </>
                    ) : (
                      <>
                        <CheckCircle className="w-3.5 h-3.5" />
                        <span>حفظ وتفعيل القاعدة فوراً</span>
                      </>
                    )}
                  </button>
                </div>
              </form>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
}
