import { Clock, Lock, Play } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import React from "react";
import { Episode } from "../video-player/video-detail-type";
import { ImageConstant } from "../../../constant/ImageConstant";

interface EpisodeGroup {
  ep: string;
  episodes: Episode[];
}

const groupEpisodes = (episodes: Episode[]): EpisodeGroup[] => {
  if (!episodes || episodes.length === 0) {
    return [];
  }

  const sortedEpisodes = [...episodes].sort(
    (a, b) => a.episode_number - b.episode_number
  );

  const grouped = sortedEpisodes.reduce((acc, episode) => {
    const isLocked = episode.episode_number > 2;
    const episodeWithLockStatus = { ...episode, locked: isLocked };

    const groupIndex = Math.floor((episode.episode_number - 1) / 10);
    if (!acc[groupIndex]) {
      const start = groupIndex * 10 + 1;
      const end = start + 9;
      acc[groupIndex] = {
        ep: `Ep ${start}-${end}`,
        episodes: [],
      };
    }
    acc[groupIndex].episodes.push(episodeWithLockStatus);
    return acc;
  }, [] as EpisodeGroup[]);

  return grouped.filter(Boolean);
};

const EpisodeCard = ({ video }: { video: Episode }) => {
  const imageUrl = video.thumbnail
    ? `${video.thumbnail}`
    : ImageConstant.imagePlaceHolder;

  return (
    <Link
      href={
        video.series?.series_id
          ? `/series/${video.series?.series_id}?episode=${video.episode_id}`
          : "#"
      }
      className={video.is_locked ? "cursor-not-allowed" : ""}
    >
      <div className="relative group rounded-lg overflow-hidden cursor-pointer">
        <Image
          src={imageUrl}
          alt={video.title}
          width={400}
          height={160}
          className="w-full h-50 object-cover"
          // onError={(e) => {
          //   e.currentTarget.src =
          //     "https://via.placeholder.com/400x160?text=Image+Not+Available";
          // }}
        />

        <span className="absolute top-2 right-2 bg-black bg-opacity-70 text-white text-xs px-2 py-1 rounded">
          <div className="flex items-center gap-2">
            <Clock size={16} /> {video.duration} m
          </div>
        </span>

        {video.is_locked && (
          <span className="absolute top-2 left-2 text-white bg-[#ED3A57] p-2 rounded-full">
            <Lock size={16} />
          </span>
        )}

        {!video.is_locked && (
          <div className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-60 opacity-0 group-hover:opacity-100 transition-opacity">
            <div className="bg-white bg-opacity-80 rounded-full p-2">
              <Play size={24} color="#f00" />
            </div>
          </div>
        )}

        <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black to-transparent p-2 text-white text-sm">
          {video.episode_number.toString().padStart(2, "0")} : {video.title}
        </div>
      </div>
    </Link>
  );
};

const EpisodesList = ({ seriesDetails }: { seriesDetails: Episode[] }) => {
  const groupedVideos = groupEpisodes(seriesDetails);

  return (
    <div className="container mx-auto px-4 md:px-2">
      <h2 className="text-xl font-semibold my-8">All Episodes</h2>

      {groupedVideos?.map((group, index) => (
        <div key={index} className="mb-10">
          <h2 className="relative w-fit rounded-[5px] mb-8 p-[2px] bg-[linear-gradient(89deg,#ED3A57_34.19%,#FD521E_99.12%)]">
            <span className="block bg-black px-12 py-2 rounded-[3px] text-white">
              {group.ep}
            </span>
          </h2>

          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-4 mb-5">
            {group?.episodes?.map((video) => (
              <EpisodeCard key={video.episode_id} video={video} />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};

export default EpisodesList;
