import React, { useState, useEffect, useContext, useCallback } from 'react';
import axios from 'axios';
import Container from '@mui/material/Container';
import Grid from '@mui/material/Grid';
import Pagination from '@mui/material/Pagination';
import { Link } from 'react-router-dom';
import CircularProgress from '@mui/material/CircularProgress';

import ConfigContext from './Config';
import MovieCard from './components/MovieCard';
import CategoryNav from './components/CategoryNav';

const Main = () => {
  const config = useContext(ConfigContext);
  const [loading, setLoading] = useState(false);
  const categories = [
    { label: '15min', idx: 0 },
    { label: '30min', idx: 1 },
    { label: '60min', idx: 2 },
    { label: '大于60min', idx: 3 },
  ];

  const limit = 20;

  const getInitialParams = () => {
    const storedParams = localStorage.getItem('params');
    if (storedParams) {
      return JSON.parse(storedParams);
    } else {
      return {
        lastCategory: 0,
        history: {
          0: { lastPage: 1, scrollPos: 0 },
          1: { lastPage: 1, scrollPos: 0 },
          2: { lastPage: 1, scrollPos: 0 },
          3: { lastPage: 1, scrollPos: 0 },
        },
      };
    }
  };

  const [params, setParams] = useState(getInitialParams());

  const [pagination, setPagination] = useState({
    movies: [],
    page: params.history[params.lastCategory].lastPage,
    total: 1,
    length: 1,
  });

  const fetchMovies = useCallback(async (category, page) => {
    setLoading(true);
    try {
      const response = await axios.get(
        `${window.location.origin}/movie/?page=${page}&limit=${limit}&category=${category}`
      );

      if (response.status === 200) {
        const data = response.data.data;

        if (data.items.length === 0 && page > 1) {
          fetchMovies(category, page - 1);
        } else {
          setPagination({
            movies: data.items,
            page: page,
            total: data.total,
            length: Math.ceil(data.total / limit),
          });
        }
      }
    } catch (error) {
      console.error('Error fetching movies:', error);
    } finally {
      setLoading(false);
    }
  }, [window.location.origin, limit]);

  useEffect(() => {
    const currentCategory = params.lastCategory;
    const currentPage = params.history[currentCategory].lastPage;
    fetchMovies(currentCategory, currentPage);
  }, [fetchMovies, params]);

  const updateParams = useCallback((newParams) => {
    setParams((prevParams) => {
      const updatedParams = { ...prevParams, ...newParams };
      localStorage.setItem('params', JSON.stringify(updatedParams));
      return updatedParams;
    });
  }, []);

  const handlePageChange = useCallback(
    (event, page) => {
      const currentCategory = params.lastCategory;
      updateParams({
        history: {
          ...params.history,
          [currentCategory]: { ...params.history[currentCategory], lastPage: page },
        },
      });
      fetchMovies(currentCategory, page);
    },
    [fetchMovies, params, updateParams]
  );

  // 导致递归刷新
  const handleCategoryChange = useCallback(
    (category) => {
      const currentPage = params.history[category].lastPage;
      fetchMovies(category, currentPage);

      const currentCategory = params.lastCategory;
      updateParams({
        lastCategory: category,
        history: {
          ...params.history,
          [currentCategory]: { ...params.history[currentCategory], scrollPos: window.scrollY },
        },
      });
    },
    [fetchMovies, params, updateParams]
  );

  const handleRenderComplete = useCallback(() => {
    const { scrollPos } = params.history[params.lastCategory];
    window.scrollTo(0, scrollPos);
  }, [params]);

  const handleMovieCardClick = () => {
    const currentCategory = params.lastCategory;
    updateParams({
      history: {
        ...params.history,
        [currentCategory]: { ...params.history[currentCategory], scrollPos: window.scrollY },
      },
    });
  };

  return (
    <Container style={{ marginTop: 20 }}>
      <CategoryNav
        categories={categories}
        currentCategory={params.lastCategory}
        onCategoryChange={handleCategoryChange}
      />

      <PaginationWrapper page={pagination.page} length={pagination.length} onPageChange={handlePageChange} />

      {loading ? (
        <Loading />
      ) : (
        <MoviesGrid
          movies={pagination.movies}
          config={config}
          onRenderComplete={handleRenderComplete}
         onMovieCardClick={handleMovieCardClick}
        />
      )}

      <PaginationWrapper page={pagination.page} length={pagination.length} onPageChange={handlePageChange} />
    </Container>
  );
};

const PaginationWrapper = ({ page, length, onPageChange }) => (
  <Grid container justifyContent="center" style={{ marginTop: 20, marginBottom: 20 }}>
    <Pagination count={length} page={page} onChange={onPageChange} />
  </Grid>
);
 

const MoviesGrid = ({ movies, config, onRenderComplete, onMovieCardClick }) => {
  useEffect(() => {
    onRenderComplete();
  }, [movies, onRenderComplete]);

  return (
    <Grid container spacing={2} style={{ marginTop: 3 }}>
      {movies.map((item) => (
        <Grid item xs={6} sm={4} md={3} lg={2}
          style={{ display: 'flex', justifyContent: 'space-between' }}
          key={item.filename}
        >
          <Link
            to={`/res/${item.filename}`}
            style={{ textDecoration: 'none', paddingBottom: 10 }}
            onClick={onMovieCardClick} // 修改这里
          >
            <MovieCard movie={item} config={config} />
          </Link>
        </Grid>
      ))}
    </Grid>
  );
};

const Loading = () => (
  <Grid container justifyContent="center" style={{ marginTop: 20 }}>
    <CircularProgress />
  </Grid>
);

export default Main;