"use client";

import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Play, Pause, SkipForward, ArrowRight, CheckCircle2, Clock, Users, Zap } from "lucide-react";
import type { Locale } from "@/lib/i18n";

interface WorkflowVisualizationProps {
  locale?: Locale;
  className?: string;
}

interface WorkflowStep {
  id: string;
  agent: string;
  agentType: string;
  action: string;
  status: "pending" | "active" | "completed";
  duration: string;
  color: string;
}

interface WorkflowScenario {
  id: string;
  name: string;
  nameAr: string;
  description: string;
  descriptionAr: string;
  steps: WorkflowStep[];
}

const workflowScenarios: WorkflowScenario[] = [
  {
    id: "customer-onboarding",
    name: "Customer Onboarding",
    nameAr: "تهيئة العميل",
    description: "Watch how AI agents collaborate to onboard a new customer seamlessly",
    descriptionAr: "شاهد كيف يتعاون وكلاء AI لتهيئة عميل جديد بسلاسة",
    steps: [
      {
        id: "step1",
        agent: "Sales Agent",
        agentType: "sales",
        action: "Receives new customer signup - Ahmed Al-Rashid",
        status: "pending",
        duration: "2s",
        color: "from-electric-cyan to-soft-emerald"
      },
      {
        id: "step2",
        agent: "Sales Agent",
        agentType: "sales",
        action: "Creates customer profile and assigns account manager",
        status: "pending",
        duration: "3s",
        color: "from-electric-cyan to-soft-emerald"
      },
      {
        id: "step3",
        agent: "Ops Engine",
        agentType: "operations",
        action: "Provisions account and sends welcome email",
        status: "pending",
        duration: "4s",
        color: "from-electric-cyan to-purple-500"
      },
      {
        id: "step4",
        agent: "Finance Core",
        agentType: "finance",
        action: "Creates invoice and sets up payment method",
        status: "pending",
        duration: "3s",
        color: "from-soft-emerald to-pink-500"
      },
      {
        id: "step5",
        agent: "Support Lead",
        agentType: "support",
        action: "Schedules onboarding call for tomorrow",
        status: "pending",
        duration: "2s",
        color: "from-soft-emerald to-teal-500"
      },
      {
        id: "step6",
        agent: "HR Hub",
        agentType: "hr",
        action: "Updates customer database and triggers internal notifications",
        status: "pending",
        duration: "2s",
        color: "from-electric-cyan to-orange-500"
      }
    ]
  },
  {
    id: "lead-qualification",
    name: "Lead Qualification",
    nameAr: "تأهيل العميل المحتمل",
    description: "See AI agents automatically qualify and route incoming leads",
    descriptionAr: "شاهد وكلاء AI يؤهلون ويوجهون العملاء المحتملين تلقائياً",
    steps: [
      {
        id: "step1",
        agent: "Marketing Hub",
        agentType: "marketing",
        action: "Captures lead from landing page form",
        status: "pending",
        duration: "2s",
        color: "from-electric-cyan to-blue-500"
      },
      {
        id: "step2",
        agent: "Sales Agent",
        agentType: "sales",
        action: "Analyzes lead intent: HIGH (87% score)",
        status: "pending",
        duration: "3s",
        color: "from-electric-cyan to-soft-emerald"
      },
      {
        id: "step3",
        agent: "Sales Agent",
        agentType: "sales",
        action: "Enriches lead data from 5 external sources",
        status: "pending",
        duration: "4s",
        color: "from-electric-cyan to-soft-emerald"
      },
      {
        id: "step4",
        agent: "Ops Engine",
        agentType: "operations",
        action: "Routes to Enterprise team based on company size",
        status: "pending",
        duration: "2s",
        color: "from-electric-cyan to-purple-500"
      },
      {
        id: "step5",
        agent: "Sales Agent",
        agentType: "sales",
        action: "Sends personalized follow-up email",
        status: "pending",
        duration: "2s",
        color: "from-electric-cyan to-soft-emerald"
      }
    ]
  },
  {
    id: "support-resolution",
    name: "Support Resolution",
    nameAr: "حل مشكلة الدعم",
    description: "Experience AI-driven support resolution with automatic escalation",
    descriptionAr: "عش حل الدعم المدعوم بـ AI مع التصعيد التلقائي",
    steps: [
      {
        id: "step1",
        agent: "Tier 1 Support",
        agentType: "support",
        action: "Receives ticket: 'Payment processing failed'",
        status: "pending",
        duration: "2s",
        color: "from-soft-emerald to-teal-500"
      },
      {
        id: "step2",
        agent: "Tier 1 Support",
        agentType: "support",
        action: "Attempts standard fixes - unable to resolve",
        status: "pending",
        duration: "3s",
        color: "from-soft-emerald to-teal-500"
      },
      {
        id: "step3",
        agent: "Ops Engine",
        agentType: "operations",
        action: "Detects payment gateway anomaly - escalates",
        status: "pending",
        duration: "3s",
        color: "from-electric-cyan to-purple-500"
      },
      {
        id: "step4",
        agent: "Finance Core",
        agentType: "finance",
        action: "Investigates transaction log - finds root cause",
        status: "pending",
        duration: "4s",
        color: "from-soft-emerald to-pink-500"
      },
      {
        id: "step5",
        agent: "Finance Core",
        agentType: "finance",
        action: "Applies fix and processes refund",
        status: "pending",
        duration: "2s",
        color: "from-soft-emerald to-pink-500"
      },
      {
        id: "step6",
        agent: "Tier 2 Support",
        agentType: "support",
        action: "Confirms resolution with customer - ticket closed",
        status: "pending",
        duration: "2s",
        color: "from-soft-emerald to-teal-500"
      }
    ]
  }
];

export function WorkflowVisualization({ locale = "en", className = "" }: WorkflowVisualizationProps) {
  const [activeScenario, setActiveScenario] = useState<string>("customer-onboarding");
  const [currentStepIndex, setCurrentStepIndex] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [workflowState, setWorkflowState] = useState<"idle" | "running" | "completed" | "paused">("idle");
  const isRTL = locale === "ar";

  const currentScenario = workflowScenarios.find(s => s.id === activeScenario)!;

  useEffect(() => {
    if (!isPlaying || workflowState === "idle" || workflowState === "paused" || workflowState === "completed") return;

    const interval = setInterval(() => {
      setCurrentStepIndex((prev) => {
        if (prev < currentScenario.steps.length - 1) {
          return prev + 1;
        } else {
          setWorkflowState("completed");
          setIsPlaying(false);
          return prev;
        }
      });
    }, 2500);

    return () => clearInterval(interval);
  }, [isPlaying, workflowState, currentScenario.steps.length]);

  const handlePlay = () => {
    if (workflowState === "completed") {
      // Reset
      setCurrentStepIndex(0);
      setWorkflowState("running");
      setIsPlaying(true);
    } else {
      setWorkflowState(isPlaying ? "paused" : "running");
      setIsPlaying(!isPlaying);
    }
  };

  const handleReset = () => {
    setCurrentStepIndex(0);
    setWorkflowState("idle");
    setIsPlaying(false);
  };

  const handleScenarioChange = (scenarioId: string) => {
    setActiveScenario(scenarioId);
    handleReset();
  };

  const activeStep = workflowState === "idle" ? null : currentScenario.steps[currentStepIndex];
  const completedSteps = workflowState === "idle" ? [] : currentScenario.steps.slice(0, currentStepIndex);
  const pendingSteps = workflowState === "idle"
    ? currentScenario.steps
    : currentScenario.steps.slice(currentStepIndex + 1);

  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">
              <Zap className="w-5 h-5 text-void-black" />
            </div>
            <div>
              <h3 className="font-space-grotesk font-bold text-warm-white">
                {locale === "en" ? "AI Workflow Visualization" : "تصور سير العمل AI"}
              </h3>
              <p className="text-xs text-muted-white">
                {locale === "en" ? "Watch agents collaborate in real-time" : "شاهد الوكلاء يتعاونون في الوقت الفعلي"}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={handleReset}
              className="p-2 rounded-lg bg-white/5 text-muted-white hover:text-warm-white transition-colors"
              title={locale === "en" ? "Reset" : "إعادة تعيين"}
            >
              <SkipForward className="w-4 h-4" />
            </button>
            <button
              onClick={handlePlay}
              className="flex items-center gap-2 px-4 py-2 rounded-lg bg-electric-cyan/20 text-electric-cyan hover:bg-electric-cyan/30 transition-all"
            >
              {isPlaying ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
              <span className="text-sm font-medium">
                {isPlaying ? (locale === "en" ? "Pause" : "إيقاف") : (locale === "en" ? "Play" : "تشغيل")}
              </span>
            </button>
          </div>
        </div>
      </div>

      <div className="p-6 space-y-6">
        {/* Scenario Selector */}
        <div className="flex flex-wrap gap-3">
          {workflowScenarios.map((scenario) => (
            <button
              key={scenario.id}
              onClick={() => handleScenarioChange(scenario.id)}
              className={`px-4 py-3 rounded-xl border transition-all ${
                activeScenario === scenario.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-medium text-warm-white text-sm">
                {locale === "ar" ? scenario.nameAr : scenario.name}
              </div>
            </button>
          ))}
        </div>

        {/* Description */}
        <motion.div
          key={activeScenario}
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center"
        >
          <p className="text-sm text-muted-white">
            {locale === "ar" ? currentScenario.descriptionAr : currentScenario.description}
          </p>
        </motion.div>

        {/* Workflow Visualization */}
        <div className="relative space-y-4">
          {/* Progress Line */}
          <div className="absolute left-8 top-0 bottom-0 w-0.5 bg-white/10" />
          <div
            className="absolute left-8 top-0 w-0.5 bg-gradient-to-b from-electric-cyan to-soft-emerald transition-all duration-1000"
            style={{
              height: workflowState === "idle" ? "0%" : `${((currentStepIndex + 1) / currentScenario.steps.length) * 100}%`
            }}
          />

          {/* Workflow Steps */}
          <div className="space-y-4">
            {/* Completed Steps */}
            {completedSteps.map((step, index) => (
              <motion.div
                key={step.id}
                initial={{ opacity: 0, x: isRTL ? 20 : -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.3, delay: index * 0.1 }}
                className="relative flex items-start gap-4"
              >
                <div className="w-16 flex justify-center">
                  <div className={`w-8 h-8 rounded-full bg-gradient-to-r ${step.color} flex items-center justify-center`}>
                    <CheckCircle2 className="w-4 h-4 text-void-black" />
                  </div>
                </div>
                <div className="flex-1 bg-white/5 border border-white/10 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-space-grotesk font-semibold text-warm-white text-sm">
                      {step.agent}
                    </span>
                    <span className="text-[10px] text-muted-white font-jetbrains-mono">
                      {step.duration}
                    </span>
                  </div>
                  <div className="text-xs text-muted-white">{step.action}</div>
                </div>
              </motion.div>
            ))}

            {/* Active Step */}
            <AnimatePresence mode="wait">
              {activeStep && workflowState !== "idle" && (
                <motion.div
                  key={activeStep.id}
                  initial={{ opacity: 0, scale: 0.95 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.95 }}
                  transition={{ duration: 0.3 }}
                  className="relative flex items-start gap-4"
                >
                  <div className="w-16 flex justify-center">
                    <motion.div
                      animate={{ scale: [1, 1.1, 1] }}
                      transition={{ duration: 1, repeat: Infinity }}
                      className={`w-8 h-8 rounded-full bg-gradient-to-r ${activeStep.color} flex items-center justify-center`}
                    >
                      <Clock className="w-4 h-4 text-void-black" />
                    </motion.div>
                  </div>
                  <div className={`flex-1 bg-gradient-to-r ${activeStep.color} border border-white/20 rounded-lg p-4`}>
                    <div className="flex items-center justify-between mb-2">
                      <span className="font-space-grotesk font-semibold text-void-black text-sm">
                        {activeStep.agent}
                      </span>
                      <div className="flex items-center gap-2">
                        <span className="text-[10px] text-void-black/70 font-jetbrains-mono">
                          {activeStep.duration}
                        </span>
                        <motion.div
                          animate={{ opacity: [0.5, 1, 0.5] }}
                          transition={{ duration: 1.5, repeat: Infinity }}
                          className="w-2 h-2 bg-void-black rounded-full"
                        />
                      </div>
                    </div>
                    <div className="text-xs text-void-black/90">{activeStep.action}</div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>

            {/* Pending Steps */}
            {pendingSteps.map((step, index) => (
              <div
                key={step.id}
                className="relative flex items-start gap-4 opacity-40"
              >
                <div className="w-16 flex justify-center">
                  <div className="w-8 h-8 rounded-full bg-white/10 border border-white/20 flex items-center justify-center">
                    <Clock className="w-4 h-4 text-muted-white" />
                  </div>
                </div>
                <div className="flex-1 bg-white/5 border border-white/10 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-space-grotesk font-semibold text-muted-white text-sm">
                      {step.agent}
                    </span>
                    <span className="text-[10px] text-muted-white font-jetbrains-mono">
                      {step.duration}
                    </span>
                  </div>
                  <div className="text-xs text-muted-white">{step.action}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Completion Message */}
        <AnimatePresence>
          {workflowState === "completed" && (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="bg-gradient-to-r from-soft-emerald/20 to-teal-500/20 border border-soft-emerald/30 rounded-xl p-4 text-center"
            >
              <div className="flex items-center justify-center gap-3 mb-2">
                <CheckCircle2 className="w-6 h-6 text-soft-emerald" />
                <span className="font-space-grotesk font-bold text-soft-emerald">
                  {locale === "en" ? "Workflow Completed!" : "اكتمل سير العمل!"}
                </span>
              </div>
              <p className="text-sm text-muted-white">
                {locale === "en"
                  ? `${currentScenario.steps.length} AI agents collaborated to complete this task in ${currentScenario.steps.length * 2.5} seconds`
                  : `${currentScenario.steps.length} وكيل AI تعاونوا لإكمال هذه المهمة في ${currentScenario.steps.length * 2.5} ثانية`
                }
              </p>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Stats */}
        <div className="grid grid-cols-3 gap-4">
          <div className="text-center p-3 bg-white/5 rounded-lg">
            <div className="text-lg font-space-grotesk font-bold text-electric-cyan">
              {currentScenario.steps.length}
            </div>
            <div className="text-[10px] text-muted-white">
              {locale === "en" ? "Agents" : "وكيل"}
            </div>
          </div>
          <div className="text-center p-3 bg-white/5 rounded-lg">
            <div className="text-lg font-space-grotesk font-bold text-soft-emerald">
              {Math.round(currentScenario.steps.length * 2.5)}s
            </div>
            <div className="text-[10px] text-muted-white">
              {locale === "en" ? "Total Time" : "الوقت الإجمالي"}
            </div>
          </div>
          <div className="text-center p-3 bg-white/5 rounded-lg">
            <div className="text-lg font-space-grotesk font-bold text-warm-white">
              {currentScenario.steps.length}x
            </div>
            <div className="text-[10px] text-muted-white">
              {locale === "en" ? "Faster" : "أسرع"}
            </div>
          </div>
        </div>

        {/* CTA */}
        <button
          onClick={handlePlay}
          className="w-full bg-gradient-to-r from-electric-cyan to-soft-emerald text-void-black font-semibold py-4 px-6 rounded-xl hover:opacity-90 transition-opacity flex items-center justify-center gap-2"
        >
          <Users className="w-5 h-5" />
          <span>
            {locale === "en" ? "Build Your AI Workforce" : "ابن قوتك العاملة AI"}
          </span>
          <ArrowRight className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}
