import React, { useState, useEffect } from "react";
import { useLocation, useParams, useNavigate } from "react-router-dom";
import api from "../services/api";
import { useSelector, useDispatch } from "react-redux";
import { selectPoster, deselectPoster } from "../services/action";
import {
  Container,
  Typography,
  Grid,
  Card,
  Box,
  Paper,
} from "@material-ui/core";
import { ToggleButton, ToggleButtonGroup } from "@mui/material";
import CheckIcon from "@material-ui/icons/Check";

const LANG_FILTERS = [
  { value: "all",  label: "All" },
  { value: "en",   label: "EN" },
  { value: "fr",   label: "FR" },
  { value: "ja",   label: "JA" },
  { value: "none", label: "—" },
];

const PosterCard = ({ poster, movieName, isSelected, onClick }) => {
  const [imgLoaded, setImgLoaded] = useState(false);

  return (
    <Card
      className={`poster-card ${isSelected ? "selected-poster" : ""}`}
      onClick={onClick}
    >
      <div className="poster-aspect-wrapper">
        <div className={`poster-skeleton${imgLoaded ? " poster-skeleton--hidden" : ""}`} />
        <img
          src={`https://image.tmdb.org/t/p/w500${poster.file_path}`}
          alt={movieName}
          className={`poster-image-img${imgLoaded ? " poster-image-img--loaded" : ""}`}
          onLoad={() => setImgLoaded(true)}
        />
      </div>
      {isSelected && <CheckIcon className="check-icon" />}
    </Card>
  );
};

const PosterGallery = () => {
  const location = useLocation();
  const { watchedDate } = location.state || {};
  const { movieName, movieYear } = useParams();
  const navigate = useNavigate();
  const [posters, setPosters] = useState([]);
  const [loading, setLoading] = useState(true);
  const [langFilter, setLangFilter] = useState("all");
  const dispatch = useDispatch();

  const movieId = `${movieName}-${movieYear}`;
  const selectedPosters = useSelector(
    (state) => state.posterSelections[movieId] || []
  );

  useEffect(() => {
    const fetchPosters = async () => {
      try {
        setLoading(true);
        const response = await api.get(
          `/api/posters/${encodeURIComponent(movieName)}/${encodeURIComponent(movieYear)}`
        );
        if (response.data?.posters) setPosters(response.data.posters);
      } catch (error) {
        console.error("Error fetching posters:", error);
      } finally {
        setLoading(false);
      }
    };
    if (movieName && movieYear) fetchPosters();
  }, [movieName, movieYear]);

  const filteredPosters = posters.filter((p) => {
    if (langFilter === "all") return true;
    if (langFilter === "none") return !p.iso_639_1;
    return p.iso_639_1 === langFilter;
  });

  const isPosterSelected = (posterId) =>
    selectedPosters.some((p) => p.posterId === posterId);

  const handlePosterSelect = (posterId) => {
    if (isPosterSelected(posterId)) {
      dispatch(deselectPoster(movieName, movieYear, posterId));
    } else {
      dispatch(selectPoster(movieName, movieYear, posterId, watchedDate));
      navigate(-1);
    }
  };

  const visiblePosters = loading
    ? Array.from({ length: 8 }).map((_, i) => ({ _skeleton: true, file_path: `sk-${i}` }))
    : filteredPosters;

  return (
    <Container className="poster-gallery">
      <Paper elevation={3} className="content-paper">
        <Box className="lang-filter-bar">
          <ToggleButtonGroup
            value={langFilter}
            exclusive
            onChange={(_, v) => v && setLangFilter(v)}
            className="lang-toggle-group"
          >
            {LANG_FILTERS.map(({ value, label }) => (
              <ToggleButton key={value} value={value} className="lang-toggle-btn">
                {label}
              </ToggleButton>
            ))}
          </ToggleButtonGroup>
        </Box>

        {!loading && filteredPosters.length === 0 ? (
          <Typography align="center" className="no-posters-msg">
            No posters for this language.
          </Typography>
        ) : (
          <Grid container spacing={3}>
            {visiblePosters.map((poster, index) =>
              poster._skeleton ? (
                <Grid item xs={12} sm={6} md={4} lg={3} key={poster.file_path}>
                  <div className="poster-aspect-wrapper">
                    <div className="poster-skeleton" />
                  </div>
                </Grid>
              ) : (
                <Grid item xs={12} sm={6} md={4} lg={3} key={index}>
                  <PosterCard
                    poster={poster}
                    movieName={movieName}
                    isSelected={isPosterSelected(poster.file_path)}
                    onClick={() => handlePosterSelect(poster.file_path)}
                  />
                </Grid>
              )
            )}
          </Grid>
        )}
      </Paper>
    </Container>
  );
};

export default PosterGallery;
