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 TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import IconButton from '@mui/material/IconButton';
import SearchIcon from '@mui/icons-material/Search';
import ClearIcon from '@mui/icons-material/Clear';

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

const categories = [
  { label: '15min', value: '15min' },
  { label: '30min', value: '30min' },
  { label: '60min', value: '60min' },
  { label: '大于60min', value: '大于60min' },
  { label: '最新添加', value: '最新添加' },
];

const SEARCH_CATEGORY = 'search';
const LIMIT = 20;
const DEFAULT_CATEGORY = categories[0].value;


const usePersistedState = (key, defaultValue) => {
  const [state, setState] = useState(() => {
    const stored = localStorage.getItem(key);
    return stored ? JSON.parse(stored) : defaultValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(state));
  }, [key, state]);

  return [state, setState];
};

const Main = () => {
  const config = useContext(ConfigContext);
  const [loading, setLoading] = useState(false);
  const isFirstLoad = useRef(true);
  const scrollListenerActive = useRef(false);
  const skipScrollRestore = useRef(false);
  const isPaginating = useRef(false); // New ref for pagination

  const [params, setParams] = usePersistedState('params', {
    lastCategory: DEFAULT_CATEGORY,
    history: Object.fromEntries([
      ...categories.map(cat => [cat.value, { lastPage: 1, scrollPos: 0 }]),
      [SEARCH_CATEGORY, { lastPage: 1, scrollPos: 0, searchQuery: '' }] // Ensure searchQuery is part of history for search
    ]),
    searchQuery: '' // Global search query, might be redundant if using history.searchQuery
  });

  const [movies, setMovies] = useState([]);
  const [pagination, setPagination] = useState({ page: 1, total: 0, pages: 1 });
  const [searchInput, setSearchInput] = useState(params.searchQuery || '');

  const currentCategory = params.lastCategory || DEFAULT_CATEGORY;
  const currentCategoryHistory = params.history[currentCategory] || { lastPage: 1, scrollPos: 0 };


  const handleScrollPosition = useCallback((action, category = currentCategory) => {
    if (action === 'save') {
      const currentScrollPos = window.scrollY;
      setParams(prev => ({
        ...prev,
        history: {
          ...prev.history,
          [category]: {
            ...(prev.history[category] || { lastPage: 1 }),
            scrollPos: currentScrollPos
          }
        }
      }));
    } else if (action === 'restore') {
      const scrollPos = params.history?.[category]?.scrollPos || 0;
      // console.log(`Attempting to restore scroll for ${category} to ${scrollPos}`);
      requestAnimationFrame(() => {
        // Increased timeout slightly for better rendering chance
        setTimeout(() => {
          window.scrollTo(0, scrollPos);
          // console.log(`Scrolled to ${scrollPos} for ${category}`);
        }, 150);
      });
    }
  }, [setParams, params.history, currentCategory]);


  const manageScrollListener = useCallback((action) => {
    const scrollHandler = () => {
      clearTimeout(window.scrollTimer);
      window.scrollTimer = setTimeout(() => handleScrollPosition('save'), 200); // Debounce save
    };
    window.scrollHandler = scrollHandler; // Store to remove the correct one

    if (action === 'setup' && !scrollListenerActive.current) {
      window.addEventListener('scroll', window.scrollHandler);
      scrollListenerActive.current = true;
    } else if (action === 'remove' && scrollListenerActive.current) {
      window.removeEventListener('scroll', window.scrollHandler);
      scrollListenerActive.current = false;
      clearTimeout(window.scrollTimer);
    }
  }, [handleScrollPosition]);


  const fetchMovies = useCallback(async (category, page, search = '', options = {}) => {
    if (options.skipRestore) {
      skipScrollRestore.current = true;
    }

    setLoading(true);
    try {
      const isSearch = category === SEARCH_CATEGORY;
      const isLatest = category === '最新添加';

      let apiUrl = `/movie/list?page=${page}&limit=${LIMIT}`;
      if (isSearch) apiUrl += `&search=${encodeURIComponent(search)}`;
      else if (isLatest) apiUrl += `&sort=created_time&order=desc`;
      else apiUrl += `&category=${encodeURIComponent(category)}`;

      const response = await axios.get(apiUrl);
      if (response.status !== 200) {
        console.error("API Error:", response);
        setMovies([]);
        setPagination({ page, total: 0, pages: 1 });
        return;
      }

      const { items, total } = response.data.data;
      const totalPages = Math.ceil(total / LIMIT);

      if (items.length === 0 && page > 1 && !isSearch) { // Don't auto-decrement page for search
        setParams(prev => ({
          ...prev,
          history: {
            ...prev.history,
            [category]: { ...prev.history[category], lastPage: Math.max(1, page - 1) }
          }
        }));
        // Optionally, fetch page - 1 here, or let user do it.
        // For now, just update the state and show no movies.
        setMovies([]);
        setPagination({ page: Math.max(1, page - 1), total, pages: totalPages });
        return;
      }

      setMovies(items);
      setPagination({ page, total, pages: totalPages });

    } catch (error) {
      console.error('Error fetching movies:', error);
      setMovies([]);
      setPagination({ page, total: 0, pages: 1 });
    } finally {
      setLoading(false); // This will trigger the useEffect[loading]
    }
  }, [setParams]); // Removed currentCategory from deps as fetchMovies doesn't directly use it for scroll


  const handleTransition = useCallback((actionCallback) => {
    // console.log(`Transition: Saving scroll for ${currentCategory}`);
    manageScrollListener('remove');
    handleScrollPosition('save'); // Save scroll for the category we are leaving
    actionCallback();
    // manageScrollListener will be set up again in useEffect[loading]
  }, [manageScrollListener, handleScrollPosition, currentCategory]);


  // Initial Load
  useEffect(() => {
    if (!isFirstLoad.current) return;

    const categoryToLoad = params.lastCategory || DEFAULT_CATEGORY;
    const historyForCategory = params.history[categoryToLoad] || { lastPage: 1, scrollPos: 0 };
    const pageToLoad = historyForCategory.lastPage;
    let searchQueryToLoad = '';
    if (categoryToLoad === SEARCH_CATEGORY) {
      searchQueryToLoad = params.searchQuery || (historyForCategory.searchQuery || '');
      setSearchInput(searchQueryToLoad); // Sync search input
    }
    // console.log(`Initial Load: Fetching ${categoryToLoad}, page ${pageToLoad}, search: "${searchQueryToLoad}"`);
    fetchMovies(categoryToLoad, pageToLoad, searchQueryToLoad);
    isFirstLoad.current = false;
  }, []); // Runs only once on mount


  // Scroll Management after data loading
  useEffect(() => {
    if (loading || isFirstLoad.current) return; // Don't run if loading or still initial phase

    manageScrollListener('remove'); // Ensure no listener interference

    if (isPaginating.current) {
      // console.log("Pagination: Scrolling to top");
      window.scrollTo(0, 0);
      isPaginating.current = false;
    } else if (skipScrollRestore.current) {
      // console.log(`Skipping scroll restore for ${currentCategory} (e.g., after rename)`);
      skipScrollRestore.current = false;
    } else {
      // console.log(`Restoring scroll for ${currentCategory} (normal flow)`);
      handleScrollPosition('restore', currentCategory);
    }

    manageScrollListener('setup'); // Setup listener after scroll decision

  }, [loading, currentCategory, handleScrollPosition, manageScrollListener]);


  const handleCategoryChange = useCallback((newCategory) => {
    handleTransition(() => {
      const newCategoryHistory = params.history[newCategory] || { lastPage: 1, scrollPos: 0 };
      let searchQueryForNewCategory = '';
      if (newCategory === SEARCH_CATEGORY) {
        searchQueryForNewCategory = params.searchQuery || (newCategoryHistory.searchQuery || '');
        setSearchInput(searchQueryForNewCategory); // Sync search input
      } else {
        setSearchInput(''); // Clear search input if not search category
      }

      setParams(prev => ({ ...prev, lastCategory: newCategory }));
      // console.log(`Category Change: Fetching ${newCategory}, page ${newCategoryHistory.lastPage}`);
      fetchMovies(newCategory, newCategoryHistory.lastPage, searchQueryForNewCategory);
    });
  }, [handleTransition, setParams, fetchMovies, params.history, params.searchQuery]);


  const handlePageChange = useCallback((_, page) => {
    // Save scroll position for the current page of the current category BEFORE fetching new page data
    handleScrollPosition('save', currentCategory);
    isPaginating.current = true; // Signal that this is a pagination action

    setParams(prev => ({
      ...prev,
      history: {
        ...prev.history,
        [currentCategory]: { ...currentCategoryHistory, lastPage: page }
      }
    }));

    const searchQueryForPageChange = currentCategory === SEARCH_CATEGORY ? (params.searchQuery || currentCategoryHistory.searchQuery || '') : '';
    // console.log(`Page Change: Fetching ${currentCategory}, page ${page}, search: "${searchQueryForPageChange}"`);
    fetchMovies(currentCategory, page, searchQueryForPageChange);
    // Scrolling to top will be handled by useEffect[loading] due to isPaginating.current
  }, [setParams, fetchMovies, currentCategory, params.searchQuery, currentCategoryHistory, handleScrollPosition]);


  const handleSearchSubmit = useCallback(() => {
    const trimmedSearch = searchInput.trim();
    if (!trimmedSearch) return;

    handleTransition(() => {
      setParams(prev => ({
        ...prev,
        lastCategory: SEARCH_CATEGORY,
        searchQuery: trimmedSearch, // Update global search query
        history: {
          ...prev.history,
          [SEARCH_CATEGORY]: { // Reset search history to page 1 for new search
            lastPage: 1,
            scrollPos: 0, // New search starts at top
            searchQuery: trimmedSearch
          }
        }
      }));
      // console.log(`Search Submit: Fetching ${SEARCH_CATEGORY}, page 1, search: "${trimmedSearch}"`);
      fetchMovies(SEARCH_CATEGORY, 1, trimmedSearch);
    });
  }, [handleTransition, setParams, fetchMovies, searchInput]);


  const handleClearSearch = useCallback(() => {
    if (!searchInput && currentCategory !== SEARCH_CATEGORY) return;

    setSearchInput('');
    // If we are currently in search results, transition to default category
    if (currentCategory === SEARCH_CATEGORY) {
      handleTransition(() => {
        const defaultCategoryHistory = params.history[DEFAULT_CATEGORY] || { lastPage: 1, scrollPos: 0 };
        setParams(prev => ({
          ...prev,
          lastCategory: DEFAULT_CATEGORY,
          searchQuery: '', // Clear global search query
          // We can choose to preserve or reset params.history[SEARCH_CATEGORY].searchQuery
          // For now, let's clear it in history as well if we are clearing and navigating away
          history: {
            ...prev.history,
            [SEARCH_CATEGORY]: { ...params.history[SEARCH_CATEGORY], searchQuery: '' }
          }
        }));
        // console.log(`Clear Search (was search category): Fetching ${DEFAULT_CATEGORY}, page ${defaultCategoryHistory.lastPage}`);
        fetchMovies(DEFAULT_CATEGORY, defaultCategoryHistory.lastPage);
      });
    } else {
      // If not in search results, just clear the persisted search query
      setParams(prev => ({ ...prev, searchQuery: '' }));
    }
  }, [currentCategory, fetchMovies, params.history, searchInput, setParams, handleTransition]);


  const handleRename = useCallback(async (oldName, newName) => {
    try {
      const response = await axios.post('/movie/rename', { old_name: oldName, new_name: newName });
      if (response.data.code === 200) {
        // Refresh current view data, but skip scroll restoration
        const pageToRefresh = currentCategoryHistory.lastPage;
        const searchQueryForRefresh = currentCategory === SEARCH_CATEGORY ? (params.searchQuery || currentCategoryHistory.searchQuery || '') : '';
        // console.log(`Rename: Refreshing ${currentCategory}, page ${pageToRefresh}, search: "${searchQueryForRefresh}" with skipRestore`);
        await fetchMovies(currentCategory, pageToRefresh, searchQueryForRefresh, { skipRestore: true });
      } else {
        throw new Error(response.data.message || '重命名失败');
      }
    } catch (error) {
      console.error('重命名错误:', error);
      throw error; // Re-throw to allow MovieCard to handle it if needed
    }
  }, [fetchMovies, currentCategory, currentCategoryHistory, params.searchQuery]);


  const handleMovieCardClick = useCallback(() => {
    // This is a navigation, so save scroll state
    // console.log(`Movie Card Click: Saving scroll for ${currentCategory} before navigating away.`);
    handleScrollPosition('save', currentCategory);
    // No need for manageScrollListener('remove') here as the component might unmount
    // or if it's an in-app navigation, the next component will manage its own scroll.
  }, [handleScrollPosition, currentCategory]);

  const handleSearchChange = useCallback((e) => setSearchInput(e.target.value), []);
  const handleSearchKeyDown = useCallback((e) => {
    if (e.key === 'Enter') handleSearchSubmit();
  }, [handleSearchSubmit]);

  // Cleanup scroll listener on unmount
  useEffect(() => {
    return () => {
      manageScrollListener('remove');
    };
  }, [manageScrollListener]);


  const paginationComponent = movies.length > 0 && pagination.pages > 1 && (
    <Pagination
      count={pagination.pages}
      page={pagination.page}
      onChange={handlePageChange}
      sx={{ my: 2, display: 'flex', justifyContent: 'center' }}
    />
  );

  return (
    <Container style={{ marginTop: 20 }}>
      <TextField
        fullWidth
        variant="outlined"
        placeholder="搜索文件名..."
        value={searchInput}
        onChange={handleSearchChange}
        onKeyDown={handleSearchKeyDown}
        InputProps={{
          startAdornment: <InputAdornment position="start"><SearchIcon /></InputAdornment>,
          endAdornment: searchInput && (
            <InputAdornment position="end">
              <IconButton onClick={handleClearSearch} edge="end"><ClearIcon /></IconButton>
            </InputAdornment>
          )
        }}
        sx={{ mb: 2 }}
      />

      <CategoryNav
        categories={categories}
        currentCategory={currentCategory === SEARCH_CATEGORY ? SEARCH_CATEGORY : currentCategory} // Pass SEARCH_CATEGORY special value
        onCategoryChange={handleCategoryChange}
      />

      {currentCategory === SEARCH_CATEGORY && (
        <div style={{ textAlign: 'center', margin: '10px 0' }}>
          搜索: "{params.searchQuery || currentCategoryHistory.searchQuery}" ({pagination.total} 个结果)
        </div>
      )}

      {paginationComponent}

      {loading && <CircularProgress sx={{ display: 'block', margin: '20px auto' }} />}

      {!loading && movies.length === 0 && (
        <div style={{ textAlign: 'center', margin: '20px 0', color: 'gray' }}>
          没有找到结果。
        </div>
      )}

      {!loading && movies.length > 0 && (
        <Grid container spacing={2} sx={{ mt: 0.5 }}>
          {movies.map(item => (
            <Grid item xs={6} sm={4} md={3} lg={2} key={item.filename}>
              <Link
                to={`/res/${item.filename}`}
                style={{ textDecoration: 'none' }} // Removed paddingBottom, handle in Card
                onClick={handleMovieCardClick}
              >
                <MovieCard movie={item} config={config} onRename={handleRename} />
              </Link>
            </Grid>
          ))}
        </Grid>
      )}

      {paginationComponent}
    </Container>
  );
};

export default Main;