"use client";

import { useState, useMemo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Plus, Trash2, DollarSign, Users, Zap, CheckCircle2 } from "lucide-react";
import type { Locale } from "@/lib/i18n";

interface Agent {
  id: string;
  type: string;
  name: string;
  department: string;
  cost: number;
  tasks: number;
  efficiency: number;
}

interface Department {
  id: string;
  name: string;
  nameAr: string;
  color: string;
  agents: Array<{
    id: string;
    name: string;
    nameAr: string;
    cost: number;
    tasks: number;
    efficiency: number;
  }>;
}

const departmentsData: Department[] = [
  {
    id: "sales",
    name: "Sales",
    nameAr: "المبيعات",
    color: "from-electric-cyan to-soft-emerald",
    agents: [
      { id: "lead-qual", name: "Lead Qualifier", nameAr: "مؤهل العملاء المحتملين", cost: 299, tasks: 500, efficiency: 98 },
      { id: "sales-rep", name: "Sales Representative", nameAr: "مندوب مبيعات", cost: 499, tasks: 800, efficiency: 95 },
      { id: "account-exec", name: "Account Executive", nameAr: "مدير الحسابات", cost: 799, tasks: 1200, efficiency: 97 }
    ]
  },
  {
    id: "support",
    name: "Support",
    nameAr: "الدعم",
    color: "from-soft-emerald to-teal-500",
    agents: [
      { id: "tier1-support", name: "Tier 1 Support", nameAr: "دعم المستوى الأول", cost: 249, tasks: 600, efficiency: 99 },
      { id: "tier2-support", name: "Tier 2 Support", nameAr: "دعم المستوى الثاني", cost: 399, tasks: 400, efficiency: 97 },
      { id: "support-lead", name: "Support Lead", nameAr: "قائد الدعم", cost: 599, tasks: 300, efficiency: 96 }
    ]
  },
  {
    id: "marketing",
    name: "Marketing",
    nameAr: "التسويق",
    color: "from-electric-cyan to-blue-500",
    agents: [
      { id: "content-writer", name: "Content Writer", nameAr: "كاتب محتوى", cost: 349, tasks: 450, efficiency: 94 },
      { id: "seo-specialist", name: "SEO Specialist", nameAr: "خبير SEO", cost: 449, tasks: 350, efficiency: 96 },
      { id: "campaign-mgr", name: "Campaign Manager", nameAr: "مدير الحملات", cost: 599, tasks: 250, efficiency: 95 }
    ]
  },
  {
    id: "operations",
    name: "Operations",
    nameAr: "العمليات",
    color: "from-electric-cyan to-purple-500",
    agents: [
      { id: "workflow-auto", name: "Workflow Automator", nameAr: "مؤتمت سير العمل", cost: 399, tasks: 700, efficiency: 98 },
      { id: "quality-control", name: "Quality Control", nameAr: "مراقبة الجودة", cost: 449, tasks: 500, efficiency: 99 },
      { id: "ops-manager", name: "Operations Manager", nameAr: "مدير العمليات", cost: 699, tasks: 400, efficiency: 97 }
    ]
  },
  {
    id: "finance",
    name: "Finance",
    nameAr: "المالية",
    color: "from-soft-emerald to-pink-500",
    agents: [
      { id: "bookkeeper", name: "Bookkeeper", nameAr: "محاسب", cost: 299, tasks: 400, efficiency: 99 },
      { id: "financial-analyst", name: "Financial Analyst", nameAr: "محلل مالي", cost: 499, tasks: 300, efficiency: 96 },
      { id: "cfo-agent", name: "CFO Agent", nameAr: "وكيل CFO", cost: 899, tasks: 200, efficiency: 98 }
    ]
  },
  {
    id: "hr",
    name: "HR",
    nameAr: "HR",
    color: "from-electric-cyan to-orange-500",
    agents: [
      { id: "recruiter", name: "Recruiter", nameAr: "موظف", cost: 349, tasks: 350, efficiency: 95 },
      { id: "onboarding", name: "Onboarding Specialist", nameAr: "أخصائي التهيئة", cost: 299, tasks: 400, efficiency: 97 },
      { id: "hr-manager", name: "HR Manager", nameAr: "مدير HR", cost: 549, tasks: 250, efficiency: 96 }
    ]
  }
];

interface AgentBuilderProps {
  locale?: Locale;
  className?: string;
  onDeploy?: (configuration: Agent[]) => void;
}

export function AgentBuilder({ locale = "en", className = "", onDeploy }: AgentBuilderProps) {
  const [selectedAgents, setSelectedAgents] = useState<Agent[]>([]);
  const [activeDepartment, setActiveDepartment] = useState<string | null>(null);
  const isRTL = locale === "ar";

  const totalCost = useMemo(() => selectedAgents.reduce((sum, agent) => sum + agent.cost, 0), [selectedAgents]);
  const totalTasks = useMemo(() => selectedAgents.reduce((sum, agent) => sum + agent.tasks, 0), [selectedAgents]);
  const avgEfficiency = useMemo(() => {
    if (selectedAgents.length === 0) return 0;
    return selectedAgents.reduce((sum, agent) => sum + agent.efficiency, 0) / selectedAgents.length;
  }, [selectedAgents]);

  const humanCostSavings = useMemo(() => {
    // Assuming average human employee cost of $5000/month
    const humanEquivalentCost = selectedAgents.length * 5000;
    return humanEquivalentCost - totalCost;
  }, [selectedAgents, totalCost]);

  const addAgent = (department: Department, agentTemplate: Department["agents"][0]) => {
    const newAgent: Agent = {
      id: `${Date.now()}-${agentTemplate.id}`,
      type: agentTemplate.id,
      name: locale === "ar" ? agentTemplate.nameAr : agentTemplate.name,
      department: locale === "ar" ? department.nameAr : department.name,
      cost: agentTemplate.cost,
      tasks: agentTemplate.tasks,
      efficiency: agentTemplate.efficiency
    };
    setSelectedAgents([...selectedAgents, newAgent]);
  };

  const removeAgent = (agentId: string) => {
    setSelectedAgents(selectedAgents.filter(agent => agent.id !== agentId));
  };

  const handleDeploy = () => {
    if (onDeploy && selectedAgents.length > 0) {
      onDeploy(selectedAgents);
    }
  };

  return (
    <div className={`bg-obsidian/80 backdrop-blur-xl border border-white/10 rounded-2xl overflow-hidden ${className}`} dir={isRTL ? "rtl" : "ltr"}>
      {/* Header */}
      <div className="bg-gradient-to-r from-electric-cyan/20 to-soft-emerald/20 border-b border-white/10 px-6 py-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-gradient-to-r from-electric-cyan to-soft-emerald flex items-center justify-center">
              <Users className="w-5 h-5 text-void-black" />
            </div>
            <div>
              <h3 className="font-space-grotesk font-bold text-warm-white">
                {locale === "en" ? "Build Your AI Workforce" : "ابن قوتك العاملة AI"}
              </h3>
              <p className="text-xs text-muted-white">
                {locale === "en" ? "Select agents to build your dream team" : "اختر الوكلاء لبناء فريق أحلامك"}
              </p>
            </div>
          </div>
          {selectedAgents.length > 0 && (
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              className="bg-soft-emerald/20 border border-soft-emerald/40 rounded-full px-4 py-2"
            >
              <span className="text-sm font-jetbrains-mono text-soft-emerald">
                {selectedAgents.length} {locale === "en" ? "agents" : "وكيل"}
              </span>
            </motion.div>
          )}
        </div>
      </div>

      <div className="grid md:grid-cols-2 gap-6 p-6">
        {/* Left: Department Selection */}
        <div className="space-y-4">
          <h4 className="text-sm font-semibold text-muted-white mb-4">
            {locale === "en" ? "Choose Department" : "اختر القسم"}
          </h4>
          <div className="grid grid-cols-2 gap-3">
            {departmentsData.map((dept) => (
              <motion.button
                key={dept.id}
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                onClick={() => setActiveDepartment(activeDepartment === dept.id ? null : dept.id)}
                className={`p-4 rounded-xl border transition-all ${
                  activeDepartment === dept.id
                    ? "border-electric-cyan/50 bg-electric-cyan/10"
                    : "border-white/10 bg-obsidian/50 hover:border-white/20"
                }`}
              >
                <div className="font-space-grotesk font-semibold text-warm-white text-sm">
                  {locale === "ar" ? dept.nameAr : dept.name}
                </div>
                <div className="text-xs text-muted-white mt-1">
                  {dept.agents.length} {locale === "en" ? "agents" : "وكيل"}
                </div>
              </motion.button>
            ))}
          </div>

          {/* Agent Selection */}
          <AnimatePresence>
            {activeDepartment && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: "auto" }}
                exit={{ opacity: 0, height: 0 }}
                className="space-y-2"
              >
                <h5 className="text-xs font-semibold text-muted-white mb-3">
                  {locale === "en" ? "Select Agent Type" : "اختر نوع الوكيل"}
                </h5>
                {departmentsData
                  .find(d => d.id === activeDepartment)
                  ?.agents.map((agent) => (
                    <motion.button
                      key={agent.id}
                      whileHover={{ x: 5 }}
                      onClick={() => addAgent(
                        departmentsData.find(d => d.id === activeDepartment)!,
                        agent
                      )}
                      className="w-full p-3 rounded-lg border border-white/10 bg-obsidian/50 hover:border-electric-cyan/30 hover:bg-electric-cyan/5 transition-all text-left"
                    >
                      <div className="flex items-center justify-between">
                        <div>
                          <div className="font-space-grotesk font-medium text-warm-white text-sm">
                            {locale === "ar" ? agent.nameAr : agent.name}
                          </div>
                          <div className="text-xs text-muted-white mt-1">
                            ${agent.cost}/mo · {agent.tasks} {locale === "en" ? "tasks/day" : "مهمة/يوم"}
                          </div>
                        </div>
                        <Plus className="w-5 h-5 text-electric-cyan" />
                      </div>
                    </motion.button>
                  ))}
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        {/* Right: Selected Agents */}
        <div className="space-y-4">
          <h4 className="text-sm font-semibold text-muted-white mb-4">
            {locale === "en" ? "Your AI Team" : "فريق AI الخاص بك"}
          </h4>

          {selectedAgents.length === 0 ? (
            <div className="border-2 border-dashed border-white/10 rounded-xl p-8 text-center">
              <Users className="w-12 h-12 text-muted-white/40 mx-auto mb-3" />
              <p className="text-sm text-muted-white">
                {locale === "en" ? "No agents selected yet" : "لم يتم اختيار وكلاء بعد"}
              </p>
              <p className="text-xs text-muted-white/60 mt-1">
                {locale === "en" ? "Choose a department to get started" : "اختر قسماً للبدء"}
              </p>
            </div>
          ) : (
            <div className="space-y-2 max-h-[300px] overflow-y-auto">
              <AnimatePresence>
                {selectedAgents.map((agent) => (
                  <motion.div
                    key={agent.id}
                    initial={{ opacity: 0, x: isRTL ? 20 : -20 }}
                    animate={{ opacity: 1, x: 0 }}
                    exit={{ opacity: 0, x: isRTL ? -20 : 20 }}
                    className="bg-obsidian/50 border border-white/10 rounded-lg p-3"
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div className="flex-1 min-w-0">
                        <div className="font-space-grotesk font-medium text-warm-white text-sm truncate">
                          {agent.name}
                        </div>
                        <div className="text-xs text-muted-white mt-1">
                          {agent.department} · ${agent.cost}/mo
                        </div>
                        <div className="flex items-center gap-3 mt-2">
                          <div className="flex items-center gap-1">
                            <Zap className="w-3 h-3 text-soft-emerald" />
                            <span className="text-[10px] text-soft-emerald">{agent.efficiency}%</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <DollarSign className="w-3 h-3 text-electric-cyan" />
                            <span className="text-[10px] text-electric-cyan">{agent.tasks}/day</span>
                          </div>
                        </div>
                      </div>
                      <button
                        onClick={() => removeAgent(agent.id)}
                        className="text-muted-white hover:text-red-400 transition-colors"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </motion.div>
                ))}
              </AnimatePresence>
            </div>
          )}

          {/* Cost Summary */}
          {selectedAgents.length > 0 && (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="bg-gradient-to-r from-electric-cyan/10 to-soft-emerald/10 border border-electric-cyan/20 rounded-xl p-4 space-y-3"
            >
              <div className="flex justify-between items-center">
                <span className="text-sm text-muted-white">
                  {locale === "en" ? "Monthly Cost" : "التكلفة الشهرية"}
                </span>
                <span className="font-space-grotesk font-bold text-warm-white">${totalCost}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm text-muted-white">
                  {locale === "en" ? "Tasks/Day" : "مهمة/يوم"}
                </span>
                <span className="font-space-grotesk font-bold text-electric-cyan">{totalTasks}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm text-muted-white">
                  {locale === "en" ? "Avg Efficiency" : "متوسط الكفاءة"}
                </span>
                <span className="font-space-grotesk font-bold text-soft-emerald">{avgEfficiency.toFixed(1)}%</span>
              </div>
              <div className="pt-3 border-t border-white/10 flex justify-between items-center">
                <span className="text-sm text-warm-white">
                  {locale === "en" ? "Savings vs Human" : "التوفير مقابل البشر"}
                </span>
                <span className="font-space-grotesk font-bold text-soft-emerald">+${humanCostSavings}</span>
              </div>
            </motion.div>
          )}
        </div>
      </div>

      {/* Footer Action */}
      {selectedAgents.length > 0 && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="border-t border-white/10 p-4"
        >
          <button
            onClick={handleDeploy}
            className="w-full bg-gradient-to-r from-electric-cyan to-soft-emerald text-void-black font-semibold py-3 px-4 rounded-xl hover:opacity-90 transition-opacity flex items-center justify-center gap-2"
          >
            <CheckCircle2 className="w-5 h-5" />
            <span>
              {locale === "en" ? "Deploy AI Team" : "نشر فريق AI"}
            </span>
            <span className="font-jetbrains-mono text-sm opacity-70">
              (${totalCost}/mo)
            </span>
          </button>
        </motion.div>
      )}
    </div>
  );
}
