import React, { useState } from 'react';
import { Table, TableColumnsType } from 'antd';
import { FormattedMessage } from 'react-intl';
import { Task, Task as DataType } from '@/domain/work';
import type { ResizeCallbackData } from 'react-resizable';
import { Resizable } from 'react-resizable';
import { WorkFilter } from '@/states/patient/worklist/types/workfilter';

const columnsDef = [
  {
    title: (
      <FormattedMessage
        id="worklistTable.StudyInstanceUID"
        defaultMessage="worklistTable.StudyInstanceUID"
      />
    ),
    dataIndex: 'StudyInstanceUID',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.StudyID"
        defaultMessage="worklistTable.StudyID"
      />
    ),
    dataIndex: 'StudyID',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.SpecificCharacterSet"
        defaultMessage="worklistTable.SpecificCharacterSet"
      />
    ),
    dataIndex: 'SpecificCharacterSet',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.AccessionNumber"
        defaultMessage="worklistTable.AccessionNumber"
      />
    ),
    dataIndex: 'AccessionNumber',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.PatientID"
        defaultMessage="worklistTable.PatientID"
      />
    ),
    dataIndex: 'PatientID',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.PatientName"
        defaultMessage="worklistTable.PatientName"
      />
    ),
    dataIndex: 'PatientName',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.DisplayPatientName"
        defaultMessage="worklistTable.DisplayPatientName"
      />
    ),
    dataIndex: 'DisplayPatientName',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.PatientSize"
        defaultMessage="worklistTable.PatientSize"
      />
    ),
    dataIndex: 'PatientSize',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.PatientAge"
        defaultMessage="worklistTable.PatientAge"
      />
    ),
    dataIndex: 'PatientAge',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.PatientSex"
        defaultMessage="worklistTable.PatientSex"
      />
    ),
    dataIndex: 'PatientSex',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.AdmittingTime"
        defaultMessage="worklistTable.AdmittingTime"
      />
    ),
    dataIndex: 'AdmittingTime',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.RegSource"
        defaultMessage="worklistTable.RegSource"
      />
    ),
    dataIndex: 'RegSource',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.StudyStatus"
        defaultMessage="worklistTable.StudyStatus"
      />
    ),
    dataIndex: 'StudyStatus',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.RequestedProcedureID"
        defaultMessage="worklistTable.RequestedProcedureID"
      />
    ),
    dataIndex: 'RequestedProcedureID',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.PerformedProtocolCodeValue"
        defaultMessage="worklistTable.PerformedProtocolCodeValue"
      />
    ),
    dataIndex: 'PerformedProtocolCodeValue',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.PerformedProtocolCodeMeaning"
        defaultMessage="worklistTable.PerformedProtocolCodeMeaning"
      />
    ),
    dataIndex: 'PerformedProtocolCodeMeaning',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.PerformedProcedureStepID"
        defaultMessage="worklistTable.PerformedProcedureStepID"
      />
    ),
    dataIndex: 'PerformedProcedureStepID',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.StudyDescription"
        defaultMessage="worklistTable.StudyDescription"
      />
    ),
    dataIndex: 'StudyDescription',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.StudyStartDatetime"
        defaultMessage="worklistTable.StudyStartDatetime"
      />
    ),
    dataIndex: 'StudyStartDatetime',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.ScheduledProcedureStepStartDate"
        defaultMessage="worklistTable.ScheduledProcedureStepStartDate"
      />
    ),
    dataIndex: 'ScheduledProcedureStepStartDate',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.StudyLock"
        defaultMessage="worklistTable.StudyLock"
      />
    ),
    dataIndex: 'StudyLock',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.OperatorID"
        defaultMessage="worklistTable.OperatorID"
      />
    ),
    dataIndex: 'OperatorID',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.Modality"
        defaultMessage="worklistTable.Modality"
      />
    ),
    dataIndex: 'Modality',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.Views"
        defaultMessage="worklistTable.Views"
      />
    ),
    dataIndex: 'Views',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.Thickness"
        defaultMessage="worklistTable.Thickness"
      />
    ),
    dataIndex: 'Thickness',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.PatientType"
        defaultMessage="worklistTable.PatientType"
      />
    ),
    dataIndex: 'PatientType',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.StudyType"
        defaultMessage="worklistTable.StudyType"
      />
    ),
    dataIndex: 'StudyType',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.QRCode"
        defaultMessage="worklistTable.QRCode"
      />
    ),
    dataIndex: 'QRCode',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.IsExported"
        defaultMessage="worklistTable.IsExported"
      />
    ),
    dataIndex: 'IsExported',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.IsEdited"
        defaultMessage="worklistTable.IsEdited"
      />
    ),
    dataIndex: 'IsEdited',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.WorkRef"
        defaultMessage="worklistTable.WorkRef"
      />
    ),
    dataIndex: 'WorkRef',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.IsAppended"
        defaultMessage="worklistTable.IsAppended"
      />
    ),
    dataIndex: 'IsAppended',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.CreationTime"
        defaultMessage="worklistTable.CreationTime"
      />
    ),
    dataIndex: 'CreationTime',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.MappedStatus"
        defaultMessage="worklistTable.MappedStatus"
      />
    ),
    dataIndex: 'MappedStatus',
  },
  {
    title: (
      <FormattedMessage
        id="worklistTable.IsDelete"
        defaultMessage="worklistTable.IsDelete"
      />
    ),
    dataIndex: 'IsDelete',
  },
];

interface TitlePropsType {
  width: number;
  onResize: (
    e: React.SyntheticEvent<Element>,
    data: ResizeCallbackData
  ) => void;
}

const ResizableTitle: React.FC<
  Readonly<
    React.HTMLAttributes<HTMLTableCellElement | Resizable> & TitlePropsType
  >
> = (props) => {
  const { onResize, width, ...restProps } = props;

  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable
      width={width}
      height={0}
      minConstraints={[50, 0]} // 最小宽度 50px
      // maxConstraints={[500, 0]} // 最大宽度 500px
      handle={
        <span
          style={{
            position: 'absolute',
            right: '-5px', // 或 insetInlineEnd: "-5px"（支持逻辑属性）
            bottom: '0',
            zIndex: 1,
            width: '10px',
            height: '100%',
            cursor: 'col-resize',
          }}
          onClick={(e) => e.stopPropagation()}
        />
      }
      onResize={onResize}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th {...restProps} />
    </Resizable>
  );
};

interface WorklistTableProps {
  worklistData: Task[];
  filters?: WorkFilter;
  page?: number;
  pageSize?: number;
  selectedIds: string[];
  handleRowClick: (record: Task) => void;
  handleRowDoubleClick: (record: Task) => void;
}

const WorklistTable: React.FC<WorklistTableProps> = ({
  worklistData,
  // filters,
  // page,
  // pageSize,
  selectedIds,
  handleRowClick,
  handleRowDoubleClick,
}) => {
  const [columns, setColumns] = useState<TableColumnsType<DataType>>(
    columnsDef.map((col) => ({
      ...col,
      width: 150, // 默认宽度
    }))
  );

  const handleResize =
    (index: number) =>
    (_: React.SyntheticEvent<Element>, { size }: ResizeCallbackData) => {
      console.log('Resizing column:', index, size);
      const newColumns = [...columns];
      newColumns[index] = {
        ...newColumns[index],
        width: size.width,
      };
      setColumns(newColumns);
    };

  const mergedColumns = columns.map<TableColumnsType<DataType>[number]>(
    (col, index) => ({
      ...col,
      onHeaderCell: (column: TableColumnsType<DataType>[number]) => ({
        width: column.width,
        onResize: handleResize(index) as React.ReactEventHandler<HTMLElement>,
        style: { whiteSpace: 'nowrap' },
      }),
      onCell: () => ({ style: { whiteSpace: 'nowrap' } }),
    })
  );

  return (
    <Table<DataType>
      bordered
      className="px-4"
      columns={mergedColumns}
      scroll={{ x: 'max-content' }}
      components={{ header: { cell: ResizableTitle } }}
      dataSource={worklistData}
      rowKey="StudyID"
      onRow={(record) => ({
        onClick: () => handleRowClick(record),
        onDoubleClick: () => handleRowDoubleClick(record),
      })}
      rowHoverable={false}
      rowClassName={(record) =>
        selectedIds.includes(record.StudyID)
          ? 'bg-yellow-500 hover:bg-yellow-800'
          : ''
      }
    />
  );
};

export default WorklistTable;
