"use client";

import { useEffect, useMemo, useState } from "react";
import {
  Activity,
  AlertTriangle,
  Bot,
  CheckCircle2,
  CircleDollarSign,
  Clock,
  ExternalLink,
  Loader2,
  Pause,
  Play,
  Plus,
  RefreshCw,
  ShieldCheck,
  Target,
  Zap,
} from "lucide-react";
import { cn, formatCurrency } from "@/lib/utils";

interface AdAgent {
  id: string;
  name: string;
  business_url: string;
  goal: string;
  daily_budget_limit: number;
  monthly_budget_limit: number | null;
  target_locations: string[];
  allowed_platforms: string[];
  risk_level: string;
  automation_level: string;
  status: "active" | "paused" | "needs_setup" | "error";
  last_run_at: string | null;
  setup_notes: string | null;
  created_at: string;
}

interface AgentDecision {
  id: string;
  agent_id: string;
  campaign_id: string | null;
  decision_type: string;
  reason: string;
  execution_status: "pending" | "executed" | "skipped" | "failed";
  action_payload: Record<string, unknown>;
  execution_result: Record<string, unknown>;
  created_at: string;
}

interface AgentRun {
  id: string;
  agent_id: string;
  status: "running" | "completed" | "failed";
  summary: string | null;
  started_at: string;
  finished_at: string | null;
}

const goalOptions = [
  { id: "conversions", label: "تحويلات" },
  { id: "sales", label: "مبيعات" },
  { id: "leads", label: "عملاء محتملون" },
  { id: "traffic", label: "زيارات" },
  { id: "whatsapp", label: "واتساب" },
];

const automationOptions = [
  { id: "limited", label: "محدود", description: "ينشئ ويخفض المخاطر تلقائيا، ويرفع بحذر." },
  { id: "full", label: "كامل", description: "يطلق حملات Google مباشرة إذا كان الربط مكتمل." },
  { id: "approval_required", label: "بموافقة", description: "يحضر القرارات ولا ينفذ العالي المخاطر." },
];

const statusStyles: Record<AdAgent["status"], string> = {
  active: "border-emerald-500/25 bg-emerald-500/10 text-emerald-300",
  paused: "border-amber-500/25 bg-amber-500/10 text-amber-300",
  needs_setup: "border-blue-500/25 bg-blue-500/10 text-blue-300",
  error: "border-red-500/25 bg-red-500/10 text-red-300",
};

const statusLabel: Record<AdAgent["status"], string> = {
  active: "نشط",
  paused: "متوقف",
  needs_setup: "ينتظر الإعداد",
  error: "خطأ",
};

const decisionLabel: Record<string, string> = {
  create_campaign: "إنشاء حملة",
  pause_campaign: "إيقاف حملة",
  increase_budget: "رفع الميزانية",
  decrease_budget: "خفض الميزانية",
  add_negative_keyword: "إضافة كلمة سلبية",
  generate_new_ads: "توليد إعلانات",
  pause_keyword: "إيقاف كلمة",
  duplicate_winner: "نسخ حملة رابحة",
  needs_setup: "يتطلب إعداد",
  no_action: "لا إجراء",
};

export default function AgentPage() {
  const [agents, setAgents] = useState<AdAgent[]>([]);
  const [decisions, setDecisions] = useState<AgentDecision[]>([]);
  const [runs, setRuns] = useState<AgentRun[]>([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [runningId, setRunningId] = useState<string | null>(null);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  const [form, setForm] = useState({
    name: "وكيل إعلانات تلقائي",
    businessUrl: "",
    goal: "conversions",
    dailyBudgetLimit: 50,
    targetLocations: "Saudi Arabia",
    automationLevel: "limited",
    riskLevel: "balanced",
  });

  const activeAgent = agents[0] || null;
  const agentDecisions = useMemo(
    () => decisions.filter((decision) => !activeAgent || decision.agent_id === activeAgent.id),
    [activeAgent, decisions]
  );

  async function loadAgents() {
    setLoading(true);
    try {
      const response = await fetch("/api/agents", { cache: "no-store" });
      const data = await response.json();
      if (!response.ok) throw new Error(data.error || "تعذر تحميل الوكلاء.");
      setAgents(data.agents || []);
      setDecisions(data.decisions || []);
      setRuns(data.runs || []);
    } catch (error) {
      setMessage({ type: "error", text: error instanceof Error ? error.message : "تعذر تحميل البيانات." });
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void Promise.resolve().then(loadAgents);
  }, []);

  async function createAgent(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setCreating(true);
    setMessage(null);

    try {
      const response = await fetch("/api/agents", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          targetLocations: form.targetLocations.split(",").map((item) => item.trim()).filter(Boolean),
          allowedPlatforms: ["google"],
        }),
      });

      const data = await response.json();
      if (!response.ok) throw new Error(data.error || "فشل إنشاء الوكيل.");

      setMessage({ type: "success", text: "تم إنشاء الوكيل. شغله الآن ليبدأ إنشاء ومتابعة الحملات." });
      setForm((prev) => ({ ...prev, businessUrl: "" }));
      await loadAgents();
    } catch (error) {
      setMessage({ type: "error", text: error instanceof Error ? error.message : "فشل إنشاء الوكيل." });
    } finally {
      setCreating(false);
    }
  }

  async function runAgent(agentId: string) {
    setRunningId(agentId);
    setMessage(null);

    try {
      const response = await fetch(`/api/agents/${agentId}/run`, { method: "POST" });
      const data = await response.json();
      if (!response.ok) throw new Error(data.error || "فشل تشغيل الوكيل.");

      setMessage({ type: "success", text: data.summary || "اكتملت دورة الوكيل." });
      await loadAgents();
    } catch (error) {
      setMessage({ type: "error", text: error instanceof Error ? error.message : "فشل تشغيل الوكيل." });
    } finally {
      setRunningId(null);
    }
  }

  async function toggleAgent(agent: AdAgent) {
    const nextStatus = agent.status === "paused" ? "active" : "paused";
    setMessage(null);

    try {
      const response = await fetch(`/api/agents/${agent.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: nextStatus }),
      });
      const data = await response.json();
      if (!response.ok) throw new Error(data.error || "فشل تحديث حالة الوكيل.");
      await loadAgents();
    } catch (error) {
      setMessage({ type: "error", text: error instanceof Error ? error.message : "فشل تحديث حالة الوكيل." });
    }
  }

  return (
    <div className="min-h-screen bg-[#0a0e19] p-6 text-right text-white" dir="rtl">
      <div className="mb-6 flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="mb-2 flex items-center gap-2">
            <div className="flex h-9 w-9 items-center justify-center rounded-lg border border-emerald-500/25 bg-emerald-500/10">
              <Bot className="h-5 w-5 text-emerald-300" />
            </div>
            <h1 className="text-2xl font-bold">المحرك الذاتي للإعلانات</h1>
          </div>
          <p className="max-w-2xl text-sm leading-6 text-gray-400">
            اربط حساباتك الإعلانية، ثم أعط النظام رابط الموقع والميزانية. الوكيل ينشئ حملات Google Search تلقائيا، يتابع الأداء، ويخفض أو يرفع أو يوقف حسب الحواجز التي تحددها.
          </p>
        </div>

        <button
          onClick={loadAgents}
          className="flex items-center justify-center gap-2 rounded-lg border border-gray-800 bg-[#101418] px-4 py-2.5 text-xs font-semibold text-gray-300 transition hover:border-gray-700 hover:text-white"
        >
          <RefreshCw className="h-4 w-4" />
          تحديث
        </button>
      </div>

      {message && (
        <div
          className={cn(
            "mb-5 flex items-center gap-2 rounded-lg border px-4 py-3 text-sm",
            message.type === "success"
              ? "border-emerald-500/25 bg-emerald-500/10 text-emerald-200"
              : "border-red-500/25 bg-red-500/10 text-red-200"
          )}
        >
          {message.type === "success" ? <CheckCircle2 className="h-4 w-4" /> : <AlertTriangle className="h-4 w-4" />}
          <span>{message.text}</span>
        </div>
      )}

      <div className="grid gap-5 xl:grid-cols-[360px_1fr]">
        <form onSubmit={createAgent} className="space-y-4 rounded-lg border border-gray-800 bg-[#101418] p-5">
          <div className="flex items-center gap-2 border-b border-gray-800 pb-4">
            <Plus className="h-4 w-4 text-emerald-300" />
            <h2 className="text-sm font-bold">إعداد وكيل جديد</h2>
          </div>

          <label className="block space-y-1.5">
            <span className="text-xs font-semibold text-gray-400">اسم الوكيل</span>
            <input
              value={form.name}
              onChange={(event) => setForm((prev) => ({ ...prev, name: event.target.value }))}
              className="w-full rounded-lg border border-gray-800 bg-[#0a0e19] px-3 py-2.5 text-sm outline-none transition focus:border-emerald-500"
            />
          </label>

          <label className="block space-y-1.5">
            <span className="text-xs font-semibold text-gray-400">رابط الموقع أو المتجر</span>
            <input
              required
              value={form.businessUrl}
              onChange={(event) => setForm((prev) => ({ ...prev, businessUrl: event.target.value }))}
              placeholder="https://example.com"
              className="w-full rounded-lg border border-gray-800 bg-[#0a0e19] px-3 py-2.5 text-left text-sm outline-none transition focus:border-emerald-500"
              dir="ltr"
            />
          </label>

          <div className="grid grid-cols-2 gap-3">
            <label className="block space-y-1.5">
              <span className="text-xs font-semibold text-gray-400">الهدف</span>
              <select
                value={form.goal}
                onChange={(event) => setForm((prev) => ({ ...prev, goal: event.target.value }))}
                className="w-full rounded-lg border border-gray-800 bg-[#0a0e19] px-3 py-2.5 text-sm outline-none transition focus:border-emerald-500"
              >
                {goalOptions.map((option) => (
                  <option key={option.id} value={option.id}>{option.label}</option>
                ))}
              </select>
            </label>

            <label className="block space-y-1.5">
              <span className="text-xs font-semibold text-gray-400">ميزانية يومية</span>
              <input
                type="number"
                min={5}
                value={form.dailyBudgetLimit}
                onChange={(event) => setForm((prev) => ({ ...prev, dailyBudgetLimit: Number(event.target.value) }))}
                className="w-full rounded-lg border border-gray-800 bg-[#0a0e19] px-3 py-2.5 text-sm outline-none transition focus:border-emerald-500"
              />
            </label>
          </div>

          <label className="block space-y-1.5">
            <span className="text-xs font-semibold text-gray-400">المناطق المستهدفة</span>
            <input
              value={form.targetLocations}
              onChange={(event) => setForm((prev) => ({ ...prev, targetLocations: event.target.value }))}
              className="w-full rounded-lg border border-gray-800 bg-[#0a0e19] px-3 py-2.5 text-sm outline-none transition focus:border-emerald-500"
            />
          </label>

          <div className="space-y-2">
            <span className="text-xs font-semibold text-gray-400">مستوى التشغيل</span>
            <div className="grid gap-2">
              {automationOptions.map((option) => (
                <button
                  key={option.id}
                  type="button"
                  onClick={() => setForm((prev) => ({ ...prev, automationLevel: option.id }))}
                  className={cn(
                    "rounded-lg border p-3 text-right transition",
                    form.automationLevel === option.id
                      ? "border-emerald-500/40 bg-emerald-500/10"
                      : "border-gray-800 bg-[#0a0e19] hover:border-gray-700"
                  )}
                >
                  <span className="block text-xs font-bold text-white">{option.label}</span>
                  <span className="mt-1 block text-[11px] leading-5 text-gray-500">{option.description}</span>
                </button>
              ))}
            </div>
          </div>

          <button
            type="submit"
            disabled={creating}
            className="flex w-full items-center justify-center gap-2 rounded-lg bg-emerald-600 px-4 py-3 text-sm font-bold text-white transition hover:bg-emerald-500 disabled:opacity-60"
          >
            {creating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Zap className="h-4 w-4" />}
            إنشاء الوكيل
          </button>
        </form>

        <div className="space-y-5">
          <div className="grid gap-4 md:grid-cols-4">
            <Metric title="الوكلاء" value={agents.length} icon={<Bot className="h-4 w-4 text-emerald-300" />} />
            <Metric title="القرارات" value={decisions.length} icon={<Activity className="h-4 w-4 text-blue-300" />} />
            <Metric title="دورات التشغيل" value={runs.length} icon={<Clock className="h-4 w-4 text-amber-300" />} />
            <Metric title="آخر حالة" value={activeAgent ? statusLabel[activeAgent.status] : "لا يوجد"} icon={<ShieldCheck className="h-4 w-4 text-purple-300" />} />
          </div>

          {loading ? (
            <div className="flex h-64 items-center justify-center rounded-lg border border-gray-800 bg-[#101418]">
              <Loader2 className="h-7 w-7 animate-spin text-emerald-300" />
            </div>
          ) : agents.length === 0 ? (
            <div className="rounded-lg border border-gray-800 bg-[#101418] p-8 text-center">
              <Bot className="mx-auto mb-3 h-10 w-10 text-gray-600" />
              <h3 className="mb-1 text-base font-bold">لم يتم إنشاء وكيل بعد</h3>
              <p className="text-sm text-gray-500">ابدأ برابط الموقع والميزانية، ثم شغل الوكيل لإنشاء أول حملة تلقائية.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {agents.map((agent) => (
                <div key={agent.id} className="rounded-lg border border-gray-800 bg-[#101418] p-5">
                  <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
                    <div className="min-w-0 space-y-3">
                      <div className="flex flex-wrap items-center gap-2">
                        <h2 className="text-lg font-bold">{agent.name}</h2>
                        <span className={cn("rounded-md border px-2 py-1 text-[11px] font-bold", statusStyles[agent.status])}>
                          {statusLabel[agent.status]}
                        </span>
                        <span className="rounded-md border border-gray-800 bg-[#0a0e19] px-2 py-1 text-[11px] text-gray-400">
                          {agent.automation_level === "full" ? "تشغيل كامل" : agent.automation_level === "limited" ? "تشغيل محدود" : "بموافقة"}
                        </span>
                      </div>

                      <a href={agent.business_url} target="_blank" className="inline-flex items-center gap-1 text-xs text-blue-300 hover:text-blue-200">
                        <ExternalLink className="h-3.5 w-3.5" />
                        {agent.business_url}
                      </a>

                      <div className="grid gap-3 text-xs text-gray-400 sm:grid-cols-3">
                        <span className="flex items-center gap-1.5">
                          <Target className="h-3.5 w-3.5 text-emerald-300" />
                          {goalOptions.find((option) => option.id === agent.goal)?.label || agent.goal}
                        </span>
                        <span className="flex items-center gap-1.5">
                          <CircleDollarSign className="h-3.5 w-3.5 text-amber-300" />
                          {formatCurrency(Number(agent.daily_budget_limit || 0))} يوميا
                        </span>
                        <span className="flex items-center gap-1.5">
                          <Clock className="h-3.5 w-3.5 text-blue-300" />
                          {agent.last_run_at ? new Date(agent.last_run_at).toLocaleString("ar-SA") : "لم يعمل بعد"}
                        </span>
                      </div>

                      {agent.setup_notes && (
                        <div className="rounded-lg border border-blue-500/20 bg-blue-500/10 px-3 py-2 text-xs leading-5 text-blue-200">
                          {agent.setup_notes}
                        </div>
                      )}
                    </div>

                    <div className="flex shrink-0 items-center gap-2">
                      <button
                        onClick={() => toggleAgent(agent)}
                        className="flex items-center gap-2 rounded-lg border border-gray-800 bg-[#0a0e19] px-3 py-2 text-xs font-semibold text-gray-300 transition hover:border-gray-700 hover:text-white"
                      >
                        {agent.status === "paused" ? <Play className="h-4 w-4" /> : <Pause className="h-4 w-4" />}
                        {agent.status === "paused" ? "تشغيل" : "إيقاف"}
                      </button>
                      <button
                        onClick={() => runAgent(agent.id)}
                        disabled={runningId === agent.id || agent.status === "paused"}
                        className="flex items-center gap-2 rounded-lg bg-emerald-600 px-3 py-2 text-xs font-bold text-white transition hover:bg-emerald-500 disabled:opacity-60"
                      >
                        {runningId === agent.id ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
                        تشغيل دورة
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          <div className="rounded-lg border border-gray-800 bg-[#101418]">
            <div className="flex items-center justify-between border-b border-gray-800 px-5 py-4">
              <h2 className="text-sm font-bold">آخر قرارات الوكيل</h2>
              <span className="text-[11px] text-gray-500">{agentDecisions.length} قرار</span>
            </div>
            <div className="divide-y divide-gray-800">
              {agentDecisions.length === 0 ? (
                <div className="p-6 text-sm text-gray-500">لا توجد قرارات بعد. شغل دورة للوكيل لبدء الإنشاء أو المتابعة.</div>
              ) : (
                agentDecisions.slice(0, 12).map((decision) => (
                  <div key={decision.id} className="flex flex-col gap-2 p-4 md:flex-row md:items-start md:justify-between">
                    <div>
                      <div className="mb-1 flex flex-wrap items-center gap-2">
                        <span className="text-sm font-bold">{decisionLabel[decision.decision_type] || decision.decision_type}</span>
                        <span
                          className={cn(
                            "rounded-md border px-2 py-0.5 text-[10px] font-bold",
                            decision.execution_status === "executed"
                              ? "border-emerald-500/25 bg-emerald-500/10 text-emerald-300"
                              : decision.execution_status === "failed"
                                ? "border-red-500/25 bg-red-500/10 text-red-300"
                                : "border-gray-700 bg-[#0a0e19] text-gray-400"
                          )}
                        >
                          {decision.execution_status}
                        </span>
                      </div>
                      <p className="max-w-3xl text-xs leading-5 text-gray-400">{decision.reason}</p>
                      {Boolean(decision.execution_result?.error) && (
                        <p className="mt-1 text-xs leading-5 text-red-300">{String(decision.execution_result.error)}</p>
                      )}
                    </div>
                    <time className="shrink-0 text-[11px] text-gray-600">
                      {new Date(decision.created_at).toLocaleString("ar-SA")}
                    </time>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Metric({ title, value, icon }: { title: string; value: React.ReactNode; icon: React.ReactNode }) {
  return (
    <div className="rounded-lg border border-gray-800 bg-[#101418] p-4">
      <div className="mb-2 flex items-center justify-between">
        <span className="text-xs text-gray-500">{title}</span>
        {icon}
      </div>
      <div className="truncate text-xl font-black text-white">{value}</div>
    </div>
  );
}
