"use client";

import { BellRing, Play } from "lucide-react";
import Image from "next/image";
// import Link from "next/link";
import React, { useState } from "react";
// import { Blurhash } from "react-blurhash";
import { ImageConstant } from "../../../constant/ImageConstant";
import IconButton from "../icon-button/icon-button";
import { format } from "date-fns";
import { Button } from "../ui/button";
import { useReminder } from "@/state/home/home.action";
import { useSession } from "next-auth/react";
import { truncateWords } from "@/lib/common-function";
export interface SeriesItem {
  id: string;
  src: string;
  is_reminded?: boolean;
  early_access_datetime?: string;
  schedule_datetime?: string;
  title: string;
  tags?: string[] | null;
  genres?: string[] | null;
  video_id?: string;
  series_id?: string;
  description?: string;
  content_tag?: {
    name: string;
    text_color?: string;
    color?: string;
  } | null;
  blurHash?: {
    hash: string;
  } | null;
  thumbnail_high_1x1?: string;
  averageRating?: number;
}

interface SeriesCardProps {
  item: SeriesItem;
  categoryKey?: string;
  refetch?: () => void;
}

const SeriesCard: React.FC<SeriesCardProps> = ({
  item,
  categoryKey = "",
  refetch,
}) => {
  const { data: session } = useSession();

  const [isImageLoaded, setIsImageLoaded] = useState(false);

  const { mutate: remiderCheck } = useReminder();
  const handelReminder = () => {
    const payload = {
      seriesId: item.series_id ?? null,
      videoId: item.video_id ?? null,
      shouldEnable: !item.is_reminded,
    };
    remiderCheck(payload, {
      onSuccess: () => {
        if (refetch) refetch();
      },
    });
    // console.log("Reminder Payload:", payload);
  };

  return (
    <div className="flex flex-col h-full">
      <div className="relative group overflow-hidden rounded-[10px] flex-grow">
        <div className="relative aspect-[3/4] w-full h-full rounded-[10px] overflow-hidden">
          <Image
            src={
              item?.src?.startsWith("https")
                ? item.src
                : `${process.env.NEXT_PUBLIC_IMAGE_BASE_URL}/${item?.src}` ||
                  ImageConstant.imagePlaceHolder
            }
            alt={item?.title ?? "image"}
            fill
            sizes="(max-width: 768px) 50vw, 33vw"
            className={`object-cover transition-transform duration-500 group-hover:scale-105 ${
              isImageLoaded ? "opacity-100" : "opacity-0"
            }`}
            onLoad={() => setIsImageLoaded(true)}
          />
        </div>
        {/* <div className="absolute inset-0 rounded-[10px] bg-gradient-to-t from-[#000] via-[#000]/80 to-transparent opacity-0 group-hover:opacity-100 transition duration-500"></div> */}
        <div
          className="absolute inset-0 rounded-[10px] 
  bg-gradient-to-t from-[#121212] via-[#121212]/80 to-transparent
  opacity-0 group-hover:opacity-100 
  transition duration-500"
        ></div>
        {(item?.content_tag?.name || item?.early_access_datetime) && (
          <h5
            className="text-white text-center rounded-[0_10px_0_10px] px-2 py-0.5 absolute top-0 right-0 text-[14px] md:text-[20px] border-b-2 border-l-2 border-[#ffb306]
            "
            style={{
              background: item?.early_access_datetime
                ? "linear-gradient(to right, #3eb489, #013220)"
                : item?.schedule_datetime && categoryKey === "comingSoon"
                  ? "linear-gradient(to right, #7E19FA, #A45CFD)"
                  : item?.content_tag?.color ||
                    "linear-gradient(to right, #ED3A57, #FD521E)",
              color:
                item?.early_access_datetime || item?.schedule_datetime
                  ? "#FFFFFF"
                  : item?.content_tag?.text_color || "#FFFFFF",
            }}
          >
            {item?.schedule_datetime && item?.early_access_datetime
              ? "Early Access"
              : item?.schedule_datetime && !item?.early_access_datetime
                ? format(item?.schedule_datetime, "do MMM")
                : item?.content_tag?.name}
          </h5>
        )}
        <div className="absolute bottom-2 left-1 w-full flex flex-col gap-2 opacity-0 translate-y-4 group-hover:opacity-100 group-hover:translate-y-0 transition-all duration-500 z-10">
          <div className="flex gap-2 ml-3 flex-wrap">
            {(item.tags || item.genres)?.slice(0, 3)?.map((tag, index) => (
              <p
                className="bg-[#672bfe85] sm:text-[8px] lg:text-[10px] 2xl:text-[12px] p-1 px-2 rounded-[5px]"
                key={`tag_${tag}_${index}`}
              >
                {tag}
              </p>
            ))}
            {item.description && (
              <p className="pr-5">
                {truncateWords(item?.description || "", 10)}
              </p>
            )}
          </div>
          <div className="flex justify-between items-center mt-0 ml-3">
            <div className="mr-3">
              {((categoryKey === "comingSoon" && item?.early_access_datetime) ||
                categoryKey !== "comingSoon") && (
                <IconButton
                  label="Watch Now"
                  icon={<Play className="w-5 h-5" />}
                  href={
                    item?.series_id
                      ? `/series/${item?.series_id}`
                      : `/video/${item?.video_id}`
                  }
                  size="lg"
                  className="!p-3 px-6 font-bold !py-2 w-fit"
                />
              )}
            </div>
          </div>
        </div>
        <div
          className="absolute bottom-0 left-0 w-full h-[40%] rounded-b-[10px]
  bg-gradient-to-t from-[#121212] via-[#121212]/80 to-transparent
  opacity-100 transition duration-500"
        ></div>
      </div>

      {session?.user?.id ? (
        <>
          {item?.is_reminded === false || item?.is_reminded === true ? (
            <>
              {item?.is_reminded === false ? (
                <>
                  <Button
                    onClick={handelReminder}
                    className="bg-gray-300
       text-[14px] text-black cursor-pointer  flex items-center justify-center gap-2 rounded-[7px] transition-all duration-300 ease-in-out!p-3 px-6 hover:bg-gray-300"
                  >
                    Remind Me
                    <BellRing className="w-5 h-5" />
                  </Button>
                </>
              ) : (
                <>
                  <Button
                    onClick={handelReminder}
                    className="border border-[#E50914] bg-gradient-to-r from-[#ED3A57] via-[#ED3A57] to-[#FD521E]
       text-[14px] text-white cursor-pointer p-4 flex items-center justify-center gap-2 rounded-[7px] transition-all duration-300 ease-in-out hover:from-[#c72a40] hover:via-[#c72a40] hover:to-[#e03d1a] !p-3 px-6"
                  >
                    Reminder Set
                    <BellRing className="w-5 h-5" />
                  </Button>
                </>
              )}
            </>
          ) : (
            ""
          )}
        </>
      ) : (
        ""
      )}

      <div className="mt-3">
        <h3 className="text-white font-bold text-base truncate group-hover:text-red-500">
          {item.title}
        </h3>
        <p className="text-gray-400 text-sm mt-1">
          {(item.tags || item.genres)?.[0]}
        </p>
      </div>
    </div>
  );
};

export default SeriesCard;
