import React, { useState, useEffect } from 'react';
import { useSearchParams, useNavigate } from "react-router-dom";
import {
  Box,
  Typography,
  TextField,
  InputAdornment,
  Paper,
  Alert,
  Button,
  Card,
  CardContent
} from "@mui/material";
import { Search as SearchIcon, Visibility as VisibilityIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useChunkList } from '@/hooks/chunk-hooks';
import ChunkListResult from './components/ChunkListResult';
import knowledgeService from '@/services/knowledge_service';
import type { IKnowledge, IKnowledgeFile } from '@/interfaces/database/knowledge';
import KnowledgeBreadcrumbs from '@/pages/knowledge/components/KnowledgeBreadcrumbs';

function ChunkParsedResult() {
  const { t } = useTranslation();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const kb_id = searchParams.get('kb_id');
  const doc_id = searchParams.get('doc_id');

  const [knowledgeBase, setKnowledgeBase] = useState<IKnowledge | null>(null);
  const [document, setDocument] = useState<IKnowledgeFile | null>(null);
  const [searchKeyword, setSearchKeyword] = useState('');

  // 使用chunk列表hook
  const {
    chunks,
    total,
    loading,
    error,
    currentPage,
    pageSize,
    setCurrentPage,
    setKeywords,
    refresh
  } = useChunkList(doc_id || '', {
    page: 1,
    size: 10,
    keywords: searchKeyword
  });

  // 获取知识库和文档信息
  useEffect(() => {
    const fetchData = async () => {
      if (!kb_id || !doc_id) return;

      try {
        // 获取知识库信息
        const kbResponse = await knowledgeService.getKnowledgeDetail({ kb_id });
        if (kbResponse.data.code === 0) {
          console.log('KnowledgeBase:', kbResponse.data);
          setKnowledgeBase(kbResponse.data.data);
        }

        // 获取文档信息
        const docResponse = await knowledgeService.getDocumentInfos({ doc_ids: [doc_id] });
        if (docResponse.data.code === 0) {
          const docArr: IKnowledgeFile[] = docResponse.data.data;
          if (docArr.length > 0) {
            setDocument(docArr[0]);
          }
        }
      } catch (error) {
        console.error('Failed to fetch data:', error);
      }
    };

    fetchData();
  }, [kb_id, doc_id]);

  // 处理搜索
  const handleSearch = (keyword: string) => {
    setSearchKeyword(keyword);
    setKeywords(keyword);
    setCurrentPage(1);
  };

  // 处理查看文件
  const handleViewFile = () => {
    if (doc_id && kb_id) {
      // 跳转到文件预览页面
      navigate(`/chunk/document-preview/${kb_id}/${doc_id}`);
    }
  };

  if (!kb_id || !doc_id) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error">
          {t('chunkPage.missingParams')}
        </Alert>
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      {/* 面包屑导航 */}
      <KnowledgeBreadcrumbs
        kbItems={[
          {
            label: t('chunkPage.knowledgeBase'),
            path: '/knowledge'
          },
          {
            label: knowledgeBase?.name || t('chunkPage.knowledgeBaseDetail'),
            path: `/knowledge/${kb_id}`
          }
        ]}
        extraItems={[
          {
            label: document?.name || t('chunkPage.documentDetail')
          },
        ]}
      />
      {/* 页面标题和文档信息 */}
      <Paper sx={{ p: 3, mb: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
          <Box>
            <Typography variant="h4" gutterBottom>
              {t('chunkPage.documentChunkResult')}
            </Typography>
            <Typography variant="body1" color="text.secondary">
              {t('chunkPage.viewDocument')} "{document?.name}" {t('chunkPage.allChunkData')}
            </Typography>
          </Box>
          <Card>
            <CardContent sx={{ textAlign: 'center' }}>
              <Typography variant="h4" color="primary">
                {total}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {t('chunkPage.totalChunkCount')}
              </Typography>
            </CardContent>
          </Card>
          <Button
            variant="outlined"
            startIcon={<VisibilityIcon />}
            onClick={handleViewFile}
            sx={{ ml: 2 }}
          >
            {t('chunkPage.viewFile')}
          </Button>
        </Box>
      </Paper>

      {/* 搜索框 */}
      <Paper sx={{ p: 3, mb: 3 }}>
        <TextField
          fullWidth
          placeholder={t('chunkPage.searchChunkPlaceholder')}
          value={searchKeyword}
          onChange={(e) => handleSearch(e.target.value)}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
          }}
        />
      </Paper>

      {/* Chunk列表结果 */}
      <ChunkListResult
        doc_id={doc_id}
        chunks={chunks}
        total={total}
        loading={loading}
        error={error}
        page={currentPage}
        pageSize={pageSize}
        onPageChange={setCurrentPage}
        onRefresh={refresh}
        docName={document?.name}
      />
    </Box>
  );
}

export default ChunkParsedResult;