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 { useSelector, useDispatch } from 'react-redux';
import {
  fetchWorkThunk,
  workSelectionSlice,
} from '../../states/patient/worklist/slices/workSlice';
import WorklistTable from './components/WorklistTable';
import OperationPanel from './components/OperationPanel';
import { RootState, AppDispatch } from '../../states/store';
import { Task } from '@/domain/work';
import worklistToExam from '../../domain/patient/worklistToExam';

const { useBreakpoint } = Grid;

const WorklistPage: React.FC = () => {
  const screens = useBreakpoint();
  const [drawerVisible, setDrawerVisible] = useState(false);

  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 worklistData = useSelector(
    (state: RootState) => state.workEntities.data
  );

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

  const handleRowClick = (record: Task) => {
    console.log('Row clicked:', JSON.stringify(record, null, 2));
    console.log('Selected IDs before:', record.StudyInstanceUID);
    dispatch(
      workSelectionSlice.actions.setSelectedIds([record.StudyInstanceUID])
    );
  };

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

  return (
    <div className="h-full">
      {screens.xs ? (
        <>
          <WorklistTable
            worklistData={worklistData}
            filters={filters}
            page={page}
            pageSize={pageSize}
            selectedIds={selectedIds}
            handleRowClick={handleRowClick}
            handleRowDoubleClick={handleRowDoubleClick}
          />
          <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="overflow-auto"
          >
            <WorklistTable
              worklistData={worklistData}
              filters={filters}
              page={page}
              pageSize={pageSize}
              selectedIds={selectedIds}
              handleRowClick={handleRowClick}
              handleRowDoubleClick={handleRowDoubleClick}
            />
          </Col>
          <Col
            span={screens.lg ? 6 : screens.md ? 4 : 0}
            className="h-full overflow-auto"
          >
            <OperationPanel />
          </Col>
        </Row>
      )}
    </div>
  );
};

export default WorklistPage;
