"use client";

import React, { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Calendar,
  CreditCard,
  CheckCircle2,
  Bell,
  Smartphone,
  ArrowRight,
  ArrowLeft,
  RotateCcw,
  Wallet,
  ShieldCheck,
} from "lucide-react";
import type { Lang } from "@/lib/config";

interface DepositFlowDemoProps {
  lang: Lang;
  autoPlay?: boolean;
  autoPlayInterval?: number;
}

const translations = {
  en: {
    title: "How Deposits Work",
    subtitle: "Reduce no-shows by collecting deposits upfront via WhatsApp",
    step: "Step",
    of: "of",
    next: "Next",
    previous: "Previous",
    restart: "Try Again",
    steps: [
      {
        title: "Customer Books Appointment",
        description:
          "Customer requests an appointment through WhatsApp. AI confirms available slots instantly.",
        highlights: [
          "24/7 availability",
          "Instant response",
          "Language detection",
        ],
      },
      {
        title: "Deposit Request Sent",
        description:
          "System automatically sends a secure payment link via WhatsApp with deposit amount.",
        highlights: ["Customizable amount", "Secure link", "Auto-generated"],
      },
      {
        title: "Customer Pays Deposit",
        description:
          "Customer pays using their preferred method: Apple Pay, Mada, Visa, or bank transfer.",
        highlights: ["Apple Pay", "Mada", "All major cards"],
      },
      {
        title: "Confirmation & Reminder",
        description:
          "Both customer and clinic receive instant confirmation. Automated reminders follow.",
        highlights: ["Instant receipt", "Smart reminders", "Calendar sync"],
      },
    ],
    mockup: {
      bookingTitle: "New Appointment Request",
      customerName: "Sarah Ahmed",
      customerMessage: "Hi, I would like to book a consultation for tomorrow",
      aiResponse:
        "Hello Sarah! I found available slots for tomorrow. A deposit of SAR 100 is required to confirm.",
      depositTitle: "Deposit Required",
      depositAmount: "SAR 100",
      depositDesc: "To secure your appointment",
      payNow: "Pay Now",
      paymentTitle: "Choose Payment Method",
      processing: "Processing...",
      confirmedTitle: "Appointment Confirmed!",
      confirmedDesc: "Your appointment is booked",
      depositPaid: "Deposit Paid",
      reminderSet: "Reminder Set",
      appointmentDate: "Tomorrow, 10:00 AM",
    },
  },
  ar: {
    title: "كيف تعمل الودائع",
    subtitle: "قلل حالات عدم الحضور من خلال تحصيل الودائع مسبقاً عبر واتساب",
    step: "الخطوة",
    of: "من",
    next: "التالي",
    previous: "السابق",
    restart: "إعادة المحاولة",
    steps: [
      {
        title: "العميل يحجز موعد",
        description:
          "يطلب العميل موعداً عبر واتساب. الذكاء الاصطناعي يؤكد المواعيد المتاحة فوراً.",
        highlights: ["متاح 24/7", "رد فوري", "كشف اللغة"],
      },
      {
        title: "إرسال طلب الإيداع",
        description:
          "يرسل النظام تلقائياً رابط دفع آمن عبر واتساب مع مبلغ الإيداع.",
        highlights: ["مبلغ قابل للتخصيص", "رابط آمن", "توليد تلقائي"],
      },
      {
        title: "العميل يدفع الإيداع",
        description:
          "يدفع العميل باستخدام طريقته المفضلة: آبل باي، مدى، فيزا، أو تحويل بنكي.",
        highlights: ["آبل باي", "مدى", "جميع البطاقات"],
      },
      {
        title: "التأكيد والتذكير",
        description:
          "يتلقى كل من العميل والعيادة تأكيداً فورياً. تتبع التذكيرات الآلية.",
        highlights: ["إيصال فوري", "تذكيرات ذكية", "مزامنة التقويم"],
      },
    ],
    mockup: {
      bookingTitle: "طلب موعد جديد",
      customerName: "سارة أحمد",
      customerMessage: "مرحباً، أريد حجز استشارة غداً",
      aiResponse:
        "أهلاً سارة! وجدت مواعيد متاحة غداً. يلزم إيداع 100 ريال لتأكيد الموعد.",
      depositTitle: "مطلوب إيداع",
      depositAmount: "100 ريال",
      depositDesc: "لتأمين موعدك",
      payNow: "ادفع الآن",
      paymentTitle: "اختر طريقة الدفع",
      processing: "جاري المعالجة...",
      confirmedTitle: "تم تأكيد الموعد!",
      confirmedDesc: "تم حجز موعدك",
      depositPaid: "تم دفع الإيداع",
      reminderSet: "تم ضبط التذكير",
      appointmentDate: "غداً، 10:00 صباحاً",
    },
  },
};

/**
 * DepositFlowDemo Component
 *
 * Interactive demonstration of the deposit collection workflow.
 * Shows the full flow from booking request to payment confirmation.
 *
 * @example
 * <DepositFlowDemo lang="en" autoPlay={true} />
 */
export function DepositFlowDemo({
  lang,
  autoPlay = false,
  autoPlayInterval = 5000,
}: DepositFlowDemoProps) {
  const [currentStep, setCurrentStep] = useState(0);
  const [isAnimating, setIsAnimating] = useState(false);
  const isRTL = lang === "ar";
  const t = translations[lang];

  // Auto-play effect
  useEffect(() => {
    if (!autoPlay) return;
    const timer = setInterval(() => {
      setCurrentStep((prev) => (prev + 1) % 4);
    }, autoPlayInterval);
    return () => clearInterval(timer);
  }, [autoPlay, autoPlayInterval]);

  const goToStep = (step: number) => {
    if (isAnimating) return;
    setIsAnimating(true);
    setCurrentStep(step);
    setTimeout(() => setIsAnimating(false), 500);
  };

  const goNext = () => {
    if (currentStep < 3) goToStep(currentStep + 1);
  };

  const goPrevious = () => {
    if (currentStep > 0) goToStep(currentStep - 1);
  };

  const restart = () => {
    goToStep(0);
  };

  // Step icons
  const stepIcons = [
    <Calendar key="calendar" className="w-6 h-6 text-brand-green" />,
    <Bell key="bell" className="w-6 h-6 text-brand-green" />,
    <CreditCard key="credit" className="w-6 h-6 text-brand-green" />,
    <CheckCircle2 key="check" className="w-6 h-6 text-brand-green" />,
  ];

  // Mockup components for each step
  const renderMockup = () => {
    const mockupContent = [
      // Step 1: Booking Request
      <div
        key="booking"
        className="bg-gray-100 dark:bg-slate-800 rounded-2xl p-4 h-full"
      >
        <div className="bg-green-600 rounded-t-xl p-3 -mx-4 -mt-4 mb-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center">
              <Smartphone className="w-5 h-5 text-white" />
            </div>
            <div className="text-white">
              <p className="font-semibold text-sm">{t.mockup.bookingTitle}</p>
              <p className="text-xs opacity-80">WhatsApp Business</p>
            </div>
          </div>
        </div>
        <div className="space-y-3">
          {/* Customer message */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className={`flex ${isRTL ? "justify-end" : "justify-start"}`}
          >
            <div className="bg-white dark:bg-slate-700 rounded-2xl rounded-bl-sm p-3 max-w-[80%] shadow-sm">
              <p className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
                {t.mockup.customerName}
              </p>
              <p className="text-sm text-gray-800 dark:text-gray-200">
                {t.mockup.customerMessage}
              </p>
            </div>
          </motion.div>
          {/* AI response */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.6 }}
            className={`flex ${isRTL ? "justify-start" : "justify-end"}`}
          >
            <div className="bg-green-100 dark:bg-green-900/30 rounded-2xl rounded-br-sm p-3 max-w-[80%] shadow-sm">
              <div className="flex items-center gap-2 mb-1">
                <div className="w-4 h-4 bg-brand-green rounded-full flex items-center justify-center">
                  <span className="text-white text-[8px]">AI</span>
                </div>
                <span className="text-xs font-medium text-brand-green">
                  Mawidi AI
                </span>
              </div>
              <p className="text-sm text-gray-800 dark:text-gray-200">
                {t.mockup.aiResponse}
              </p>
            </div>
          </motion.div>
        </div>
      </div>,

      // Step 2: Deposit Request
      <div
        key="deposit"
        className="bg-gray-100 dark:bg-slate-800 rounded-2xl p-4 h-full"
      >
        <div className="bg-green-600 rounded-t-xl p-3 -mx-4 -mt-4 mb-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center">
              <Wallet className="w-5 h-5 text-white" />
            </div>
            <div className="text-white">
              <p className="font-semibold text-sm">{t.mockup.depositTitle}</p>
              <p className="text-xs opacity-80">{t.mockup.depositDesc}</p>
            </div>
          </div>
        </div>
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ delay: 0.3 }}
          className="bg-white dark:bg-slate-700 rounded-xl p-6 text-center shadow-lg"
        >
          <div className="w-16 h-16 bg-brand-green/10 rounded-full flex items-center justify-center mx-auto mb-4">
            <CreditCard className="w-8 h-8 text-brand-green" />
          </div>
          <p className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
            {t.mockup.depositAmount}
          </p>
          <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
            {t.mockup.depositDesc}
          </p>
          <motion.button
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
            className="w-full py-3 bg-brand-green hover:bg-brand-greenHover text-white font-semibold rounded-xl transition-colors"
          >
            {t.mockup.payNow}
          </motion.button>
          <div className="flex items-center justify-center gap-2 mt-4">
            <ShieldCheck className="w-4 h-4 text-gray-400" />
            <span className="text-xs text-gray-400">Secured by Stripe</span>
          </div>
        </motion.div>
      </div>,

      // Step 3: Payment Selection
      <div
        key="payment"
        className="bg-gray-100 dark:bg-slate-800 rounded-2xl p-4 h-full"
      >
        <div className="bg-gray-900 rounded-t-xl p-3 -mx-4 -mt-4 mb-4">
          <div className="flex items-center justify-between">
            <p className="text-white font-semibold text-sm">
              {t.mockup.paymentTitle}
            </p>
            <p className="text-white/60 text-xs">{t.mockup.depositAmount}</p>
          </div>
        </div>
        <div className="space-y-3">
          {/* Apple Pay */}
          <motion.button
            initial={{ opacity: 0, x: isRTL ? 20 : -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.2 }}
            whileHover={{ scale: 1.02 }}
            className="w-full flex items-center gap-4 p-4 bg-black rounded-xl text-white"
          >
            <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center">
              <span className="text-black font-bold text-lg"></span>
            </div>
            <span className="font-semibold">Apple Pay</span>
            <CheckCircle2
              className={`w-5 h-5 text-brand-green ${isRTL ? "mr-auto" : "ml-auto"}`}
            />
          </motion.button>
          {/* Mada */}
          <motion.button
            initial={{ opacity: 0, x: isRTL ? 20 : -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.3 }}
            whileHover={{ scale: 1.02 }}
            className="w-full flex items-center gap-4 p-4 bg-white dark:bg-slate-700 rounded-xl border border-gray-200 dark:border-slate-600"
          >
            <div className="w-10 h-10 bg-green-500 rounded-lg flex items-center justify-center">
              <span className="text-white font-bold text-sm">mada</span>
            </div>
            <span className="font-semibold text-gray-800 dark:text-white">
              Mada Card
            </span>
          </motion.button>
          {/* Visa/Mastercard */}
          <motion.button
            initial={{ opacity: 0, x: isRTL ? 20 : -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.4 }}
            whileHover={{ scale: 1.02 }}
            className="w-full flex items-center gap-4 p-4 bg-white dark:bg-slate-700 rounded-xl border border-gray-200 dark:border-slate-600"
          >
            <div className="w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center">
              <CreditCard className="w-5 h-5 text-white" />
            </div>
            <span className="font-semibold text-gray-800 dark:text-white">
              Credit / Debit Card
            </span>
          </motion.button>
        </div>
      </div>,

      // Step 4: Confirmation
      <div
        key="confirmed"
        className="bg-gray-100 dark:bg-slate-800 rounded-2xl p-4 h-full"
      >
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ type: "spring", stiffness: 200, damping: 20 }}
          className="bg-white dark:bg-slate-700 rounded-xl p-6 text-center shadow-lg"
        >
          <motion.div
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            transition={{ delay: 0.2, type: "spring", stiffness: 300 }}
            className="w-20 h-20 bg-brand-green rounded-full flex items-center justify-center mx-auto mb-4"
          >
            <CheckCircle2 className="w-10 h-10 text-white" />
          </motion.div>
          <h4 className="text-xl font-bold text-gray-900 dark:text-white mb-2">
            {t.mockup.confirmedTitle}
          </h4>
          <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
            {t.mockup.confirmedDesc}
          </p>
          <div className="space-y-3 text-left">
            <div className="flex items-center gap-3 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
              <CheckCircle2 className="w-5 h-5 text-brand-green" />
              <span className="text-sm font-medium text-gray-800 dark:text-gray-200">
                {t.mockup.depositPaid}: {t.mockup.depositAmount}
              </span>
            </div>
            <div className="flex items-center gap-3 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
              <Bell className="w-5 h-5 text-brand-green" />
              <span className="text-sm font-medium text-gray-800 dark:text-gray-200">
                {t.mockup.reminderSet}
              </span>
            </div>
            <div className="flex items-center gap-3 p-3 bg-brand-green/10 rounded-lg">
              <Calendar className="w-5 h-5 text-brand-green" />
              <span className="text-sm font-medium text-brand-green">
                {t.mockup.appointmentDate}
              </span>
            </div>
          </div>
        </motion.div>
      </div>,
    ];

    return mockupContent[currentStep];
  };

  return (
    <div
      dir={isRTL ? "rtl" : "ltr"}
      className="w-full bg-white dark:bg-slate-900 rounded-2xl border border-stone-200 dark:border-slate-700 overflow-hidden shadow-premium-lg"
    >
      {/* Header */}
      <div className="p-6 lg:p-8 border-b border-stone-200 dark:border-slate-700 bg-gradient-to-r from-brand-green/5 to-teal-500/5 dark:from-brand-green/10 dark:to-teal-500/10">
        <h3 className="text-2xl lg:text-3xl font-bold text-stone-900 dark:text-white mb-2">
          {t.title}
        </h3>
        <p className="text-stone-600 dark:text-stone-400">{t.subtitle}</p>
      </div>

      {/* Progress Steps */}
      <div className="px-6 lg:px-8 py-4 border-b border-stone-200 dark:border-slate-700 bg-stone-50 dark:bg-slate-800/50 overflow-x-auto">
        <div className="flex items-center justify-between min-w-max">
          {t.steps.map((step, index) => {
            const isCompleted = index < currentStep;
            const isCurrent = index === currentStep;

            return (
              <React.Fragment key={index}>
                <button
                  onClick={() => goToStep(index)}
                  className={`
                    flex flex-col items-center gap-2 px-3 py-2 rounded-xl transition-all duration-300
                    ${
                      isCurrent
                        ? "bg-brand-green/10 dark:bg-brand-green/20"
                        : "hover:bg-stone-100 dark:hover:bg-slate-700"
                    }
                  `}
                >
                  <div
                    className={`
                      w-12 h-12 rounded-xl flex items-center justify-center transition-all duration-300
                      ${
                        isCurrent
                          ? "bg-brand-green text-white shadow-lg scale-110"
                          : isCompleted
                            ? "bg-brand-green/20 text-brand-green"
                            : "bg-stone-200 dark:bg-slate-700 text-stone-500 dark:text-stone-400"
                      }
                    `}
                  >
                    {isCompleted ? (
                      <CheckCircle2 className="w-6 h-6" />
                    ) : (
                      stepIcons[index]
                    )}
                  </div>
                  <span
                    className={`
                      text-xs font-medium text-center max-w-[80px] leading-tight
                      ${
                        isCurrent
                          ? "text-brand-green"
                          : "text-stone-600 dark:text-stone-400"
                      }
                    `}
                  >
                    {step.title}
                  </span>
                </button>
                {index < t.steps.length - 1 && (
                  <div
                    className={`
                      flex-1 h-0.5 mx-2 transition-colors duration-300
                      ${
                        isCompleted
                          ? "bg-brand-green"
                          : "bg-stone-300 dark:bg-slate-600"
                      }
                    `}
                  />
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* Content */}
      <div className="p-6 lg:p-8">
        <div className="grid lg:grid-cols-2 gap-8 items-start">
          {/* Step Info */}
          <div className={`space-y-6 ${isRTL ? "lg:order-2" : "lg:order-1"}`}>
            <AnimatePresence mode="wait">
              <motion.div
                key={currentStep}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                transition={{ duration: 0.3 }}
              >
                {/* Step Badge */}
                <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-brand-green/10 text-brand-green text-sm font-medium mb-4">
                  {t.step} {currentStep + 1} {t.of} {t.steps.length}
                </div>

                {/* Title and Description */}
                <h4 className="text-xl lg:text-2xl font-bold text-stone-900 dark:text-white mb-3">
                  {t.steps[currentStep].title}
                </h4>
                <p className="text-stone-600 dark:text-stone-400 leading-relaxed mb-6">
                  {t.steps[currentStep].description}
                </p>

                {/* Highlights */}
                <div className="flex flex-wrap gap-2">
                  {t.steps[currentStep].highlights.map((highlight, idx) => (
                    <motion.span
                      key={idx}
                      initial={{ opacity: 0, scale: 0.8 }}
                      animate={{ opacity: 1, scale: 1 }}
                      transition={{ delay: 0.1 * idx }}
                      className="px-3 py-1 text-sm font-medium bg-stone-100 dark:bg-slate-800 text-stone-700 dark:text-stone-300 rounded-full"
                    >
                      {highlight}
                    </motion.span>
                  ))}
                </div>
              </motion.div>
            </AnimatePresence>
          </div>

          {/* Mockup */}
          <div
            className={`${isRTL ? "lg:order-1" : "lg:order-2"} min-h-[320px]`}
          >
            <AnimatePresence mode="wait">
              <motion.div
                key={currentStep}
                initial={{ opacity: 0, x: isRTL ? -20 : 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: isRTL ? 20 : -20 }}
                transition={{ duration: 0.3 }}
              >
                {renderMockup()}
              </motion.div>
            </AnimatePresence>
          </div>
        </div>
      </div>

      {/* Navigation */}
      <div className="px-6 lg:px-8 py-4 border-t border-stone-200 dark:border-slate-700 bg-stone-50 dark:bg-slate-800/50 flex items-center justify-between">
        <button
          onClick={goPrevious}
          disabled={currentStep === 0}
          className={`
            flex items-center gap-2 px-4 py-2 rounded-lg transition-all
            ${
              currentStep === 0
                ? "opacity-50 cursor-not-allowed"
                : "hover:bg-stone-200 dark:hover:bg-slate-700"
            }
            text-stone-700 dark:text-stone-300
          `}
        >
          {isRTL ? (
            <ArrowRight className="w-5 h-5" />
          ) : (
            <ArrowLeft className="w-5 h-5" />
          )}
          <span className="font-medium">{t.previous}</span>
        </button>

        {currentStep === 3 ? (
          <button
            onClick={restart}
            className="flex items-center gap-2 px-6 py-2 rounded-lg bg-brand-green hover:bg-brand-greenHover text-white font-medium transition-all"
          >
            <RotateCcw className="w-5 h-5" />
            <span>{t.restart}</span>
          </button>
        ) : (
          <button
            onClick={goNext}
            className="flex items-center gap-2 px-6 py-2 rounded-lg bg-brand-green hover:bg-brand-greenHover text-white font-medium transition-all"
          >
            <span>{t.next}</span>
            {isRTL ? (
              <ArrowLeft className="w-5 h-5" />
            ) : (
              <ArrowRight className="w-5 h-5" />
            )}
          </button>
        )}
      </div>
    </div>
  );
}

export default DepositFlowDemo;
