"use client";

import React, { useState, useMemo } from "react";
import ArrowButton from "../ui/ArrowButton";
import { withCDN } from "@/src/lib/utils";
import type { WorkshopSection } from "@/src/lib/services/workshopService";
import { scrollToId } from "@/src/lib/utils/scrollToId";

interface WorkshopTabProps {
  whyWorkshopData?: WorkshopSection;
}

const STATIC_IMAGES = [
  "/Workshop/pct%20(6).png",
  "/discover/discover-6.png",
  "/Workshop/main%20pct%20(selected)%20(1).png",
  "/Workshop/main%20pct%20(selected)%20(2).png",
  "/Workshop/main%20pct%20(selected)%20(3).png",
];

export default function ClientDiscoverSlider({ whyWorkshopData }: WorkshopTabProps) {
  // Parse sliders from API
  const parsedSliders = useMemo(() => {
    try {
      if (whyWorkshopData?.sliders) {
        const parsed = typeof whyWorkshopData.sliders === "string"
          ? JSON.parse(whyWorkshopData.sliders)
          : whyWorkshopData.sliders;
        return Array.isArray(parsed) ? parsed : [];
      }
      return [];
    } catch (error) {
      console.error("[WorkshopTab] Failed to parse sliders:", error);
      return [];
    }
  }, [whyWorkshopData?.sliders]);

  // Merge API data with static images
  const tabs = useMemo(() => {
    const itemCount = Math.max(parsedSliders.length, STATIC_IMAGES.length);
    return Array.from({ length: itemCount }).map((_, index) => {
      const apiSlider = parsedSliders[index] || {};
      const fallbackImage = STATIC_IMAGES[index % STATIC_IMAGES.length];
      return {
        tabTitle: apiSlider.sliderHeading || `Workshop ${index + 1}`,
        contentTitle: apiSlider.title || `Workshop Experience ${index + 1}`,
        description: apiSlider.description || "Explore our workshops and discover new possibilities.",
        mainImage: apiSlider.image || fallbackImage,
      };
    });
  }, [parsedSliders]);

  const [activeTab, setActiveTab] = useState(0);
  const [touchStart, setTouchStart] = useState<number | null>(null);
  const [touchEnd, setTouchEnd] = useState<number | null>(null);

  const minSwipeDistance = 60;
  const currentTab = tabs[activeTab];

  const tabContainerRef = React.useRef<HTMLDivElement>(null);
  const tabRefs = React.useRef<(HTMLButtonElement | null)[]>([]);

  const scrollToTab = (index: number) => {
    const container = tabContainerRef.current;
    const tab = tabRefs.current[index];

    if (!container || !tab) return;

    // Mobile only
    if (window.innerWidth < 768) {
      const containerRect = container.getBoundingClientRect();
      const tabRect = tab.getBoundingClientRect();

      const offset =
        tabRect.left -
        containerRect.left -
        container.clientWidth / 2 +
        tab.clientWidth / 2;

      container.scrollBy({
        left: offset,
        behavior: "smooth",
      });
    }
  };

  const handlePrev = () => {
    setActiveTab((prev) => {
      const next = prev === 0 ? tabs.length - 1 : prev - 1;
      scrollToTab(next);
      return next;
    });
  };

  const handleNext = () => {
    setActiveTab((prev) => {
      const next = prev === tabs.length - 1 ? 0 : prev + 1;
      scrollToTab(next);
      return next;
    });
  };

  const onTouchStart = (e: React.TouchEvent) => {
    setTouchStart(e.touches[0].clientX);
    setTouchEnd(null);
  };

  const onTouchMove = (e: React.TouchEvent) => {
    setTouchEnd(e.touches[0].clientX);
  };

  const onTouchEnd = () => {
    if (touchStart === null || touchEnd === null) return;

    const distance = touchStart - touchEnd;
    if (Math.abs(distance) < minSwipeDistance) return;

    distance > 0 ? handleNext() : handlePrev();
  };

  return (
    <div className="max-w-[1300px] mx-auto w-full px-4 sm:px-0 py-16 max-[767px]:px-0 workshop-tabs-cols">
      <h2 className="text-[30px] xl:text-[50px] font-bold text-[#0097DC] mb-6 leading-tight uppercase">
        {whyWorkshopData?.mainHeading || "Why Workshops with YE"}
      </h2>

      {/* Tabs */}
      <div
        ref={tabContainerRef}
        className="flex justify-between items-start gap-2 mb-6 max-[767px]:overflow-x-auto no-scrollbar max-[767px]:scroll-smooth tab-wrap"
      >
        {tabs.map((tab, index) => (
          <button
            key={index}
            ref={(el) => {
              tabRefs.current[index] = el;
            }}
            onClick={() => {
              setActiveTab(index);
              scrollToTab(index);
            }}
            className={`text-[12px] md:text-[13px] lg:text-[15px] xl:lg:text-[16px] tab-btns cursor-pointer transition
              text-center border border-[#0097DC] rounded-[7px] px-[10px] md:px-[6px] lg:px-[10px] py-[10px] bg-[#fff]
              ${activeTab === index
                ? "text-[#0097DC] border-[#0097DC]"
                : "text-gray-500 border-transparent "
              }`}
          >
            {tab.tabTitle}
          </button>
        ))}
      </div>

      {/* Content */}
      <div
        className="flex flex-col md:flex-row gap-6 justify-between items-center md:touch-pan-x max-[767px]:select-none sm:flex-row max-[767px]:!flex-col-reverse"
        onTouchStart={onTouchStart}
        onTouchMove={onTouchMove}
        onTouchEnd={onTouchEnd}
      >
        {/* Left */}
        <div className="md:w-[45%] lg:w-[550px]">
          <h2 className="text-[20px] xl:text-[30px] font-light text-[#0097DC] mb-2 leading-tight uppercase">
            {currentTab.contentTitle}
          </h2>

          <p className="text-[#58585A] text-[18px] md:text-[16px] xl:text-[22px] mb-4 font-light">
            {currentTab.description}
          </p>

          <button
 className="flex items-center gap-3 bg-[#0097DC] text-white px-6 py-3 rounded-full hover:bg-[#0097DC] hover:shadow-[10px_14px_14px_#0000000D] cursor-pointer active:bg-[#0084C1] text-[16px] xl:text-h2-tab mt-8 uppercase transition"            onClick={() => {
              scrollToId("allWorkshop");
            }}
          >
            <img
              src={withCDN("/gear.png")}
              alt="Gear"
              className="w-6 h-6"
              draggable={false}
            />
            Discover workshops
          </button>
        </div>

        {/* Right */}
        <div className="md:w-[55%] lg:w-2/3 w-[421px] xl:w-[700px] max-[767px]:w-[70%] max-[767px]:h-[300px] max-[600px]:h-[170px]">
          <div className="rounded-xl overflow-hidden max-[767px]:pointer-events-none">
            <img
              src={currentTab.mainImage.startsWith('http') ? currentTab.mainImage : withCDN(currentTab.mainImage)}
              alt="Workshop"
              className="w-full h-[170px] max-[767px]:h-[300px] max-[600px]:h-[170px] sm:h-[270px] md:h-[270px] xl:h-[430px] rounded-[20px] sm:rounded-[30px] object-cover transition-all duration-300"
              draggable={false}
            />
          </div>
        </div>
      </div>

      {/* Mobile arrows */}
      <div className="flex justify-between mt-6 md:hidden absolute w-[90%] top-[45%] left-[5%] tab-arrow-mob">
        <ArrowButton direction="left" onClick={handlePrev} />
        <ArrowButton direction="right" onClick={handleNext} />
      </div>
    </div>
  );
}
