import React, { useState, useEffect, useContext, useCallback, useRef} 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 {
        lastPage: {
          0: 1,
          1: 1,
          2: 1,
          3: 1,
        },
        lastCategory: 0,
      };
    }
  };

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

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


  const paramsRef = useRef(params);
  paramsRef.current = params;

  const fetchMovies = useCallback(async (category, page) => {
    setLoading(true);
    try {
      const response = await axios.get(
        `${config.Host}/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),
          });
          updateParams(category, page);
        }
      }
    } catch (error) {
      console.error('Error fetching movies:', error);
    } finally {
      setLoading(false);
    }
  }, [config.Host, limit]);

  useEffect(() => {

    fetchMovies(paramsRef.current.lastCategory, paramsRef.current.lastPage[paramsRef.current.lastCategory]);
  }, [fetchMovies]);

  const updateParams = (category, page) => {
    setParams((prevParams) => {
      const newParams = {
        ...prevParams,
        lastPage: {
          ...prevParams.lastPage,
          [category]: page,
        },
      };
      localStorage.setItem('params', JSON.stringify(newParams));
      return newParams;
    });
  };

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

  const handleCategoryChange = useCallback((category) => {
    setParams((prevParams) => {
      const newParams = {
        ...prevParams,
        lastCategory: category,
      };
      localStorage.setItem('params', JSON.stringify(newParams));
      return newParams;
    });
    // 从 paramsRef.current 获取当前 category 对应的页面
    fetchMovies(category, paramsRef.current.lastPage[category]);
  }, [fetchMovies]);

  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} />
      )}

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

const PaginationWrapper = ({ page, length, onPageChange }) => (
  <div style={{ textAlign: 'center', marginBottom: 20 }}>
    <Pagination
      count={length}
      page={page}
      onChange={onPageChange}
      shape="rounded"
      color="primary"
      size="large"
    />
  </div>
);

const Loading = () => (
  <div
    style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}
  >
    <CircularProgress />
  </div>
);

const MoviesGrid = ({ movies, config }) => (
  <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 }}
        >
          <MovieCard movie={item} config={config} />
        </Link>
      </Grid>
    ))}
  </Grid>
);

export default Main;