import { useAppDispatch } from "../../../hooks/useRedux";
import {
  startLoading,
  stopLoading,
} from "../../../features/loading/loadingSlice";
import { DataCacheKey, staleTime } from "../../../global/constants";
import { Banner } from "../../../services/content/types";
import { useQuery } from "@tanstack/react-query";
import React, { useState, useEffect, useCallback } from "react";
import { contentApi } from "../../../apis/contentApi";

const HomeBanner = () => {
  const [currentBanner, setCurrentBanner] = useState(0);
  const dispatch = useAppDispatch();

  const { data: loadBannerData = [] } = useQuery<Banner[]>({
    queryKey: [DataCacheKey.BANNERS],
    queryFn: async (): Promise<Banner[]> => {
      try {
        dispatch(startLoading({}));
        const res = await contentApi.LoadBanner({
          pageNumber: 0,
          pageSize: 10,
        });
        return res.data.banners as Banner[];
      } catch (error) {
        console.error(error);
        return []; // 🔴 bắt buộc
      } finally {
        dispatch(stopLoading());
      }
    },
    staleTime: staleTime,
  });

  const gradients = [
    "from-[#EE0434] via-[#cc002d] to-[#ff4d6d]",
    "from-[#ff4d6d] via-[#EE0434] to-[#80001a]",
    "from-[#EE0434] via-[#ff6b6b] to-[#c92a2a]",
  ];

  const nextBanner = useCallback(() => {
    setCurrentBanner((prev) => (prev + 1) % loadBannerData.length);
  }, [loadBannerData.length]);

  useEffect(() => {
    const timer = setInterval(nextBanner, 6000);
    return () => clearInterval(timer);
  }, [nextBanner]);

  return (
    <section className="px-4 py-4 md:py-6 relative">
      <div className="max-w-7xl mx-auto relative overflow-hidden rounded-[24px] md:rounded-[48px] min-h-[400px] md:min-h-[550px] shadow-2xl bg-slate-900">
        {loadBannerData.map((banner, idx) => (
          <div
            key={idx}
            className={`absolute inset-0 w-full h-full transition-all duration-[1000ms] ease-in-out flex items-center ${
              idx === currentBanner
                ? "opacity-100 z-20 scale-100"
                : "opacity-0 z-10 pointer-events-none scale-105"
            }`}
          >
            <div
              className={`absolute inset-0 bg-gradient-to-br ${
                gradients[idx % gradients.length]
              } opacity-90 transition-all`}
              style={{ backgroundImage: `url(${banner.imageUrl})` }}
            ></div>

            <div className="relative z-30 flex flex-col items-center justify-center p-6 md:p-24 w-full h-full text-center">
              <div
                className={`text-white space-y-6 md:space-y-8 transition-all duration-1000 delay-300 ${
                  idx === currentBanner
                    ? "translate-y-0 opacity-100"
                    : "translate-y-12 opacity-0"
                }`}
              >
                <div className="inline-block px-4 py-1.5 bg-white/20 backdrop-blur-xl rounded-full text-[10px] md:text-xs font-black uppercase tracking-[0.3em] border border-white/10">
                  {banner.title}
                </div>
                <h1 className="text-4xl md:text-4xl lg:text-5xl font-black leading-[1.1] tracking-tighter max-w-4xl">
                  {banner.title} <br />
                  <span className="text-white/60 drop-shadow-sm">
                    {banner.subtitle}
                  </span>
                </h1>
                <p className="text-sm md:text-xl text-white/80 font-medium max-w-2xl mx-auto leading-relaxed hidden sm:block">
                  {banner.title}
                </p>
              </div>
            </div>
          </div>
        ))}

        <div className="absolute bottom-10 left-1/2 -translate-x-1/2 z-40 flex items-center space-x-4">
          {loadBannerData.map((_, i) => (
            <button
              key={i}
              onClick={() => setCurrentBanner(i)}
              className={`group relative h-1.5 transition-all duration-500 overflow-hidden rounded-full ${
                i === currentBanner ? "w-16 bg-white/20" : "w-8 bg-white/40"
              }`}
            >
              {i === currentBanner && (
                <div className="absolute inset-0 bg-white animate-progress"></div>
              )}
            </button>
          ))}
        </div>
      </div>
    </section>
  );
};

export default HomeBanner;
