import React, { useCallback, useMemo, useState } from 'react';
import {
  Box,
  Typography,
  TextField,
  InputAdornment,
  Paper,
  Button,
  Pagination,
  Stack,
} from '@mui/material';
import { Search as SearchIcon, Refresh as RefreshIcon } from '@mui/icons-material';
import { useAgentList } from '@/hooks/agent-hooks';
import AgentGridView from '@/components/agent/AgentGridView';

function AgentListPage() {
  const [searchValue, setSearchValue] = useState('');
  const {
    agents,
    total,
    loading,
    currentPage,
    pageSize,
    setCurrentPage,
    setKeywords,
    refresh,
  } = useAgentList({ page: 1, page_size: 10 });

  const totalPages = useMemo(() => {
    return Math.ceil((agents?.length || 0) / pageSize) || 1;
  }, [agents, pageSize]);

  const currentPageData = useMemo(() => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return (agents || []).slice(startIndex, endIndex);
  }, [agents, currentPage, pageSize]);

  const handleSearch = useCallback(() => {
    setKeywords(searchValue);
    setCurrentPage(1);
  }, [searchValue, setKeywords, setCurrentPage]);

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" fontWeight={600} mb={2}>Agent 列表</Typography>

      <Paper sx={{ p: 2, mb: 2 }}>
        <Box display="flex" gap={2} alignItems="center">
          <TextField
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            placeholder="搜索名称或描述"
            size="small"
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon />
                </InputAdornment>
              )
            }}
          />
          <Button variant="contained" onClick={handleSearch}>搜索</Button>
          <Button variant="outlined" startIcon={<RefreshIcon />} onClick={refresh}>刷新</Button>
        </Box>
      </Paper>

      <AgentGridView
        agents={currentPageData}
        loading={loading}
        searchTerm={searchValue}
      />

      {totalPages >= 1 && (
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
          <Stack spacing={2}>
            <Pagination
              count={totalPages}
              page={currentPage}
              onChange={(_, page) => setCurrentPage(page)}
              color="primary"
              size="large"
              showFirstButton
              showLastButton
            />
            <Typography variant="body2" color="text.secondary" textAlign="center">
              共 {total} 个，当前第 {currentPage} / {totalPages} 页
            </Typography>
          </Stack>
        </Box>
      )}
    </Box>
  );
}

export default AgentListPage;