"use client";

import { useState, useEffect, useCallback } from "react";
import Image from "next/image";
import { AnimatePresence, motion } from "framer-motion";
import { X, ChevronLeft, ChevronRight, ShoppingCart } from "lucide-react";
import { createPortal } from "react-dom";
import { getReadableTextColor } from "@/lib/color-contrast";
import { useVisaoDaLoja } from "@/components/VisaoDaLojaContext";

export function formatMoney(value: number) {
  return new Intl.NumberFormat("pt-BR", {
    style: "currency",
    currency: "BRL",
  }).format(value);
}

interface StoryItem {
  id: string;
  image_url: string;
  product_id?: string | null;
  product?: {
    id: string;
    name: string;
    price: number;
    price_on_request: boolean;
    image_url?: string;
  };
}

interface StoryGroup {
  id: string;
  title: string;
  thumbnail_url: string | null;
  items: StoryItem[];
}

export default function StoriesCarousel({ 
  groups, 
  primaryColor,
  slug
}: { 
  groups: StoryGroup[],
  primaryColor: string,
  slug: string
}) {
  const [activeGroupId, setActiveGroupId] = useState<string | null>(null);
  const [activeItemIndex, setActiveItemIndex] = useState(0);
  const [mounted, setMounted] = useState(false);
  const [progress, setProgress] = useState(0);
  const { textoNoLugarDoPreco: textoSemPreco } = useVisaoDaLoja();

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setMounted(true);
  }, []);

  const activeGroup = groups.find(g => g.id === activeGroupId);
  const activeItem = activeGroup?.items?.[activeItemIndex];

  const closeStory = useCallback(() => {
    setActiveGroupId(null);
    setActiveItemIndex(0);
    setProgress(0);
  }, []);

  const handleNext = useCallback(() => {
    setProgress(0);
    const currentGroup = groups.find((g) => g.id === activeGroupId);
    if (!currentGroup) return;

    if (activeItemIndex < currentGroup.items.length - 1) {
      setActiveItemIndex((prev) => prev + 1);
    } else {
      const currentGroupIndex = groups.findIndex((g) => g.id === activeGroupId);
      if (currentGroupIndex < groups.length - 1) {
        setActiveGroupId(groups[currentGroupIndex + 1].id);
        setActiveItemIndex(0);
      } else {
        closeStory();
      }
    }
  }, [activeItemIndex, groups, activeGroupId, closeStory]);

  const handlePrev = useCallback(() => {
    setProgress(0);
    const currentGroup = groups.find((g) => g.id === activeGroupId);
    if (!currentGroup) return;

    if (activeItemIndex > 0) {
      setActiveItemIndex((prev) => prev - 1);
    } else {
      const currentGroupIndex = groups.findIndex((g) => g.id === activeGroupId);
      if (currentGroupIndex > 0) {
        const prevGroup = groups[currentGroupIndex - 1];
        setActiveGroupId(prevGroup.id);
        setActiveItemIndex(prevGroup.items.length - 1);
      }
    }
  }, [activeItemIndex, groups, activeGroupId]);

  // Story Timer
  useEffect(() => {
    if (!activeGroupId || !activeGroup || !activeItem) {
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setProgress(0);
      return;
    }

    const duration = 5000; // 5 seconds per story
    const interval = 50; // update every 50ms
    const step = (interval / duration) * 100;

    const timer = setInterval(() => {
      setProgress(prev => {
        if (prev >= 100) {
          clearInterval(timer);
          handleNext();
          return 0;
        }
        return prev + step;
      });
    }, interval);

    return () => clearInterval(timer);
  }, [activeGroupId, activeItemIndex, activeGroup, activeItem, handleNext]);

  if (!groups || groups.length === 0) return null;

  return (
    <div className="w-full bg-white pt-2 pb-1 border-b border-gray-100">
      <div className="flex items-start gap-3 px-3 overflow-x-auto no-scrollbar pb-1 pt-1">
        {groups.map(group => (
          <button 
            key={group.id} 
            className="flex flex-col items-center gap-1 shrink-0 group focus:outline-none"
            onClick={() => {
              setActiveGroupId(group.id);
              setActiveItemIndex(0);
            }}
          >
            <div 
              className="w-[66px] h-[66px] rounded-full p-[1.5px] transition-transform group-active:scale-95 story-ring-animated flex items-center justify-center"
            >
              <div className="w-full h-full rounded-full border-[2.5px] border-white bg-gray-100 overflow-hidden relative z-10">
                {group.thumbnail_url && (
                  <Image 
                    src={group.thumbnail_url} 
                    alt={group.title} 
                    fill 
                    className="object-cover"
                  />
                )}
              </div>
            </div>
            <span className="text-[11px] font-medium text-gray-800 w-[70px] truncate text-center mt-0.5">
              {group.title}
            </span>
          </button>
        ))}
      </div>

      {mounted && createPortal(
        <AnimatePresence>
          {activeGroupId && activeGroup && (
            <motion.div 
              initial={{ opacity: 0, y: 50 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: 50 }}
              className="fixed inset-0 z-[99999] bg-black flex flex-col"
              style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0 }}
            >
              {/* Progress Bars */}
              <div className="absolute top-0 left-0 right-0 p-4 z-20 flex gap-1">
                {activeGroup.items.map((item, idx) => (
                  <div key={item.id} className="h-1 flex-1 bg-white/30 rounded-full overflow-hidden">
                    <div 
                      className="h-full bg-white transition-all duration-75 ease-linear"
                      style={{ 
                        width: idx < activeItemIndex ? '100%' : idx === activeItemIndex ? `${progress}%` : '0%' 
                      }}
                    />
                  </div>
                ))}
              </div>

              {/* Header */}
              <div className="absolute top-6 left-0 right-0 px-4 z-20 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div className="w-8 h-8 rounded-full overflow-hidden relative border border-white/50">
                    {activeGroup.thumbnail_url && (
                      <Image src={activeGroup.thumbnail_url} alt="" fill className="object-cover" />
                    )}
                  </div>
                  <span className="text-white font-semibold text-sm drop-shadow-md">{activeGroup.title}</span>
                </div>
                <button onClick={closeStory} className="text-white p-2">
                  <X size={24} />
                </button>
              </div>

              {/* Content area with tap zones */}
              <div className="flex-1 relative flex items-center justify-center">
                {activeItem ? (
                  <div className="absolute inset-0">
                    <Image 
                      src={activeItem.image_url} 
                      alt="" 
                      fill 
                      className="object-contain"
                      priority
                    />
                  </div>
                ) : (
                  <div className="text-white/50 text-sm">Este story ainda não possui fotos.</div>
                )}

                {/* Tap zones */}
                <div className="absolute inset-y-0 left-0 w-1/3 z-10" onClick={handlePrev} />
                <div className="absolute inset-y-0 right-0 w-2/3 z-10" onClick={handleNext} />
              </div>

              {/* Bottom Product Card */}
              {activeItem?.product && (
                <div className="absolute bottom-0 left-0 right-0 p-4 pb-8 z-20 bg-gradient-to-t from-black/90 via-black/50 to-transparent">
                  <div className="bg-white/95 backdrop-blur-md rounded-2xl p-3 flex items-center gap-3 shadow-[0_8px_30px_rgb(0,0,0,0.2)] mx-2 transform transition-transform hover:scale-[1.02] cursor-pointer" onClick={() => window.location.href = `/${slug}/p/${activeItem.product!.id}`}>
                    {/* Product Thumbnail */}
                    <div className="w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shrink-0 border border-gray-200/50 relative">
                      {activeItem.product.image_url ? (
                        <Image src={activeItem.product.image_url} alt={activeItem.product.name} fill className="object-cover" />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center text-gray-400">
                          <ShoppingCart size={16} />
                        </div>
                      )}
                    </div>
                    
                    {/* Product Info */}
                    <div className="flex-1 min-w-0">
                      <h4 className="font-bold text-gray-900 truncate text-sm leading-tight">{activeItem.product.name}</h4>
                      <p className="text-[var(--ks-color-primary)] font-bold text-sm mt-0.5">
                        {activeItem.product.price_on_request ? textoSemPreco : formatMoney(activeItem.product.price)}
                      </p>
                    </div>
                    
                    {/* Action Button */}
                    <div 
                      className="flex-shrink-0 flex items-center justify-center w-10 h-10 rounded-full text-white shadow-sm"
                      style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
                    >
                      <ChevronRight size={20} />
                    </div>
                  </div>
                </div>
              )}
            </motion.div>
          )}
        </AnimatePresence>,
        document.body
      )}
    </div>
  );
}
