"use client";

import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { ChevronRight, Play, Pause, BarChart3, MessageSquare, TrendingUp, Users } from "lucide-react";
import type { Locale } from "@/lib/i18n";

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

interface DemoConversation {
  role: string;
  message: string;
  timestamp: string;
}

interface DepartmentData {
  id: string;
  name: string;
  nameAr: string;
  color: string;
  icon: string;
  description: string;
  descriptionAr: string;
  conversations: DemoConversation[];
  metrics: {
    before: string;
    after: string;
    improvement: string;
  };
}

const departmentsData: DepartmentData[] = [
  {
    id: "sales",
    name: "Sales",
    nameAr: "المبيعات",
    color: "from-electric-cyan to-soft-emerald",
    icon: "💼",
    description: "AI agents that qualify leads, follow up instantly, and close deals 24/7",
    descriptionAr: "وكلاء AI يؤهلون العملاء المحتملين، يتابعون فوراً، ويغلقون الصفقات على مدار الساعة",
    conversations: [
      { role: "Customer", message: "Hi, I'm interested in your enterprise plan", timestamp: "09:32" },
      { role: "Sales Agent", message: "Great choice! I can help you with that. How many users do you expect?", timestamp: "09:32" },
      { role: "Customer", message: "Around 50 users to start", timestamp: "09:33" },
      { role: "Sales Agent", message: "Perfect. Based on 50 users, I'd recommend our Enterprise tier at SAR 24,999/mo. This includes unlimited AI agents and 24/7 support. Would you like me to prepare a custom proposal?", timestamp: "09:33" },
      { role: "Customer", message: "That sounds good. Yes, please send the proposal", timestamp: "09:34" },
      { role: "Sales Agent", message: "Excellent! I've generated your personalized proposal and scheduled a follow-up for tomorrow at 10 AM. You'll receive it via email in 2 minutes. Deal stage: Proposal Sent ✓", timestamp: "09:34" }
    ],
    metrics: {
      before: "45 day sales cycle",
      after: "7 day sales cycle",
      improvement: "80% faster"
    }
  },
  {
    id: "support",
    name: "Support",
    nameAr: "الدعم",
    color: "from-soft-emerald to-teal-500",
    icon: "🎧",
    description: "Instant support that resolves 80% of issues without human intervention",
    descriptionAr: "دعم فوري يحل 80٪ من المشاكل بدون تدخل بشري",
    conversations: [
      { role: "Customer", message: "I can't access my dashboard, getting error 403", timestamp: "14:22" },
      { role: "Support Agent", message: "I'm sorry to hear that! Let me help you resolve this immediately. I can see you're on the Professional plan. Is this happening across all devices or just one?", timestamp: "14:22" },
      { role: "Customer", message: "Just my laptop, mobile app works fine", timestamp: "14:23" },
      { role: "Support Agent", message: "Thank you for that detail. Based on your account, I can see this is likely a permissions issue. I'm running a diagnostic... Found it! Your account was locked due to 3 failed login attempts. I'm unlocking it now and sending you a secure password reset link.", timestamp: "14:23" },
      { role: "Support Agent", message: "Issue resolved! ✓ Your dashboard should now be accessible. I've also enabled two-factor authentication to prevent this in the future.", timestamp: "14:24" },
      { role: "Customer", message: "Wow, that was fast! Thank you!", timestamp: "14:24" }
    ],
    metrics: {
      before: "18 hour avg response",
      after: "30 second avg response",
      improvement: "99% faster"
    }
  },
  {
    id: "marketing",
    name: "Marketing",
    nameAr: "التسويق",
    color: "from-electric-cyan to-blue-500",
    icon: "📱",
    description: "Content creation, campaign management, and performance optimization on autopilot",
    descriptionAr: "إنشاء المحتوى، إدارة الحملات، وتحسين الأداء تلقائياً",
    conversations: [
      { role: "Marketing Hub", message: "📊 Weekly Campaign Report Ready", timestamp: "09:00" },
      { role: "Marketing Hub", message: "Last week's performance:\n• Email open rate: 28% (+4%)\n• Social engagement: 3.2% (+1.2%)\n• Landing page conversion: 8.5% (+2.1%)\n• ROI: 340%", timestamp: "09:00" },
      { role: "Marketing Hub", message: "🎯 New opportunities detected:\n1. 'AI in Manufacturing' trending - suggested content angle\n2. Competitor launched new feature - analysis ready\n3. Best-performing post identified - recommend scaling", timestamp: "09:01" },
      { role: "Marketing Hub", message: "✅ Actions taken:\n• Created 3 blog posts for trending topic\n• Generated competitor comparison article\n• Allocated SAR 5,000 to scale winning ad\n• Scheduled 12 social posts for this week", timestamp: "09:02" }
    ],
    metrics: {
      before: "40 hrs content creation/mo",
      after: "2 hrs content creation/mo",
      improvement: "95% time saved"
    }
  },
  {
    id: "finance",
    name: "Finance",
    nameAr: "المالية",
    color: "from-soft-emerald to-pink-500",
    icon: "💰",
    description: "Automated invoicing, expense tracking, and financial reporting",
    descriptionAr: "الفواتير الآلية، تتبع النفقات، والتقارير المالية",
    conversations: [
      { role: "Finance Core", message: "📊 Monthly Financial Summary - June 2026", timestamp: "08:00" },
      { role: "Finance Core", message: "Revenue: SAR 287,450 (+12% vs May)\nExpenses: SAR 89,320 (-8% vs May)\nNet Profit: SAR 198,130\nProfit Margin: 69%", timestamp: "08:00" },
      { role: "Finance Core", message: "💡 Insights:\n• Largest expense category: Software subscriptions (32%)\n• 3 vendors with overdue payments - collection initiated\n• 2 invoices ready for sending - draft created\n• Tax deadline in 15 days - ZATCA compliance check passed ✓", timestamp: "08:01" },
      { role: "Finance Core", message: "⚡ Automated actions completed:\n• Sent 2 customer invoices (SAR 45,000 total)\n• Initiated collection for 3 overdue payments\n• Generated cash flow forecast for next 60 days\n• Updated financial projections for Q3", timestamp: "08:02" }
    ],
    metrics: {
      before: "25 hrs bookkeeping/mo",
      after: "2 hrs bookkeeping/mo",
      improvement: "92% time saved"
    }
  },
  {
    id: "operations",
    name: "Operations",
    nameAr: "العمليات",
    color: "from-electric-cyan to-purple-500",
    icon: "⚙️",
    description: "Workflow automation, quality control, and process optimization",
    descriptionAr: "أتمتة سير العمل، مراقبة الجودة، وتحسين العمليات",
    conversations: [
      { role: "Ops Engine", message: "🔍 Workflow Analysis Complete", timestamp: "10:15" },
      { role: "Ops Engine", message: "Bottleneck detected in 'Customer Onboarding' process:\n• Average completion time: 8 days\n• Stage 3 (Account setup) takes 4 days\n• 23% drop-off at stage 3", timestamp: "10:15" },
      { role: "Ops Engine", message: "🎯 Optimization suggested:\n• Automate account setup (saves 3 days)\n• Add real-time progress tracking\n• Implement automated reminders", timestamp: "10:16" },
      { role: "Ops Engine", message: "✅ Optimization deployed:\n• New workflow automation active\n• Expected improvement: 60% faster onboarding\n• Projected completion time: 3 days\n• A/B test initiated - will measure results over next 50 customers", timestamp: "10:17" }
    ],
    metrics: {
      before: "70% process efficiency",
      after: "98% process efficiency",
      improvement: "40% improvement"
    }
  },
  {
    id: "hr",
    name: "HR",
    nameAr: "HR",
    color: "from-electric-cyan to-orange-500",
    icon: "👥",
    description: "Recruitment, onboarding, and employee management automation",
    descriptionAr: "التوظيف، التهيئة، وإدارة الموظفين الآلية",
    conversations: [
      { role: "HR Hub", message: "📋 Recruitment Pipeline Update", timestamp: "11:00" },
      { role: "HR Hub", message: "Active positions: 12\nTotal applicants: 847\nScreened: 234\nInterviews scheduled: 18\nOffers sent: 5", timestamp: "11:00" },
      { role: "HR Hub", message: "⚡ Automated actions:\n• Screened 156 new applicants (AI qualified 23)\n• Scheduled 8 interviews for next week\n• Sent 3 offer letters to top candidates\n• Initiated background checks for 5 candidates", timestamp: "11:01" },
      { role: "HR Hub", message: "📊 Top performing candidates:\n1. Ahmed Al-Rashid - 98% match score\n2. Sarah Mohammed - 96% match score\n3. Khalid Othman - 94% match score\n\nRecommendation: Fast-track Ahmed for Senior Developer role", timestamp: "11:02" }
    ],
    metrics: {
      before: "45 day hiring process",
      after: "14 day hiring process",
      improvement: "70% faster hiring"
    }
  }
];

export function DepartmentDemo({ locale = "en", className = "" }: DepartmentDemoProps) {
  const [activeDepartment, setActiveDepartment] = useState<string>("sales");
  const [isPlaying, setIsPlaying] = useState(true);
  const [currentMessageIndex, setCurrentMessageIndex] = useState(0);
  const [demoMode, setDemoMode] = useState<"conversation" | "metrics">("conversation");
  const isRTL = locale === "ar";

  const activeDept = departmentsData.find(d => d.id === activeDepartment)!;

  useEffect(() => {
    if (!isPlaying) return;

    const interval = setInterval(() => {
      setCurrentMessageIndex((prev) => {
        const conversations = activeDept.conversations;
        if (prev < conversations.length - 1) {
          return prev + 1;
        } else {
          // Reset and pause
          setIsPlaying(false);
          return 0;
        }
      });
    }, 2000);

    return () => clearInterval(interval);
  }, [isPlaying, activeDept]);

  const handleDepartmentChange = (deptId: string) => {
    setActiveDepartment(deptId);
    setCurrentMessageIndex(0);
    setIsPlaying(false);
  };

  const handlePlay = () => {
    if (currentMessageIndex === activeDept.conversations.length - 1) {
      setCurrentMessageIndex(0);
    }
    setIsPlaying(!isPlaying);
  };

  return (
    <div className={`space-y-6 ${className}`} dir={isRTL ? "rtl" : "ltr"}>
      {/* Department Tabs */}
      <div className="flex flex-wrap gap-3">
        {departmentsData.map((dept) => (
          <button
            key={dept.id}
            onClick={() => handleDepartmentChange(dept.id)}
            className={`px-4 py-3 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="flex items-center gap-2">
              <span className="text-xl">{dept.icon}</span>
              <span className="font-space-grotesk font-medium text-warm-white text-sm">
                {locale === "ar" ? dept.nameAr : dept.name}
              </span>
            </div>
          </button>
        ))}
      </div>

      {/* Demo Mode Toggle */}
      <div className="flex gap-2">
        <button
          onClick={() => setDemoMode("conversation")}
          className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all ${
            demoMode === "conversation"
              ? "bg-electric-cyan/20 text-electric-cyan"
              : "bg-obsidian/50 text-muted-white hover:text-warm-white"
          }`}
        >
          <MessageSquare className="w-4 h-4" />
          <span className="text-sm font-medium">
            {locale === "en" ? "Live Demo" : "عرض مباشر"}
          </span>
        </button>
        <button
          onClick={() => setDemoMode("metrics")}
          className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all ${
            demoMode === "metrics"
              ? "bg-electric-cyan/20 text-electric-cyan"
              : "bg-obsidian/50 text-muted-white hover:text-warm-white"
          }`}
        >
          <BarChart3 className="w-4 h-4" />
          <span className="text-sm font-medium">
            {locale === "en" ? "Performance" : "الأداء"}
          </span>
        </button>
      </div>

      <AnimatePresence mode="wait">
        {demoMode === "conversation" ? (
          <motion.div
            key="conversation"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            transition={{ duration: 0.3 }}
          >
            {/* Live Demo Panel */}
            <div className="bg-obsidian/80 backdrop-blur-xl border border-white/10 rounded-2xl overflow-hidden">
              {/* 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">
                    <span className="text-2xl">{activeDept.icon}</span>
                    <div>
                      <h3 className="font-space-grotesk font-bold text-warm-white">
                        {locale === "ar" ? activeDept.nameAr : activeDept.name}
                      </h3>
                      <p className="text-xs text-muted-white">
                        {locale === "ar" ? activeDept.descriptionAr : activeDept.description}
                      </p>
                    </div>
                  </div>
                  <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>

              {/* Conversation */}
              <div className="p-6 space-y-4 max-h-[400px] overflow-y-auto">
                {activeDept.conversations.slice(0, currentMessageIndex + 1).map((msg, index) => (
                  <motion.div
                    key={index}
                    initial={{ opacity: 0, x: isRTL ? 20 : -20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ duration: 0.3, delay: index * 0.1 }}
                    className={`flex ${msg.role === "Customer" ? "justify-start" : "justify-end"}`}
                  >
                    <div
                      className={`max-w-[80%] rounded-2xl px-4 py-3 ${
                        msg.role === "Customer"
                          ? "bg-white/5 border border-white/10"
                          : `bg-gradient-to-r ${activeDept.color} border border-white/10`
                      }`}
                    >
                      <div className="flex items-center gap-2 mb-2">
                        <span className="text-xs font-jetbrains-mono text-muted-white">
                          {msg.role === "Customer" ? (locale === "en" ? "Customer" : "العميل") : (locale === "ar" ? activeDept.nameAr : activeDept.name)}
                        </span>
                        <span className="text-[10px] text-muted-white/60">{msg.timestamp}</span>
                      </div>
                      <p className="text-sm whitespace-pre-wrap text-warm-white">
                        {msg.message}
                      </p>
                    </div>
                  </motion.div>
                ))}
              </div>
            </div>
          </motion.div>
        ) : (
          <motion.div
            key="metrics"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            transition={{ duration: 0.3 }}
          >
            {/* Performance Metrics */}
            <div className="bg-obsidian/80 backdrop-blur-xl border border-white/10 rounded-2xl p-6">
              <div className="flex items-center justify-between mb-6">
                <div className="flex items-center gap-3">
                  <span className="text-2xl">{activeDept.icon}</span>
                  <h3 className="font-space-grotesk font-bold text-warm-white text-lg">
                    {locale === "en" ? "Performance Comparison" : "مقارنة الأداء"}
                  </h3>
                </div>
                <span className="text-soft-emerald font-jetbrains-mono text-sm">
                  {locale === "ar" ? activeDept.nameAr : activeDept.name}
                </span>
              </div>

              {/* Before/After Comparison */}
              <div className="grid md:grid-cols-3 gap-6">
                {/* Before */}
                <div className="text-center p-4 rounded-xl bg-white/5 border border-white/10">
                  <div className="flex items-center justify-center gap-2 mb-2">
                    <Users className="w-5 h-5 text-muted-white" />
                    <span className="text-sm text-muted-white">
                      {locale === "en" ? "Before (Human)" : "قبل (بشري)"}
                    </span>
                  </div>
                  <div className="text-2xl font-space-grotesk font-bold text-muted-white">
                    {activeDept.metrics.before}
                  </div>
                </div>

                {/* After */}
                <div className="text-center p-4 rounded-xl bg-gradient-to-br from-electric-cyan/20 to-soft-emerald/20 border border-electric-cyan/30">
                  <div className="flex items-center justify-center gap-2 mb-2">
                    <TrendingUp className="w-5 h-5 text-soft-emerald" />
                    <span className="text-sm text-soft-emerald">
                      {locale === "en" ? "After (AI)" : "بعد (AI)"}
                    </span>
                  </div>
                  <div className="text-2xl font-space-grotesk font-bold text-soft-emerald">
                    {activeDept.metrics.after}
                  </div>
                </div>

                {/* Improvement */}
                <div className="text-center p-4 rounded-xl bg-gradient-to-br from-soft-emerald/20 to-teal-500/20 border border-soft-emerald/30">
                  <div className="flex items-center justify-center gap-2 mb-2">
                    <ChevronRight className="w-5 h-5 text-warm-white" />
                    <span className="text-sm text-warm-white">
                      {locale === "en" ? "Improvement" : "التحسين"}
                    </span>
                  </div>
                  <div className="text-2xl font-space-grotesk font-bold text-warm-white">
                    {activeDept.metrics.improvement}
                  </div>
                </div>
              </div>

              {/* Visual Bar Chart */}
              <div className="mt-6 space-y-3">
                <div className="flex items-center gap-4">
                  <span className="text-xs text-muted-white w-20">
                    {locale === "en" ? "Before" : "قبل"}
                  </span>
                  <div className="flex-1 h-4 bg-white/5 rounded-full overflow-hidden">
                    <motion.div
                      initial={{ width: 0 }}
                      animate={{ width: "30%" }}
                      transition={{ duration: 0.8, delay: 0.2 }}
                      className="h-full bg-muted-white/50 rounded-full"
                    />
                  </div>
                  <span className="text-xs text-muted-white w-12">30%</span>
                </div>
                <div className="flex items-center gap-4">
                  <span className="text-xs text-soft-emerald w-20">
                    {locale === "en" ? "After AI" : "بعد AI"}
                  </span>
                  <div className="flex-1 h-4 bg-white/5 rounded-full overflow-hidden">
                    <motion.div
                      initial={{ width: 0 }}
                      animate={{ width: "95%" }}
                      transition={{ duration: 0.8, delay: 0.4 }}
                      className="h-full bg-gradient-to-r from-electric-cyan to-soft-emerald rounded-full"
                    />
                  </div>
                  <span className="text-xs text-soft-emerald w-12">95%</span>
                </div>
              </div>

              {/* Key Stats */}
              <div className="mt-6 grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="text-center p-3 rounded-lg bg-white/5">
                  <div className="text-lg font-space-grotesk font-bold text-electric-cyan">99.9%</div>
                  <div className="text-[10px] text-muted-white">
                    {locale === "en" ? "Accuracy" : "الدقة"}
                  </div>
                </div>
                <div className="text-center p-3 rounded-lg bg-white/5">
                  <div className="text-lg font-space-grotesk font-bold text-soft-emerald">24/7</div>
                  <div className="text-[10px] text-muted-white">
                    {locale === "en" ? "Available" : "متاح"}
                  </div>
                </div>
                <div className="text-center p-3 rounded-lg bg-white/5">
                  <div className="text-lg font-space-grotesk font-bold text-electric-cyan">
                    {locale === "en" ? "<30s" : "<30ث"}
                  </div>
                  <div className="text-[10px] text-muted-white">
                    {locale === "en" ? "Response" : "الاستجابة"}
                  </div>
                </div>
                <div className="text-center p-3 rounded-lg bg-white/5">
                  <div className="text-lg font-space-grotesk font-bold text-soft-emerald">∞</div>
                  <div className="text-[10px] text-muted-white">
                    {locale === "en" ? "Scalability" : "قابلية التوسع"}
                  </div>
                </div>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
