"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { ChevronRight, TrendingUp, Users, Clock, DollarSign, ArrowRight, Zap } from "lucide-react";
import type { Locale } from "@/lib/i18n";

interface CaseStudiesProps {
  locale: Locale;
}

interface CaseStudy {
  id: string;
  company: string;
  industry: string;
  logo: string;
  before: {
    employees: number;
    responseTime: string;
    cost: string;
    efficiency: string;
  };
  after: {
    employees: number;
    responseTime: string;
    cost: string;
    efficiency: string;
  };
  story: string[];
  results: {
    metric: string;
    value: string;
    improvement: string;
  }[];
}

const caseStudiesData: CaseStudy[] = [
  {
    id: "retail",
    company: "Al-Noor Retail Group",
    industry: "Retail & E-commerce",
    logo: "🛒",
    before: {
      employees: 45,
      responseTime: "18 hours",
      cost: "$180,000/mo",
      efficiency: "65%"
    },
    after: {
      employees: 8,
      responseTime: "30 seconds",
      cost: "$35,000/mo",
      efficiency: "98%"
    },
    story: [
      "Al-Noor Retail Group operated 12 stores across Saudi Arabia with a growing e-commerce presence. Customer support was overwhelmed during peak seasons.",
      "The company deployed AI agents for customer support, order processing, and inventory management. The AI team handled 80% of customer inquiries autonomously.",
      "Within 3 months, customer satisfaction scores rose from 72% to 94%. The human team focused on complex issues and relationship-building.",
      "Today, Al-Noor processes 3x more orders with 60% fewer staff. Their AI agents work 24/7, handling everything from order tracking to personalized product recommendations."
    ],
    results: [
      { metric: "Cost Savings", value: "$1.7M/yr", improvement: "80% reduction" },
      { metric: "Response Time", value: "30 seconds", improvement: "99% faster" },
      { metric: "Customer Satisfaction", value: "94%", improvement: "+22 points" },
      { metric: "Order Processing", value: "3x capacity", improvement: "200% increase" }
    ]
  },
  {
    id: "finance",
    company: "Saudi FinTech Solutions",
    industry: "Financial Services",
    logo: "💳",
    before: {
      employees: 28,
      responseTime: "24 hours",
      cost: "$140,000/mo",
      efficiency: "70%"
    },
    after: {
      employees: 5,
      responseTime: "2 minutes",
      cost: "$25,000/mo",
      efficiency: "99%"
    },
    story: [
      "Saudi FinTech Solutions provided digital payment processing for hundreds of merchants. Their manual verification process created bottlenecks.",
      "AI agents were deployed for fraud detection, transaction monitoring, and customer onboarding. The system learned from thousands of transactions daily.",
      "Fraud detection accuracy improved from 87% to 99.2%. False positives dropped by 80%, meaning fewer legitimate transactions were blocked.",
      "The company now processes 5x more transactions with the same team. Their AI agents flag suspicious activity in real-time, protecting both merchants and customers."
    ],
    results: [
      { metric: "Fraud Detection", value: "99.2%", improvement: "+12 points" },
      { metric: "Processing Speed", value: "2 minutes", improvement: "95% faster" },
      { metric: "False Positives", value: "-80%", improvement: "Dramatically reduced" },
      { metric: "Transaction Volume", value: "5x capacity", improvement: "400% increase" }
    ]
  },
  {
    id: "healthcare",
    company: "MedCare Saudi",
    industry: "Healthcare",
    logo: "🏥",
    before: {
      employees: 35,
      responseTime: "4 hours",
      cost: "$175,000/mo",
      efficiency: "60%"
    },
    after: {
      employees: 12,
      responseTime: "5 minutes",
      cost: "$45,000/mo",
      efficiency: "95%"
    },
    story: [
      "MedCare Saudi operated multiple clinics across the kingdom. Patient scheduling and follow-up management consumed significant staff time.",
      "AI agents were implemented for appointment scheduling, prescription reminders, and patient inquiries. The system integrated with their existing EHR.",
      "No-show rates dropped from 25% to 8% as AI agents sent personalized reminders and follow-up messages. Patient satisfaction improved significantly.",
      "The medical staff now spends 40% more time with patients and less on administrative tasks. AI agents handle routine communications while humans provide care."
    ],
    results: [
      { metric: "No-Show Rate", value: "8%", improvement: "-68% reduction" },
      { metric: "Patient Time", value: "+40%", improvement: "More care time" },
      { metric: "Response Time", value: "5 minutes", improvement: "98% faster" },
      { metric: "Staff Satisfaction", value: "89%", improvement: "+25 points" }
    ]
  }
];

export function CaseStudies({ locale }: CaseStudiesProps) {
  const [activeCaseStudy, setActiveCaseStudy] = useState<string>("retail");
  const [showStory, setShowStory] = useState(false);
  const isRTL = locale === "ar";

  const activeStudy = caseStudiesData.find(s => s.id === activeCaseStudy)!;

  const formatSAR = (amount: string) => {
    return amount.replace('$', 'SAR ');
  };

  return (
    <section className="py-24 relative overflow-hidden" dir={isRTL ? "rtl" : "ltr"}>
      {/* Background Effects */}
      <div className="absolute inset-0 bg-gradient-to-b from-void-black via-graphite to-void-black" />
      <div className="absolute top-1/2 right-1/3 w-[500px] h-[500px] bg-electric-cyan/10 rounded-full blur-3xl" />
      <div className="absolute bottom-1/3 left-1/4 w-[500px] h-[500px] bg-soft-emerald/10 rounded-full blur-3xl" />

      {/* Content */}
      <div className="container-custom relative z-10">
        {/* Header */}
        <div className="text-center mb-16">
          <h2 className="font-space-grotesk font-bold text-4xl md:text-5xl lg:text-6xl mb-4">
            <span className="text-warm-white block">
              {locale === "en" ? "Real Results," : "نتائج حقيقية،"}
            </span>
            <span className="text-transparent bg-clip-text bg-gradient-to-r from-electric-cyan to-soft-emerald">
              {locale === "en" ? "Real Companies" : "شركات حقيقية"}
            </span>
          </h2>
          <p className="text-lg text-muted-white max-w-2xl mx-auto">
            {locale === "en"
              ? "See how businesses across industries are transforming with AI workforces"
              : "شاهد كيف تحول الشركات عبر الصناعات مع قوى العمل AI"
            }
          </p>
        </div>

        {/* Case Study Selector */}
        <div className="flex flex-wrap justify-center gap-4 mb-12">
          {caseStudiesData.map((study) => (
            <button
              key={study.id}
              onClick={() => {
                setActiveCaseStudy(study.id);
                setShowStory(false);
              }}
              className={`px-6 py-4 rounded-xl border transition-all ${
                activeCaseStudy === study.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-3">
                <span className="text-2xl">{study.logo}</span>
                <div className="text-left">
                  <div className="font-space-grotesk font-semibold text-warm-white text-sm">
                    {study.company}
                  </div>
                  <div className="text-xs text-muted-white">
                    {study.industry}
                  </div>
                </div>
              </div>
            </button>
          ))}
        </div>

        {/* Active Case Study */}
        <AnimatePresence mode="wait">
          <motion.div
            key={activeCaseStudy}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            transition={{ duration: 0.5 }}
            className="space-y-8"
          >
            {/* Before/After Comparison */}
            <div className="grid md:grid-cols-2 gap-6">
              {/* Before */}
              <div className="bg-obsidian/50 border border-white/10 rounded-xl p-6">
                <div className="flex items-center gap-3 mb-6">
                  <div className="w-12 h-12 rounded-full bg-muted-white/10 flex items-center justify-center">
                    <Users className="w-6 h-6 text-muted-white" />
                  </div>
                  <div>
                    <h3 className="font-space-grotesk font-bold text-warm-white">
                      {locale === "en" ? "Before" : "قبل"}
                    </h3>
                    <p className="text-sm text-muted-white">
                      {locale === "en" ? "Traditional Operations" : "العمليات التقليدية"}
                    </p>
                  </div>
                </div>
                <div className="space-y-4">
                  <div className="flex justify-between items-center">
                    <span className="text-muted-white">{locale === "en" ? "Team Size" : "حجم الفريق"}</span>
                    <span className="font-jetbrains-mono text-warm-white">{activeStudy.before.employees} {locale === "en" ? "staff" : "موظف"}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-muted-white">{locale === "en" ? "Response Time" : "وقت الاستجابة"}</span>
                    <span className="font-jetbrains-mono text-warm-white">{activeStudy.before.responseTime}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-muted-white">{locale === "en" ? "Monthly Cost" : "التكلفة الشهرية"}</span>
                    <span className="font-jetbrains-mono text-warm-white">{formatSAR(activeStudy.before.cost)}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-muted-white">{locale === "en" ? "Efficiency" : "الكفاءة"}</span>
                    <span className="font-jetbrains-mono text-warm-white">{activeStudy.before.efficiency}</span>
                  </div>
                </div>
              </div>

              {/* After */}
              <div className="bg-gradient-to-br from-electric-cyan/10 to-soft-emerald/10 border border-electric-cyan/30 rounded-xl p-6">
                <div className="flex items-center gap-3 mb-6">
                  <div className="w-12 h-12 rounded-full bg-gradient-to-r from-electric-cyan to-soft-emerald flex items-center justify-center">
                    <Zap className="w-6 h-6 text-void-black" />
                  </div>
                  <div>
                    <h3 className="font-space-grotesk font-bold text-warm-white">
                      {locale === "en" ? "After AI" : "بعد AI"}
                    </h3>
                    <p className="text-sm text-soft-emerald">
                      {locale === "en" ? "With AI Workforce" : "مع قوة العمل AI"}
                    </p>
                  </div>
                </div>
                <div className="space-y-4">
                  <div className="flex justify-between items-center">
                    <span className="text-muted-white">{locale === "en" ? "Team Size" : "حجم الفريق"}</span>
                    <span className="font-jetbrains-mono text-soft-emerald">{activeStudy.after.employees} {locale === "en" ? "staff" : "موظف"}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-muted-white">{locale === "en" ? "Response Time" : "وقت الاستجابة"}</span>
                    <span className="font-jetbrains-mono text-soft-emerald">{activeStudy.after.responseTime}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-muted-white">{locale === "en" ? "Monthly Cost" : "التكلفة الشهرية"}</span>
                    <span className="font-jetbrains-mono text-soft-emerald">{formatSAR(activeStudy.after.cost)}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-muted-white">{locale === "en" ? "Efficiency" : "الكفاءة"}</span>
                    <span className="font-jetbrains-mono text-soft-emerald">{activeStudy.after.efficiency}</span>
                  </div>
                </div>
              </div>
            </div>

            {/* Story Toggle */}
            <div className="text-center">
              <button
                onClick={() => setShowStory(!showStory)}
                className="inline-flex items-center gap-2 px-6 py-3 rounded-full bg-white/5 border border-white/10 text-warm-white hover:bg-white/10 transition-all"
              >
                <span>
                  {showStory
                    ? (locale === "en" ? "Hide Transformation Story" : "إخفاء قصة التحويل")
                    : (locale === "en" ? "Read Transformation Story" : "اقرأ قصة التحويل")
                  }
                </span>
                <ChevronRight className={`w-4 h-4 transition-transform ${showStory ? 'rotate-90' : ''}`} />
              </button>
            </div>

            {/* Story Content */}
            <AnimatePresence>
              {showStory && (
                <motion.div
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: "auto" }}
                  exit={{ opacity: 0, height: 0 }}
                  className="bg-obsidian/30 border border-white/10 rounded-xl p-8"
                >
                  <div className="space-y-4">
                    {activeStudy.story.map((paragraph, index) => (
                      <motion.p
                        key={index}
                        initial={{ opacity: 0, x: isRTL ? 20 : -20 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ duration: 0.5, delay: index * 0.1 }}
                        className="text-muted-white leading-relaxed"
                      >
                        {paragraph}
                      </motion.p>
                    ))}
                  </div>
                </motion.div>
              )}
            </AnimatePresence>

            {/* Results Grid */}
            <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4">
              {activeStudy.results.map((result, index) => (
                <motion.div
                  key={index}
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ duration: 0.5, delay: 0.2 + index * 0.1 }}
                  className="bg-gradient-to-br from-soft-emerald/10 to-teal-500/10 border border-soft-emerald/20 rounded-xl p-6 text-center"
                >
                  <div className="text-sm text-muted-white mb-2">
                    {result.metric}
                  </div>
                  <div className="text-2xl font-space-grotesk font-bold text-soft-emerald mb-1">
                    {result.value}
                  </div>
                  <div className="text-xs text-soft-emerald">
                    {result.improvement}
                  </div>
                </motion.div>
              ))}
            </div>
          </motion.div>
        </AnimatePresence>

        {/* CTA */}
        <div className="text-center mt-16">
          <button className="px-8 py-4 bg-gradient-to-r from-electric-cyan to-soft-emerald text-void-black font-semibold rounded-xl hover:opacity-90 transition-opacity inline-flex items-center gap-2">
            <span>
              {locale === "en" ? "Start Your Transformation" : "ابدأ تحولك"}
            </span>
            <ArrowRight className="w-5 h-5" />
          </button>
        </div>
      </div>
    </section>
  );
}
