import React, { useState, useEffect } from 'react';
import { Row, Col, Button, Drawer } from 'antd';
import { SettingOutlined } from '@ant-design/icons';
import { FormattedMessage } from 'react-intl';
import { useSelector, useDispatch } from 'react-redux';
import {
  fetchWorkThunk,
  historySelectionSlice,
  historyPaginationSlice,
  historyFiltersSlice,
} from '../../states/patient/worklist/slices/history';
import { updateThumbnailsFromHistorySelection } from '../../states/patient/worklist/slices/thumbnailListSlice';
import WorklistTable from './components/WorklistTable';
import OperationPanel from './components/OperationPanel';
import SendPanel from '../../pages/output/SendPanel';
import ThumbnailList from './components/ThumbnailList';
import GenericPagination from '../../components/GenericPagination';
import PatientPortraitFloat from './components/PatientPortraitFloat';
import { RootState, AppDispatch } from '../../states/store';
import { Task } from '@/domain/work';
import worklistToExam from '../../domain/patient/worklistToExam';
import { ColumnConfig, columnConfigService } from '@/config/tableColumns';
import { useMultiSelection } from '@/hooks/useMultiSelection';
import useEffectiveBreakpoint from '../../hooks/useEffectiveBreakpoint';

const HistorylistPage: React.FC = () => {
  const screens = useEffectiveBreakpoint();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [selectedPatientForPortrait, setSelectedPatientForPortrait] = useState<Task | null>(null); // 照片显示用的选中患者

  const dispatch: AppDispatch = useDispatch();
  const filters = useSelector((state: RootState) => state.historyFilters);
  const page = useSelector((state: RootState) => state.historyPagination.page);
  const pageSize = useSelector(
    (state: RootState) => state.historyPagination.pageSize
  );
  const selectedIds = useSelector(
    (state: RootState) => state.historySelection.selectedIds
  );
  const historylistData = useSelector(
    (state: RootState) => state.historyEntities.data
  );
  const currentPanel = useSelector(
    (state: RootState) => state.historyPanelSwitch.currentPanel
  );
  const productName = useSelector(
    (state: RootState) => state.product.productName
  );
  const [columnConfig, setColumnConfig] = useState<ColumnConfig[]>([]);
  // 获取和应用列配置
  useEffect(() => {
    columnConfigService
      .getColumnConfig('history')
      .then((config) => {
        setColumnConfig(config.columns);
        console.log(`成功为history设置列的配置信息`);
      })
      .catch((error) => {
        console.error('Failed to load history column config:', error);
        // 失败时使用空配置，表格会显示所有列
        setColumnConfig([]);
      });
  }, []);
  // 同步分页状态到过滤器
  useEffect(() => {
    console.log('[historylist] Syncing pagination to filters:', {
      page,
      pageSize,
    });
    dispatch(
      historyFiltersSlice.actions.setFilters({
        page,
        page_size: pageSize,
      })
    );
  }, [dispatch, page, pageSize]);

  useEffect(() => {
    console.log(
      'Fetching historylist data with filters:',
      filters,
      'page:',
      page,
      'pageSize:',
      pageSize
    );
    dispatch(fetchWorkThunk({ page, pageSize, filters }));
  }, [dispatch, filters, page, pageSize]);

  // 使用多选 Hook
  const { handleRowClick } = useMultiSelection({
    selectedIds,
    onSelectionChange: (newIds) => {
      console.log('Selected IDs changed:', newIds);

      // 如果只有一个选中项，设置选中患者用于显示照片
      if (newIds.length === 1) {
        const selectedRecord = historylistData.find(item => item.StudyID === newIds[0]);
        if (selectedRecord) {
          setSelectedPatientForPortrait(selectedRecord);
        }
      } else {
        // 多选时清空患者照片
        setSelectedPatientForPortrait(null);
      }

      // 更新 Redux 状态（用于其他功能）
      dispatch(historySelectionSlice.actions.setSelectedIds(newIds));
      dispatch(updateThumbnailsFromHistorySelection(newIds));
    },
    enableMultiSelect: true,
  });

  // 处理行点击事件（兼容现有功能）
  const handleRowClickInternal = (record: Task, event?: React.MouseEvent) => {
    handleRowClick(record, event || {} as React.MouseEvent);
  };

  const handleRowDoubleClick = (record: Task) => {
    console.log(
      '[WorklistTable] Row double-clicked:',
      JSON.stringify(record, null, 2)
    );
    worklistToExam(record);
  };

  return (
    <div className="h-full">
      {/* 患者照片浮动组件 */}
      <PatientPortraitFloat
        patient={selectedPatientForPortrait}
        onClose={() => setSelectedPatientForPortrait(null)}
      />

      {screens.xs ? (
        <>
          <div className="flex-1 overflow-auto">
            <WorklistTable
              productName={productName}
              columnConfig={columnConfig}
              worklistData={historylistData}
              filters={filters}
              page={page}
              pageSize={pageSize}
              selectedIds={selectedIds}
              handleRowClick={handleRowClickInternal}
              handleRowDoubleClick={handleRowDoubleClick}
            />
          </div>
          <GenericPagination
            paginationSelector={(state) => state.historyPagination}
            entitiesSelector={(state) => state.historyEntities}
            paginationActions={historyPaginationSlice.actions}
            className="border-t"
          />
          <Button
            type="primary"
            shape="circle"
            icon={<SettingOutlined />}
            className="fixed bottom-6 right-6 z-50"
            onClick={() => setDrawerVisible(true)}
          />
          <Drawer
            title={
              <FormattedMessage
                id="worklist.operationPanel"
                defaultMessage="worklist.operationPanel"
              />
            }
            placement="left"
            onClose={() => setDrawerVisible(false)}
            open={drawerVisible}
            width={300}
          >
            {currentPanel === 'OperationPanel' ? (
              <OperationPanel />
            ) : (
              <SendPanel />
            )}
          </Drawer>
        </>
      ) : (
        <Row className="h-full">
          <Col
            span={screens.lg ? 18 : screens.md ? 20 : 24}
            className="h-full flex flex-col"
          >
            <div className="flex-1 flex flex-col h-[80%]">
              <div className="flex-1 overflow-auto h-full">
                <WorklistTable
                  data-testid="worklist-table-from-history-page"
                  productName={productName}
                  columnConfig={columnConfig}
                  worklistData={historylistData}
                  filters={filters}
                  page={page}
                  pageSize={pageSize}
                  selectedIds={selectedIds}
                  handleRowClick={handleRowClickInternal}
                  handleRowDoubleClick={handleRowDoubleClick}
                />
              </div>
              <GenericPagination
                paginationSelector={(state) => state.historyPagination}
                entitiesSelector={(state) => state.historyEntities}
                paginationActions={historyPaginationSlice.actions}
                className="border-t"
              />
            </div>
            <div className=" overflow-auto">
              <ThumbnailList />
            </div>
          </Col>
          <Col
            span={screens.lg ? 6 : screens.md ? 4 : 0}
            className="h-full overflow-auto"
          >
            {currentPanel === 'OperationPanel' ? (
              <OperationPanel />
            ) : (
              <SendPanel />
            )}
          </Col>
        </Row>
      )}
    </div>
  );
};

export default HistorylistPage;
