"use client";

import { useEffect, useState, useRef, useCallback } from "react";
import Image from "next/image";

interface ExperienceItem {
  id: string;
  label: string;
  headline: string;
  description: string;
  stat: string;
  statCaption: string;
  image: string;
  imageAlt: string;
}

interface ExperienceShowcaseProps {
  items: ExperienceItem[];
  isRtl: boolean;
}

// Get emoji icon for each sector
function getSectorIcon(sectorId: string): string {
  const icons: { [key: string]: string } = {
    "health-care": "🏥",
    "beauty-wellness": "💆‍♀️",
    "food-leisure": "🍽️",
    "retail-services": "🛍️",
    "property-facilities": "🏢",
    "mobility-industry": "🚛",
  };
  return icons[sectorId] || "📱";
}

export default function ExperienceShowcase({
  items,
  isRtl,
}: ExperienceShowcaseProps) {
  const [activeIndex, setActiveIndex] = useState(0);
  const [isAutoPlaying, setIsAutoPlaying] = useState(true);
  const [progress, setProgress] = useState(0);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const progressRef = useRef<NodeJS.Timeout | null>(null);

  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (e.key === " " || e.key === "Spacebar") {
        e.preventDefault();
        setIsAutoPlaying(!isAutoPlaying);
      } else if (e.key === "ArrowLeft") {
        e.preventDefault();
        const direction = isRtl ? 1 : -1;
        setActiveIndex((prev) => {
          const newIndex = prev + direction;
          return newIndex < 0 ? items.length - 1 : newIndex % items.length;
        });
        setIsAutoPlaying(false);
      } else if (e.key === "ArrowRight") {
        e.preventDefault();
        const direction = isRtl ? -1 : 1;
        setActiveIndex((prev) => {
          const newIndex = prev + direction;
          return newIndex < 0 ? items.length - 1 : newIndex % items.length;
        });
        setIsAutoPlaying(false);
      }
    },
    [isAutoPlaying, isRtl, items.length],
  );

  useEffect(() => {
    if (isAutoPlaying) {
      // Auto-advance every 4 seconds
      intervalRef.current = setInterval(() => {
        setActiveIndex((prev) => (prev + 1) % items.length);
        setProgress(0);
      }, 4000);

      // Update progress bar
      progressRef.current = setInterval(() => {
        setProgress((prev) => Math.min(prev + 2.5, 100));
      }, 100);
    }

    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
      if (progressRef.current) clearInterval(progressRef.current);
    };
  }, [isAutoPlaying, items.length, activeIndex]);

  useEffect(() => {
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [handleKeyDown]);

  const activeItem = items[activeIndex];

  return (
    <div className="space-y-8">
      {/* Industry Tabs with Progress */}
      <div className="space-y-4">
        <div className="flex flex-wrap gap-2">
          {items.map((item, index) => (
            <button
              key={item.id}
              onClick={() => {
                setActiveIndex(index);
                setIsAutoPlaying(false);
                setProgress(0);
              }}
              className={`relative rounded-full px-6 py-3 text-sm font-semibold transition-all duration-300 ${
                index === activeIndex
                  ? "bg-gradient-to-r from-brand-green to-emerald-600 text-white shadow-xl scale-105"
                  : "bg-white/80 backdrop-blur text-gray-700 hover:bg-gray-100 dark:bg-slate-800/80 dark:text-gray-300 dark:hover:bg-slate-700 border border-gray-200 dark:border-gray-700"
              }`}
            >
              {item.label}
              {index === activeIndex && isAutoPlaying && (
                <div
                  className="absolute bottom-0 left-0 h-1 bg-white/50 rounded-full transition-all duration-100"
                  style={{ width: `${progress}%` }}
                />
              )}
            </button>
          ))}
        </div>
        {/* Auto-play indicator */}
        <div className="flex items-center justify-center gap-2 text-sm text-gray-500 dark:text-gray-400">
          <span
            className={`inline-block w-2 h-2 rounded-full ${isAutoPlaying ? "bg-brand-green animate-pulse" : "bg-gray-400"}`}
          />
          <span>
            {isAutoPlaying
              ? isRtl
                ? "التشغيل التلقائي نشط"
                : "Auto-play active"
              : isRtl
                ? "التشغيل التلقائي متوقف"
                : "Auto-play paused"}
          </span>
        </div>
      </div>

      {/* Active Showcase */}
      <div className="grid gap-8 lg:grid-cols-2">
        <div className="space-y-6">
          <div className="space-y-4">
            <h3 className="text-2xl font-bold text-gray-900 dark:text-white md:text-3xl">
              {activeItem.headline}
            </h3>
            <p className="text-lg text-gray-600 dark:text-gray-300">
              {activeItem.description}
            </p>
          </div>

          <div className="rounded-2xl bg-brand-green/10 p-6">
            <div className="flex items-baseline gap-3">
              <span className="text-3xl font-bold text-brand-green md:text-4xl">
                {activeItem.stat}
              </span>
              <span className="text-base text-gray-700 dark:text-gray-300">
                {activeItem.statCaption}
              </span>
            </div>
          </div>
        </div>

        <div className="relative">
          <div className="relative aspect-[4/3] overflow-hidden rounded-3xl bg-gradient-to-br from-brand-green/5 via-emerald-50/30 to-teal-50/20 dark:from-brand-green/10 dark:via-emerald-900/20 dark:to-teal-900/10 shadow-xl">
            {activeItem.image.endsWith(".svg") ||
            activeItem.image.endsWith(".png") ||
            activeItem.image.endsWith(".jpg") ? (
              <Image
                src={activeItem.image}
                alt={activeItem.imageAlt}
                width={640}
                height={480}
                className="h-full w-full object-cover"
                priority
                onError={(e) => {
                  // Fallback to icon if image fails to load
                  const target = e.target as HTMLImageElement;
                  target.style.display = "none";
                  const parent = target.parentElement;
                  if (parent) {
                    parent.innerHTML = `<div class="flex h-full items-center justify-center">
                      <div class="text-8xl">${getSectorIcon(activeItem.id)}</div>
                    </div>`;
                  }
                }}
              />
            ) : (
              <div className="flex h-full items-center justify-center">
                <div className="text-8xl text-brand-green/60 dark:text-brand-green/40">
                  {getSectorIcon(activeItem.id)}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Controls */}
      <div className="flex items-center justify-center gap-3">
        {items.map((_, index) => (
          <button
            key={index}
            onClick={() => {
              setActiveIndex(index);
              setIsAutoPlaying(false);
            }}
            className={`h-2 rounded-full transition-all ${
              index === activeIndex
                ? "w-8 bg-brand-green"
                : "w-2 bg-gray-300 dark:bg-gray-600 hover:bg-gray-400 dark:hover:bg-gray-500"
            }`}
            aria-label={`Go to ${items[index].label}`}
          />
        ))}
      </div>

      {/* Keyboard Hint */}
      <p className="text-center text-sm text-gray-500 dark:text-gray-400">
        {isRtl
          ? "استخدم الأسهم للتنقل • مسافة للإيقاف/التشغيل"
          : "Use arrows to navigate • Space to pause/play"}
      </p>
    </div>
  );
}
