import React from 'react';
import {
  Row,
  Col,
  Collapse,
  Grid,
  Divider,
  Button,
  Space,
  Form,
  message,
} from 'antd';
import { FormattedMessage } from 'react-intl';
import BasicInfoForm from './components/register.form';
import SelectedProtocolList from './components/register.selected.view.list';
import RegisterAvailableList from './components/register.available.list';
import {
  RegisterInfo,
  registerWork,
  RegisterWorkResponse,
  RegisterWorkResponseData,
} from '@/API/patient/workActions';
import useRegisterState from '@/hooks/useRegisterState';
import registerformSchema from '@/validation/patient/registerSchema';
import registerToExam from '@/domain/patient/registerToExam';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { View } from '@/API/patient/viewActions';
dayjs.extend(utc);

const { useBreakpoint } = Grid;
const { Panel } = Collapse;

const RegisterPage: React.FC = () => {
  const screens = useBreakpoint();
  const [form] = Form.useForm();
  const { selectedViews, currentPatientType } = useRegisterState();

  const handleRegister = async (): Promise<{
    success: boolean;

    data?: RegisterWorkResponseData;
    views?: View[];
  }> => {
    try {
      let values = form.getFieldsValue();
      const formatDob = values.patient_dob
        ? dayjs.utc(values.patient_dob).format('YYYY-MM-DDTHH:mm:ss.SSS[Z]') //values.patient_dob.toString('YYYY-MM-DD[T00:00:00.000000Z]')
        : '';
      console.log(`转换后的日期：${formatDob}`);

      values = { ...values, patient_dob: formatDob };
      console.log(`${JSON.stringify(values, null, 2)}`);

      const validateResult = registerformSchema.safeParse(values);
      if (!validateResult.success) {
        message.error(`必填项未填写或者不合规则`);
        // todo 更详细和人性化的提示
        // message.error(JSON.stringify(validateResult.error, null, 2));
        console.log(JSON.stringify(validateResult.error, null, 2));

        return { success: false, views: [] as [] };
      }
      const registerInfo: RegisterInfo = {
        ...values,
        patient_type: currentPatientType?.patient_type_id,
        modality: 'dx',
        study_type: 'Normal',
        views: selectedViews.map((view) => ({
          view_id: view.view_id,
          procedure_id: view.procedure_id,
        })),
      };
      const response: RegisterWorkResponse = await registerWork(registerInfo);
      console.log('Work registered successfully:', response);
      message.info('Work registered successfully');
      return { success: true, data: response.data, views: selectedViews };
    } catch (error) {
      console.error('Error registering work:', error);
      message.error(
        'Error registering work, please check the console for details.'
      );
      return { success: false, views: [] };
    }
  };

  return (
    <>
      {screens.xl || screens.xxl ? (
        <Row className="flex-1 h-full">
          <Col
            xs={24}
            sm={24}
            md={8}
            lg={8}
            xl={8}
            xxl={8}
            style={{
              display: 'flex',
              flexDirection: 'column',
            }}
            className="h-full px-4"
          >
            <BasicInfoForm form={form} style={{ overflow: 'auto' }} />
          </Col>
          <Col xs={24} sm={24} md={8} lg={8} xl={8} xxl={8} className="h-full">
            <RegisterAvailableList />
          </Col>
          <Col xs={24} sm={24} md={8} lg={8} xl={8} xxl={8} className="h-full">
            <SelectedProtocolList />
          </Col>
        </Row>
      ) : screens.md || screens.lg ? (
        <Row className="h-full flex-1 ">
          <Col
            xs={24}
            sm={24}
            md={12}
            lg={12}
            className="h-full flex flex-column"
          >
            <BasicInfoForm
              form={form}
              style={{ overflow: 'auto', width: '100%' }}
            />
          </Col>
          <Col xs={24} sm={24} md={12} lg={12}>
            <Row gutter={[0, 16]}>
              <Col span={24}>
                <RegisterAvailableList />
              </Col>
              <Divider />
              <Col span={24}>
                <SelectedProtocolList className="" />
              </Col>
            </Row>
          </Col>
        </Row>
      ) : (
        <Collapse
          accordion
          defaultActiveKey={['1']}
          style={{ overflow: 'auto', height: '100%' }}
        >
          <Panel
            header={
              <FormattedMessage
                id="register.basicInfoPanel"
                defaultMessage="register.basicInfoPanel"
              />
            }
            key="1"
          >
            <BasicInfoForm form={form} />
          </Panel>
          <Panel
            header={
              <FormattedMessage
                id="register.protocolListPanel"
                defaultMessage="register.protocolListPanel"
              />
            }
            key="2"
          >
            <RegisterAvailableList />
          </Panel>
          <Panel
            header={
              <FormattedMessage
                id="register.selectedProtocolListPanel"
                defaultMessage="register.selectedProtocolListPanel"
              />
            }
            key="3"
          >
            <SelectedProtocolList />
          </Panel>
        </Collapse>
      )}
      <Space
        style={{
          position: 'fixed',
          bottom: '20px',
          right: '20px',
          zIndex: 1000,
        }}
      >
        <Button type="primary" onClick={handleRegister}>
          注册
        </Button>
        <Button
          type="default"
          onClick={async () => {
            const registerResult = await handleRegister();
            if (registerResult.success && registerResult.data) {
              await registerToExam(registerResult.data);
            }
          }}
        >
          检查
        </Button>
      </Space>
    </>
  );
};

export default RegisterPage;
