import React, { useEffect, useState } from 'react';
import { Modal, Button, Input, message, Form } from 'antd';
import { RootState, useAppDispatch, useAppSelector } from '@/states/store';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';

import { createdDepartment, getDepartment } from '@/API/report/ReportActions';
import useIntl from 'react-intl/src/components/useIntl';
import { setDepartments } from '@/states/patient/DiagnosticReport/departmentSlice';

interface DepartmentModalProps {
  visible: boolean;
  onClose: () => void;
}

export const DepartmentModal: React.FC<DepartmentModalProps> = ({
  visible,
  onClose,
}) => {
  const intl = useIntl();
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  const departments = useAppSelector(
    (state: RootState) => state.department.departments
  );

  const getDepartmentData = async () => {
    const res = await getDepartment({});
    if (res.code === '0x000000') {
      dispatch(setDepartments(res?.data?.departments || []));
    }
  };
  const onFinish = async (values: { departments: string[] }) => {
    // 防止重复提交
    if (submitting) return;

    setSubmitting(true);
    try {
      const res = await createdDepartment(values);
      if (res.code === '0x000000') {
        await getDepartmentData();
        onClose();
        message.success(
          intl.formatMessage({ id: 'report.department.saveSuccess' })
        );
      } else {
        message.error(intl.formatMessage({ id: 'report.department.saveFail' }));
      }
    } catch {
      message.error(intl.formatMessage({ id: 'report.department.saveFail' }));
    } finally {
      setSubmitting(false);
    }
  };

  useEffect(() => {
    if (visible) {
      form.setFieldsValue({
        departments: departments.map((k) => k.department),
      });
    }
  }, [visible]);

  return (
    <Modal
      title={intl.formatMessage({
        id: 'report.department.title',
      })}
      centered
      closable={false}
      open={visible}
      maskClosable={false}
      destroyOnHidden
      onCancel={onClose}
      okText={intl.formatMessage({ id: 'report.department.okButtonText' })}
      cancelText={intl.formatMessage({
        id: 'report.department.cancelButtonText',
      })}
      styles={{ body: { maxHeight: '50vh', overflow: 'auto' } }}
      okButtonProps={{
        autoFocus: true,
        htmlType: 'submit',
        loading: submitting,
        style: { marginRight: '50px' },
      }}
      modalRender={(dom) => (
        <Form layout="vertical" form={form} clearOnDestroy onFinish={onFinish}>
          {dom}
        </Form>
      )}
    >
      <Form.List name="departments">
        {(fields, { add, remove }) => (
          <>
            {fields.map((field) => (
              <Form.Item label={''} required={false} key={field.key}>
                <Form.Item
                  {...field}
                  validateTrigger={['onChange', 'onBlur']}
                  rules={[
                    {
                      required: true,
                      whitespace: true,
                      message: intl.formatMessage({
                        id: 'report.department.inputEmptyCheck',
                      }),
                    },
                  ]}
                  noStyle
                >
                  <Input
                    placeholder={intl.formatMessage({
                      id: 'report.department.placeholder',
                    })}
                    style={{ width: '90%' }}
                  />
                </Form.Item>
                <MinusCircleOutlined
                  style={{
                    position: 'relative',
                    top: '4px',
                    margin: '0 8px',
                    color: '#999',
                    fontSize: '24px',
                    cursor: 'pointer',
                  }}
                  onClick={() => remove(field.name)}
                />
              </Form.Item>
            ))}
            <Form.Item>
              <Button
                // disabled={fields.length >= 6}
                type="dashed"
                onClick={() => add()}
                style={{ width: '90%' }}
                icon={<PlusOutlined />}
              >
                {intl.formatMessage({ id: 'report.department.addButtonText' })}
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
    </Modal>
  );
};
