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 { useRisAutoSync } from '@/hooks/useRisAutoSync';
import {
  fetchWorkThunk,
  workSelectionSlice,
  workPaginationSlice,
  workFiltersSlice,
} from '../../states/patient/worklist/slices/workSlice';
import { updateThumbnailsFromWorkSelection } from '../../states/patient/worklist/slices/thumbnailListSlice';
import WorklistTable from './components/WorklistTable';
import OperationPanel from './components/OperationPanel';
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 { saveRisData } from '../../domain/patient/risSaveLogic';
import { columnConfigService } from '@/config/tableColumns';
import { ColumnConfig } from '@/config/tableColumns/types/columnConfig';
import { useMultiSelection } from '@/hooks/useMultiSelection';
import AppendViewModal from '../exam/components/AppendViewModal';
import useEffectiveBreakpoint from '../../hooks/useEffectiveBreakpoint';

const WorklistPage: React.FC = () => {
  const screens = useEffectiveBreakpoint();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [columnConfig, setColumnConfig] = useState<ColumnConfig[]>([]); // 新增：列配置状态
  const [selectedPatientForPortrait, setSelectedPatientForPortrait] = useState<Task | null>(null); // 照片显示用的选中患者
  const [isAppendModalOpen, setIsAppendModalOpen] = useState(false); // 追加体位模态框状态
  const [currentStudy, setCurrentStudy] = useState<Task | null>(null); // 当前保存的study信息

  // 启用RIS自动同步（在后台静默运行）
  useRisAutoSync();

  const dispatch: AppDispatch = useDispatch();
  const filters = useSelector((state: RootState) => state.workFilters);
  const page = useSelector((state: RootState) => state.workPagination.page);
  const pageSize = useSelector(
    (state: RootState) => state.workPagination.pageSize
  );
  const selectedIds = useSelector(
    (state: RootState) => state.workSelection.selectedIds
  );
  const selectedSecondaryIds = useSelector(  // 获取次要选中ID列表
    (state: RootState) => state.workSelection.selectedSecondaryIds
  );
  const worklistData = useSelector(
    (state: RootState) => state.workEntities.data
  );
  const productName = useSelector(
    (state: RootState) => state.product.productName
  );

  // 新增：获取列配置
  useEffect(() => {
    columnConfigService
      .getColumnConfig('worklist')
      .then((config) => {
        setColumnConfig(config.columns);
      })
      .catch((error) => {
        console.error('Failed to load worklist column config:', error);
        // 失败时使用空配置，表格会显示所有列
        setColumnConfig([]);
      });
  }, []);

  // 同步分页状态到过滤器
  useEffect(() => {
    console.log('[worklist] Syncing pagination to filters:', {
      page,
      pageSize,
    });
    dispatch(
      workFiltersSlice.actions.setFilters({
        page,
        page_size: pageSize,
      })
    );
  }, [dispatch, page, pageSize]);

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

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

      // 如果只有一个选中项，设置选中患者用于显示照片
      if (newIds.length === 1) {
        const selectedRecord = worklistData.find(item =>
          !item.entry_id &&                    // 只处理本地数据（不是RIS数据）
          item.StudyID === newIds[0] &&        // StudyID匹配
          newIds[0]                           // 确保StudyID不为空
        );
        if (selectedRecord) {
          setSelectedPatientForPortrait(selectedRecord);
        }
      } else {
        // 多选时清空患者照片
        setSelectedPatientForPortrait(null);
      }

      // 更新 Redux 状态（用于其他功能）
      dispatch(workSelectionSlice.actions.setSelectedIds(newIds));
      dispatch(workSelectionSlice.actions.setSelectedSecondaryIds(secondNewIds ?? []));
      dispatch(updateThumbnailsFromWorkSelection(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)
    );

    // 判断是否为RIS数据
    if (record.entry_id) {
      // RIS数据：触发保存到本地，保存成功后打开追加体位对话框
      saveRisData(record.entry_id, (task) => {
        console.log('[WorklistPage] RIS数据保存成功，Study ID:', task.StudyID, '打开追加体位对话框');
        setCurrentStudy(task);
        setIsAppendModalOpen(true);
      });
    } else {
      // 本地study数据：进入检查
      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={worklistData}
              filters={filters}
              page={page}
              pageSize={pageSize}
              selectedIds={selectedIds}
              selectedSecondaryIds={selectedSecondaryIds}  // 新增
              handleRowClick={handleRowClickInternal}
              handleRowDoubleClick={handleRowDoubleClick}
            />
          </div>
          <GenericPagination
            paginationSelector={(state) => state.workPagination}
            entitiesSelector={(state) => state.workEntities}
            paginationActions={workPaginationSlice.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}
          >
            <OperationPanel />
          </Drawer>
        </>
      ) : (
        <Row className="h-full">
          <Col
            span={screens.lg ? 18 : screens.md ? 20 : 24}
            className="h-full flex flex-col"
          >
            <div className="flex flex-col h-[80%]">
              <div className="overflow-auto flex flex-col">
                <WorklistTable
                  productName={productName}
                  columnConfig={columnConfig}
                  worklistData={worklistData}
                  filters={filters}
                  page={page}
                  pageSize={pageSize}
                  selectedIds={selectedIds}
                  selectedSecondaryIds={selectedSecondaryIds}  // 新增
                  handleRowClick={handleRowClickInternal}
                  handleRowDoubleClick={handleRowDoubleClick}
                  className='flex-1 overflow-auto'
                />
              </div>
              <GenericPagination
                paginationSelector={(state) => state.workPagination}
                entitiesSelector={(state) => state.workEntities}
                paginationActions={workPaginationSlice.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"
          >
            <OperationPanel />
          </Col>
        </Row>
      )}

      {/* 追加体位模态框 */}
      <AppendViewModal
        open={isAppendModalOpen}
        onCancel={() => {
          setIsAppendModalOpen(false);
          setCurrentStudy(null); // 关闭时清空study信息
        }}
        studyId={currentStudy?.StudyID}
        currentWork={currentStudy}
        onSuccess={() => {
          setIsAppendModalOpen(false);
          // 追加成功后选中该study，然后进入检查
          if (currentStudy) {
            const studyId = currentStudy.StudyID;
            const entryId = currentStudy.entry_id;

            // 更新选中状态
            dispatch(workSelectionSlice.actions.setSelectedIds([studyId]));
            dispatch(workSelectionSlice.actions.setSelectedSecondaryIds(entryId ? [entryId] : []));

            console.log('[WorklistPage] 追加成功，选中study:', studyId, '进入检查');
            worklistToExam(currentStudy);
          }
        }}
      />
    </div>
  );
};

export default WorklistPage;
