"use client";
import { FC, ReactNode, useState } from "react";
import { MovieCard } from "@/components/atoms/MovieCard";
import { Movie } from "@/types/global";
import { useGlobalStore } from "@/app/store/globalStore";
import { Dropdown } from "@/components/atoms/Dropdown";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { Button } from "@/components/atoms/Button";
import { Label } from "@/components/atoms/Label";
import { FaList } from "react-icons/fa";
import { MovieRow } from "@/components/atoms/MovieRow";

type Props = {
  heading?: string;
  icon?: ReactNode;
  colors?: keyof typeof colorsMap;
  displayType?: "grid" | "list";

  overrideMovies?: Movie[];

  showFilters?: boolean;
  filterSeen?: 0 | 1;
  filterFavorites?: 0 | 1;
  filterUpcoming?: 0 | 1;
  filterReleased?: 0 | 1;

  fluid?: boolean;
  showSorting?: boolean;
  sort?: "title" | "releaseDate" | "popularity";
  sortDirection?: "asc" | "desc";

  loadMore?: boolean;
};

export const MovieList: FC<Props> = ({
  heading,
  icon,
  colors = "white",
  overrideMovies,
  showFilters = true,
  filterSeen: filterSeenInitial,
  filterFavorites: filterFavoritesInitial,
  filterUpcoming: filterUpcomingInitial,
  filterReleased: filterReleasedInitial,
  fluid = false,
  showSorting = true,
  sort: sortType = "releaseDate",
  sortDirection = "asc",
  loadMore = false,
  displayType = "grid",
}) => {
  const { movies: storeMovies } = useGlobalStore();
  const movies = overrideMovies || storeMovies;

  const [display, setDisplay] = useState<"grid" | "list">(displayType);
  const [filter, setFilter] = useState({
    seen: filterSeenInitial,
    favorites: filterFavoritesInitial,
    upcoming: filterUpcomingInitial,
    released: filterReleasedInitial,
  });
  const [sort, setSort] = useState<"title" | "releaseDate" | "popularity">(
    sortType
  );

  const [loaded, setLoaded] = useState(loadMore ? 8 : movies.length);
  const [parent] = useAutoAnimate();

  const filteredMovies = movies.filter((movie) => {
    let result = true;
    const today = new Date();
    if (filter.seen !== undefined) {
      result = movie.seen === !!filter.seen;
    }
    if (filter.favorites !== undefined) {
      result = result && movie.favorite === !!filter.favorites;
    }
    if (filter.upcoming !== undefined) {
      const releaseDate = new Date(movie.release_date);
      result =
        result && filter.upcoming ? releaseDate > today : releaseDate < today;
    }
    if (filter.released !== undefined) {
      const releaseDate = new Date(movie.release_date);
      result =
        result && filter.released ? releaseDate < today : releaseDate > today;
    }
    return result;
  });

  let sortedMovies = filteredMovies.sort((a, b) => {
    if (sort === "title") return a.title.localeCompare(b.title);
    if (sort === "releaseDate")
      return (
        new Date(b.release_date).getTime() - new Date(a.release_date).getTime()
      );
    if (sort === "popularity") return b.popularity - a.popularity;
    return 0;
  });

  sortedMovies = sortedMovies.slice(0, loaded);

  if (sortDirection === "desc") {
    sortedMovies = sortedMovies.reverse();
  }

  const handleFilter = (key?: keyof typeof filter) => {
    setFilter({
      seen: filterSeenInitial,
      favorites: filterFavoritesInitial,
      upcoming: filterUpcomingInitial,
      released: filterReleasedInitial,
      ...(key && { [key]: 1 }),
    });
  };

  return (
    <section className="blocks">
      <div className={`${fluid ? "max-w-full px-4" : "container"}`}>
        {heading && (
          <div className="flex items-center gap-3">
            {icon && (
              <div
                className={`hidden sm:block p-2 rounded-lg ${colorsMap[colors]}`}
              >
                {icon}
              </div>
            )}
            <h2
              className={`text-3xl font-bold ${colorsMap[colors]} bg-clip-text text-transparent text-center sm:text-left`}
            >
              {heading}
            </h2>
          </div>
        )}
        {showFilters && (
          <div className="flex flex-wrap gap-4 mt-6 p-4 rounded-xl bg-gradient-to-br from-slate-800/50 via-slate-800/30 to-slate-900/50 border border-slate-700/30 shadow-lg">
            <Label
              onClick={() => handleFilter()}
              active={
                filter.seen === filterSeenInitial &&
                filter.favorites === filterFavoritesInitial &&
                filter.upcoming === filterUpcomingInitial &&
                filter.released === filterReleasedInitial
              }
            >
              Wszystkie ({movies.length})
            </Label>
            <Label
              active={filter.favorites !== undefined}
              onClick={() => handleFilter("favorites")}
            >
              Ulubione ({movies.filter((movie) => movie.favorite).length})
            </Label>
            <Label
              active={filter.seen !== undefined}
              onClick={() => handleFilter("seen")}
            >
              Obejrzane ({movies.filter((movie) => movie.seen).length})
            </Label>
            <Label
              active={filter.released !== undefined}
              onClick={() => handleFilter("released")}
            >
              W kinach (
              {
                movies.filter(
                  (movie) => new Date(movie.release_date) < new Date()
                ).length
              }
              )
            </Label>
            <Label
              active={filter.upcoming !== undefined}
              onClick={() => handleFilter("upcoming")}
            >
              Nadchodzące (
              {
                movies.filter(
                  (movie) => new Date(movie.release_date) > new Date()
                ).length
              }
              )
            </Label>

            {showSorting && (
              <div className="flex items-center gap-3 ml-auto">
                <Dropdown
                  items={[
                    { label: "Tytuł", value: "title" },
                    { label: "Data premiery", value: "releaseDate" },
                    { label: "Popularność", value: "popularity" },
                  ]}
                  defaultValue={sort}
                  callback={(value) => setSort(value as "title")}
                />
                <Button
                  theme="glass"
                  size="icon"
                  onClick={() =>
                    setDisplay(display === "grid" ? "list" : "grid")
                  }
                >
                  <FaList />
                </Button>
              </div>
            )}
          </div>
        )}
        {filteredMovies.length === 0 && (
          <p className="text-text/60 text-sm">Brak filmów</p>
        )}
        {filteredMovies.length > 0 && (
          <div
            className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-y-6 gap-3 sm:gap-6 mt-8 justify-center"
            ref={parent}
          >
            {sortedMovies.map((movie) =>
              display === "grid" ? (
                <MovieCard key={movie.id} layout="aurora" {...movie} />
              ) : (
                <MovieRow key={movie.id} movie={movie} compact />
              )
            )}
          </div>
        )}
        {loadMore && filteredMovies.length > loaded && (
          <div className="flex justify-center mt-10">
            <Button
              size="small"
              theme="glass"
              onClick={() => setLoaded(movies.length)}
            >
              Pokaż więcej
            </Button>
          </div>
        )}
      </div>
    </section>
  );
};

const colorsMap = {
  white: "bg-gradient-to-r from-white to-gray-300",
  yellow: "bg-gradient-to-r from-yellow-400 to-orange-400",
  blue: "bg-gradient-to-r from-blue-400 to-purple-400",
  green: "bg-gradient-to-r from-green-400 to-teal-400",
  red: "bg-gradient-to-r from-red-400 to-pink-400",
  purple: "bg-gradient-to-r from-purple-400 to-pink-400",
  orange: "bg-gradient-to-r from-orange-400 to-yellow-400",
  pink: "bg-gradient-to-r from-pink-400 to-purple-400",
  teal: "bg-gradient-to-r from-teal-400 to-green-400",
  gray: "bg-gradient-to-r from-gray-400 to-gray-400",
};
