import React, { useState, useCallback, useMemo, useEffect } from 'react';
import {
  Box,
  Typography,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
  InputAdornment,
  Pagination,
  Stack,
  CircularProgress,
} from '@mui/material';
import {
  Search as SearchIcon,
  Add as AddIcon,
  Refresh as RefreshIcon,
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { useKnowledgeList, useKnowledgeOperations } from '@/hooks/knowledge-hooks';
import { useUserData } from '@/hooks/useUserData';
import KnowledgeGridView from '@/components/knowledge/KnowledgeGridView';
import type { IKnowledge } from '@/interfaces/database/knowledge';
import { useDialog } from '@/hooks/useDialog';
import logger from '@/utils/logger';
import { useTranslation } from 'react-i18next';
import CreateKnowledgeDialog from './components/CreateKnowledgeDialog';

const KnowledgeBaseList: React.FC = () => {

  const {t} = useTranslation();

  const navigate = useNavigate();

  const { deleteKnowledge } = useKnowledgeOperations();

  // 搜索和筛选状态
  const [searchTerm, setSearchTerm] = useState('');
  const [teamFilter, setTeamFilter] = useState<string[]>([]);
  const pageSize = 12; // 每页显示12个知识库

  // 获取用户数据（包含租户列表）
  const { tenantList } = useUserData();

  // 使用knowledge_hooks获取数据
  const {
    knowledgeBases,
    total,
    loading,
    error,
    currentPage,
    setTeamFilter: hookSetTeamFilter,
    setKeywords,
    setCurrentPage,
    refresh,
  } = useKnowledgeList({
    keywords: searchTerm,
    page: 1,
    page_size: pageSize,
  });

  // 处理搜索
  const handleSearch = useCallback((value: string) => {
    setSearchTerm(value);
    setKeywords(value);
  }, [setKeywords]);

  // 处理团队筛选
  const handleTeamFilterChange = useCallback((value: string[]) => {
    if (value.includes('all')) {
      setTeamFilter([]);
      hookSetTeamFilter([]);
    } else {
      setTeamFilter(value);
      hookSetTeamFilter(value);
    }
    setCurrentPage(1);
  }, [setCurrentPage, hookSetTeamFilter]);

  // 处理分页变化
  const handlePageChange = useCallback((_: React.ChangeEvent<unknown>, page: number) => {
    setCurrentPage(page);
  }, [setCurrentPage]);

  // 处理刷新
  const handleRefresh = useCallback(() => {
    refresh();
  }, [refresh]);

  // 创建知识库对话框
  const [createDialogOpen, setCreateDialogOpen] = useState(false);

  // 处理创建知识库：打开对话框
  const handleCreateKnowledge = useCallback(() => {
    setCreateDialogOpen(true);
  }, []);

  const dialog = useDialog();

  // 处理删除知识库
  const handleDeleteKnowledge = useCallback(async (kb: IKnowledge) => {
    // 需要确认删除
    dialog.confirm({
      title: t('common.deleteModalTitle'),
      content: `${t('knowledgeList.confirmDeleteKnowledge')} ${kb.name}？`,
      onConfirm: async () => {
        try {
          await deleteKnowledge(kb.id);
          // 删除成功后刷新列表
          refresh();
        } catch (err) {
          console.error('Failed to delete knowledge:', err);
          // 可以添加错误提示
        }
      },
    });
  }, [deleteKnowledge, refresh, dialog]);

  // 处理查看知识库详情
  const handleViewKnowledge = useCallback((kb: IKnowledge) => {
    navigate(`/knowledge/${kb.id}`);
  }, [navigate]);

  // 计算总页数（基于筛选后的结果）
  const totalPages = Math.ceil(knowledgeBases.length / pageSize);

  // 获取当前页的数据
  const currentPageData = useMemo(() => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return knowledgeBases.slice(startIndex, endIndex);
  }, [knowledgeBases, currentPage, pageSize]);

  // 构建团队筛选选项
  const teamFilterOptions = useMemo(() => {
    const options = [
      { value: 'all', label: t('common.all') },
    ];

    // 添加租户选项
    if (tenantList && tenantList.length > 0) {
      tenantList.forEach(tenant => {
        options.push({
          value: tenant.tenant_id,
          label: tenant.nickname || tenant.tenant_id,
        });
      });
    }

    return options;
  }, [tenantList]);

  return (
    <Box sx={{ p: 3 }}>
      {/* 页面标题 */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4" fontWeight={600}>
          {t('header.knowledgeBase')}
        </Typography>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={handleCreateKnowledge}
          sx={{ borderRadius: 2 }}
        >
          {t('knowledgeList.createKnowledgeBase')}
        </Button>
      </Box>

      {/* 搜索和筛选区域 */}
      <Box sx={{ display: 'flex', gap: 2, mb: 3, alignItems: 'center' }}>
        <TextField
          placeholder={t('knowledgeList.searchKnowledgePlaceholder')}
          value={searchTerm}
          onChange={(e) => handleSearch(e.target.value)}
          sx={{ flex: 1, maxWidth: 400 }}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
          }}
        />

        <FormControl sx={{ minWidth: 120 }}>
          <InputLabel>{t('knowledgeList.teamFilter')}</InputLabel>
          <Select
            value={teamFilter.length > 0 ? teamFilter[0] : 'all'}
            label={t('knowledgeList.teamFilter')}
            defaultValue={'all'}
            onChange={(e) => {
              const value = e.target.value as string;
              handleTeamFilterChange([value]);
            }}
          >
            {teamFilterOptions.map(option => (
              <MenuItem key={option.value} value={option.value}>
                {option.label}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <Button
          variant="outlined"
          startIcon={<RefreshIcon />}
          onClick={handleRefresh}
          disabled={loading}
        >
          {t('common.refresh')}
        </Button>
      </Box>

      {/* 错误提示 */}
      {error && (
        <Box sx={{ mb: 3, p: 2, bgcolor: 'error.light', borderRadius: 1 }}>
          <Typography color="error">
            {t('knowledgeList.loadError')}: {error}
          </Typography>
        </Box>
      )}

      {/* 加载状态 */}
      {loading && (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
          <CircularProgress />
        </Box>
      )}

      {/* 知识库列表 */}
      {!loading && (
        <>
          <KnowledgeGridView
            knowledgeBases={currentPageData}
            onView={handleViewKnowledge}
            onDelete={handleDeleteKnowledge}
            loading={loading}
            searchTerm={searchTerm}
            // teamFilter={teamFilter}
            onCreateKnowledge={handleCreateKnowledge}
          />

          {/* 创建知识库对话框 */}
          <CreateKnowledgeDialog
            open={createDialogOpen}
            onClose={() => setCreateDialogOpen(false)}
            onSuccess={() => {
              setCreateDialogOpen(false);
              refresh();
            }}
          />

          {/* 分页组件 */}
          {totalPages > 1 && (
            <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
              <Stack spacing={2}>
                <Pagination
                  count={totalPages}
                  page={currentPage}
                  onChange={handlePageChange}
                  color="primary"
                  size="large"
                  showFirstButton
                  showLastButton
                />
                <Typography variant="body2" color="text.secondary" textAlign="center">
                  {t('knowledgeList.paginationInfo', { 
                    total: knowledgeBases.length, 
                    current: currentPage, 
                    totalPages: totalPages 
                  })}
                </Typography>
              </Stack>
            </Box>
          )}
        </>
      )}
    </Box>
  );
};

export default KnowledgeBaseList;