'use client';

import React, { useRef, useState, useEffect } from 'react';
import Link from 'next/link';
import { motion } from 'framer-motion';
import { FiChevronLeft, FiChevronRight, FiPlay, FiX } from 'react-icons/fi';
import { useProfileStore, WatchProgress } from '@/stores/profileStore';
import { cn } from '@/lib/utils';
import { moviesApi, seriesApi } from '@/lib/api';

export default function ContinueWatchingRow() {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(true);
  const { activeProfile, watchProgress, clearProgress } = useProfileStore();
  const [posterMap, setPosterMap] = useState<Record<string, string>>({});

  useEffect(() => {
    async function loadPosters() {
      try {
        const [moviesRes, seriesRes] = await Promise.all([
          moviesApi.getAll(1, 200).catch(() => ({ data: [] })),
          seriesApi.getAll(1, 200).catch(() => ({ data: [] }))
        ]);

        const map: Record<string, string> = {};

        if (moviesRes && moviesRes.data) {
          moviesRes.data.forEach((m: any) => {
            if (m.posterUrl) map[String(m.id)] = m.posterUrl;
          });
        }

        if (seriesRes && seriesRes.data) {
          seriesRes.data.forEach((s: any) => {
            if (s.posterUrl) map[String(s.id)] = s.posterUrl;
          });
        }

        setPosterMap(map);
      } catch (err) {
        console.error('Error loading posters mapping:', err);
      }
    }
    loadPosters();
  }, []);

  const items = activeProfile ? watchProgress[activeProfile.id] || [] : [];

  const checkScroll = () => {
    if (!scrollRef.current) return;
    const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
    setCanScrollLeft(scrollLeft > 10);
    setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 10);
  };

  const scroll = (direction: 'left' | 'right') => {
    if (!scrollRef.current) return;
    const amount = scrollRef.current.clientWidth * 0.75;
    scrollRef.current.scrollBy({
      left: direction === 'left' ? -amount : amount,
      behavior: 'smooth',
    });
    setTimeout(checkScroll, 500);
  };

  if (items.length === 0) return null;

  return (
    <motion.section
      initial={{ opacity: 0, y: 15 }}
      animate={{ opacity: 1, y: 0 }}
      className="relative group/row"
    >
      {/* Title */}
      <h2 className="text-lg md:text-xl font-bold text-white mb-3 flex items-center gap-2 select-none">
        🍿 Continuar Viendo
      </h2>

      {/* Scroll container */}
      <div className="relative">
        {/* Left arrow */}
        {canScrollLeft && (
          <button
            onClick={() => scroll('left')}
            className="absolute left-0 top-0 bottom-4 z-20 w-12 bg-gradient-to-r from-dark to-transparent flex items-center justify-start pl-1 opacity-0 group-hover/row:opacity-100 transition-opacity duration-300 cursor-pointer border-0 outline-none"
          >
            <div className="w-9 h-9 rounded-full bg-dark-200/90 border border-white/10 flex items-center justify-center text-white hover:bg-white/20 transition-colors">
              <FiChevronLeft size={20} />
            </div>
          </button>
        )}

        {/* Right arrow */}
        {canScrollRight && (
          <button
            onClick={() => scroll('right')}
            className="absolute right-0 top-0 bottom-4 z-20 w-12 bg-gradient-to-l from-dark to-transparent flex items-center justify-end pr-1 opacity-0 group-hover/row:opacity-100 transition-opacity duration-300 cursor-pointer border-0 outline-none"
          >
            <div className="w-9 h-9 rounded-full bg-dark-200/90 border border-white/10 flex items-center justify-center text-white hover:bg-white/20 transition-colors">
              <FiChevronRight size={20} />
            </div>
          </button>
        )}

        {/* Row Scroll View */}
        <div
          ref={scrollRef}
          onScroll={checkScroll}
          className="flex gap-4 overflow-x-auto pb-4 scrollbar-none snap-x snap-mandatory pr-10"
        >
          {items.map((item) => {
            const percent = (item.currentTime / item.duration) * 100;
            const href = item.type === 'movie' 
              ? `/movies/${item.contentId}` 
              : `/series/${item.seriesId || item.contentId}`;

            return (
              <div
                key={item.id}
                className="flex-shrink-0 w-36 md:w-44 snap-start relative group/card flex flex-col"
              >
                {/* Card Thumbnail Area */}
                <div className="relative aspect-[2/3] w-full rounded-xl overflow-hidden bg-dark-200 border border-white/5 shadow-md transition-all duration-300 group-hover/card:scale-[1.03] group-hover/card:border-primary/80 group-hover/card:shadow-lg group-hover/card:shadow-primary/30">
                  {/* Poster Image */}
                  <img
                    src={posterMap[String(item.contentId)] || posterMap[String(item.seriesId || '')] || item.logoUrl || '/logo.png'}
                    alt={item.title}
                    className="w-full h-full object-cover"
                    loading="lazy"
                    onError={(e) => {
                      (e.target as HTMLImageElement).src = '/logo.png';
                    }}
                  />

                  {/* Hover Dark Overlay & Play Button */}
                  <Link href={href} className="absolute inset-0 bg-black/45 opacity-0 group-hover/card:opacity-100 transition-opacity flex items-center justify-center z-10 cursor-pointer">
                    <div className="w-12 h-12 rounded-full bg-primary/95 flex items-center justify-center scale-75 group-hover/card:scale-100 transition-transform shadow-lg shadow-primary/20">
                      <FiPlay size={20} className="ml-1 text-white" />
                    </div>
                  </Link>

                  {/* Remove button (Dismiss card) */}
                  <button
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      clearProgress(item.contentId);
                    }}
                    className="absolute top-2 right-2 p-1.5 rounded-full bg-black/60 text-white/60 hover:text-white hover:bg-red-600 transition-colors z-20 opacity-0 group-hover/card:opacity-100 border-0"
                    title="Quitar de continuar viendo"
                  >
                    <FiX size={12} />
                  </button>

                  {/* Progress bar overlay at bottom */}
                  <div className="absolute bottom-0 left-0 right-0 h-1 bg-white/20 z-10">
                    <div 
                      className="h-full bg-primary" 
                      style={{ width: `${percent}%` }}
                    />
                  </div>
                </div>

                {/* Title & Metadata */}
                <div className="mt-2.5 px-0.5">
                  <Link href={href} className="text-xs font-bold text-white hover:text-primary transition-colors block truncate max-w-full">
                    {item.title}
                  </Link>
                  <span className="text-[10px] text-white/40 block mt-0.5 select-none font-semibold uppercase tracking-wider font-sans">
                    {item.type === 'movie' ? 'Película' : 'Episodio'} · Falta {Math.round((item.duration - item.currentTime) / 60)} min
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </motion.section>
  );
}
