import React, { useState, useEffect } from 'react';
import { Row, Col, Button, Drawer, Grid } from 'antd';
import { SettingOutlined } from '@ant-design/icons';
import { FormattedMessage } from 'react-intl';
import WorklistTable from './components/WorklistTable';
import BinOperationPanel from './components/BinOperationPanel';
import GenericPagination from '../../components/GenericPagination';
import PatientPortraitFloat from './components/PatientPortraitFloat';
import { useAppDispatch, useAppSelector } from '../../states/store';
import {
  fetchBinThunk,
  binSelectionSlice,
  binPaginationSlice,
  binFiltersSlice,
} from '../../states/patient/bin/slices/binSlice';
import { fetchDiskInfoThunk } from '../../states/patient/bin/slices/binDiskInfoSlice';
import { Task } from '@/domain/work';

const { useBreakpoint } = Grid;

const BinPage: React.FC = () => {
  const screens = useBreakpoint();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [selectedPatientForPortrait, setSelectedPatientForPortrait] =
    useState<Task | null>(null);
  const dispatch = useAppDispatch();

  // 从Redux获取状态
  const binData = useAppSelector((state) => state.binEntities.data);
  const page = useAppSelector((state) => state.binPagination.page);
  const pageSize = useAppSelector((state) => state.binPagination.pageSize);
  const filters = useAppSelector((state) => state.binFilters);
  const selectedIds = useAppSelector((state) => state.binSelection.selectedIds);

  // 初始加载数据
  useEffect(() => {
    console.log('Bin页面加载，获取回收站数据');
    dispatch(fetchBinThunk({ page, pageSize, filters }));
    dispatch(fetchDiskInfoThunk());
  }, []);

  // 监听filters和分页变化，重新获取数据
  useEffect(() => {
    console.log('回收站过滤条件或分页变化，重新获取数据');
    dispatch(fetchBinThunk({ page, pageSize, filters }));
  }, [filters, page, pageSize, dispatch]);

  // 同步分页到filters
  useEffect(() => {
    dispatch(
      binFiltersSlice.actions.setFilters({
        page,
        page_size: pageSize,
      })
    );
  }, [dispatch, page, pageSize]);

  // 处理行点击事件
  const handleRowClick = (record: Task) => {
    const studyId = record.StudyID;
    const newSelectedIds = [studyId];

    // 设置选中患者用于显示照片
    setSelectedPatientForPortrait(record);

    // 更新 Redux 状态
    dispatch(binSelectionSlice.actions.setSelectedIds(newSelectedIds));
  };

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

      {screens.xs ? (
        <>
          <div className="flex-1 overflow-auto">
            <WorklistTable
              columnConfig={[]}
              worklistData={binData}
              filters={filters}
              page={page}
              pageSize={pageSize}
              selectedIds={selectedIds}
              handleRowClick={handleRowClick}
              handleRowDoubleClick={() => {}}
            />
          </div>
          <GenericPagination
            paginationSelector={(state) => state.binPagination}
            entitiesSelector={(state) => state.binEntities}
            paginationActions={binPaginationSlice.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="bin.operationPanel"
                defaultMessage="Operation Panel"
              />
            }
            placement="left"
            onClose={() => setDrawerVisible(false)}
            open={drawerVisible}
            width={300}
          >
            <BinOperationPanel />
          </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">
              <div className="flex-1 overflow-auto">
                <WorklistTable
                  columnConfig={[]}
                  worklistData={binData}
                  filters={filters}
                  page={page}
                  pageSize={pageSize}
                  selectedIds={selectedIds}
                  handleRowClick={handleRowClick}
                  handleRowDoubleClick={() => {}}
                />
              </div>
              <GenericPagination
                paginationSelector={(state) => state.binPagination}
                entitiesSelector={(state) => state.binEntities}
                paginationActions={binPaginationSlice.actions}
                className="border-t"
              />
            </div>
          </Col>
          <Col
            span={screens.lg ? 6 : screens.md ? 4 : 0}
            className="h-full overflow-auto"
          >
            <BinOperationPanel />
          </Col>
        </Row>
      )}
    </div>
  );
};

export default BinPage;
