"use client";

import React, { useState, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Check, ChevronRight, ChevronLeft, RotateCcw } from "lucide-react";
import type { Lang } from "@/lib/config";

export interface WorkflowStep {
  id: string;
  titleEn: string;
  titleAr: string;
  descriptionEn: string;
  descriptionAr: string;
  icon: React.ReactNode;
  mockup?: React.ReactNode;
  highlights?: {
    en: string[];
    ar: string[];
  };
}

interface WorkflowShowcaseProps {
  lang: Lang;
  steps: WorkflowStep[];
  title: {
    en: string;
    ar: string;
  };
  subtitle?: {
    en: string;
    ar: string;
  };
  accentColor?: string;
  autoAdvance?: boolean;
  autoAdvanceInterval?: number;
}

/**
 * WorkflowShowcase Component
 *
 * Interactive step-by-step workflow visualization with animations.
 * Supports RTL for Arabic, dark mode, and mobile-responsive design.
 *
 * @example
 * <WorkflowShowcase
 *   lang="en"
 *   steps={depositFlowSteps}
 *   title={{ en: "Deposit Flow", ar: "مسار الإيداع" }}
 * />
 */
export function WorkflowShowcase({
  lang,
  steps,
  title,
  subtitle,
  accentColor = "brand-green",
  autoAdvance = false,
  autoAdvanceInterval = 4000,
}: WorkflowShowcaseProps) {
  const [currentStep, setCurrentStep] = useState(0);
  const [completedSteps, setCompletedSteps] = useState<Set<number>>(new Set());
  const isRTL = lang === "ar";
  const t = {
    en: {
      step: "Step",
      of: "of",
      next: "Next",
      previous: "Previous",
      restart: "Restart",
      completed: "Completed",
    },
    ar: {
      step: "الخطوة",
      of: "من",
      next: "التالي",
      previous: "السابق",
      restart: "إعادة",
      completed: "مكتمل",
    },
  }[lang];

  // Auto-advance effect
  React.useEffect(() => {
    if (!autoAdvance) return;
    const timer = setInterval(() => {
      setCurrentStep((prev) => {
        const next = prev + 1;
        if (next >= steps.length) {
          return 0;
        }
        setCompletedSteps((completed) => new Set([...completed, prev]));
        return next;
      });
    }, autoAdvanceInterval);
    return () => clearInterval(timer);
  }, [autoAdvance, autoAdvanceInterval, steps.length]);

  const goToStep = useCallback(
    (stepIndex: number) => {
      if (stepIndex < currentStep) {
        setCurrentStep(stepIndex);
      } else if (stepIndex === currentStep + 1) {
        setCompletedSteps((prev) => new Set([...prev, currentStep]));
        setCurrentStep(stepIndex);
      }
    },
    [currentStep],
  );

  const goNext = useCallback(() => {
    if (currentStep < steps.length - 1) {
      setCompletedSteps((prev) => new Set([...prev, currentStep]));
      setCurrentStep(currentStep + 1);
    }
  }, [currentStep, steps.length]);

  const goPrevious = useCallback(() => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  }, [currentStep]);

  const restart = useCallback(() => {
    setCurrentStep(0);
    setCompletedSteps(new Set());
  }, []);

  const currentStepData = steps[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"
    >
      {/* Header */}
      <div className="p-6 lg:p-8 border-b border-stone-200 dark:border-slate-700 bg-gradient-to-r from-stone-50 to-white dark:from-slate-800 dark:to-slate-900">
        <h3 className="text-2xl lg:text-3xl font-bold text-stone-900 dark:text-white mb-2">
          {title[lang]}
        </h3>
        {subtitle && (
          <p className="text-stone-600 dark:text-stone-400">{subtitle[lang]}</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 gap-2 min-w-max">
          {steps.map((step, index) => {
            const isCompleted = completedSteps.has(index);
            const isCurrent = index === currentStep;
            const isClickable = index <= currentStep + 1;

            return (
              <React.Fragment key={step.id}>
                <button
                  onClick={() => isClickable && goToStep(index)}
                  disabled={!isClickable}
                  className={`
                    flex items-center gap-2 px-4 py-2 rounded-full transition-all duration-300
                    ${
                      isCurrent
                        ? `bg-${accentColor} text-white shadow-lg scale-105`
                        : isCompleted
                          ? `bg-${accentColor}/20 text-${accentColor} dark:bg-${accentColor}/30`
                          : "bg-stone-200 dark:bg-slate-700 text-stone-500 dark:text-stone-400"
                    }
                    ${isClickable ? "cursor-pointer hover:scale-105" : "cursor-not-allowed opacity-60"}
                  `}
                >
                  {isCompleted && !isCurrent ? (
                    <Check className="w-4 h-4" />
                  ) : (
                    <span className="w-5 h-5 flex items-center justify-center text-xs font-bold rounded-full bg-current/20">
                      {index + 1}
                    </span>
                  )}
                  <span className="text-sm font-medium whitespace-nowrap hidden sm:inline">
                    {lang === "ar" ? step.titleAr : step.titleEn}
                  </span>
                </button>
                {index < steps.length - 1 && (
                  <div
                    className={`w-8 h-0.5 transition-colors duration-300 ${
                      completedSteps.has(index)
                        ? `bg-${accentColor}`
                        : "bg-stone-300 dark:bg-slate-600"
                    }`}
                  />
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* Step Content */}
      <div className="p-6 lg:p-8">
        <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 }}
            className="grid lg:grid-cols-2 gap-8 items-center"
          >
            {/* Step Info */}
            <div className={`space-y-6 ${isRTL ? "lg:order-2" : "lg:order-1"}`}>
              {/* Step Number Badge */}
              <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-stone-100 dark:bg-slate-800 text-stone-600 dark:text-stone-400 text-sm">
                <span className="font-medium">{t.step}</span>
                <span className={`font-bold text-${accentColor}`}>
                  {currentStep + 1}
                </span>
                <span>{t.of}</span>
                <span>{steps.length}</span>
              </div>

              {/* Icon and Title */}
              <div className="flex items-start gap-4">
                <div
                  className={`flex-shrink-0 w-14 h-14 rounded-xl bg-${accentColor}/10 dark:bg-${accentColor}/20 flex items-center justify-center`}
                >
                  {currentStepData.icon}
                </div>
                <div>
                  <h4 className="text-xl lg:text-2xl font-bold text-stone-900 dark:text-white">
                    {lang === "ar"
                      ? currentStepData.titleAr
                      : currentStepData.titleEn}
                  </h4>
                  <p className="mt-2 text-stone-600 dark:text-stone-400 leading-relaxed">
                    {lang === "ar"
                      ? currentStepData.descriptionAr
                      : currentStepData.descriptionEn}
                  </p>
                </div>
              </div>

              {/* Highlights */}
              {currentStepData.highlights && (
                <div className="flex flex-wrap gap-2 mt-4">
                  {(lang === "ar"
                    ? currentStepData.highlights.ar
                    : currentStepData.highlights.en
                  ).map((highlight, idx) => (
                    <span
                      key={idx}
                      className={`px-3 py-1 text-sm font-medium bg-${accentColor}/10 dark:bg-${accentColor}/20 text-${accentColor} rounded-full`}
                    >
                      {highlight}
                    </span>
                  ))}
                </div>
              )}
            </div>

            {/* Mockup Area */}
            <div className={`${isRTL ? "lg:order-1" : "lg:order-2"}`}>
              {currentStepData.mockup && (
                <motion.div
                  initial={{ opacity: 0, scale: 0.95 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ delay: 0.1, duration: 0.4 }}
                  className="relative rounded-xl overflow-hidden shadow-2xl border border-stone-200 dark:border-slate-700"
                >
                  {currentStepData.mockup}
                </motion.div>
              )}
            </div>
          </motion.div>
        </AnimatePresence>
      </div>

      {/* Navigation Footer */}
      <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 ? (
            <ChevronRight className="w-5 h-5" />
          ) : (
            <ChevronLeft className="w-5 h-5" />
          )}
          <span className="font-medium">{t.previous}</span>
        </button>

        {currentStep === steps.length - 1 ? (
          <button
            onClick={restart}
            className={`flex items-center gap-2 px-6 py-2 rounded-lg bg-${accentColor} hover:bg-${accentColor}Hover 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-${accentColor} hover:bg-${accentColor}Hover text-white font-medium transition-all`}
          >
            <span>{t.next}</span>
            {isRTL ? (
              <ChevronLeft className="w-5 h-5" />
            ) : (
              <ChevronRight className="w-5 h-5" />
            )}
          </button>
        )}
      </div>
    </div>
  );
}

export default WorkflowShowcase;
