import React, { useEffect, useState } from 'react';
import {
  ModalForm,
  ProForm,
  ProFormDatePicker,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Divider, Form, Input, Modal, Space } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type {
  VenueInfoDictForm,
  VenueInfoForm,
  VenueInfoItem,
} from '@/services/jobportal/venueInfo';

interface EditModalProps {
  open: boolean;
  values?: VenueInfoItem;
  venueTypeOptions: any[];
  lineOptions: any[];
  defaultHandler?: string;
  onCreateDictOption: (values: VenueInfoDictForm) => Promise<boolean>;
  onCancel: () => void;
  onSubmit: (values: VenueInfoForm) => Promise<void>;
}

const VENUE_TYPE_DICT = 'venue_info_type';

const splitRouteLineIds = (routeLineIds?: string) => {
  if (!routeLineIds) {
    return [];
  }
  return routeLineIds
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean);
};

const EditModal: React.FC<EditModalProps> = ({
  open,
  values,
  venueTypeOptions,
  lineOptions,
  defaultHandler,
  onCreateDictOption,
  onCancel,
  onSubmit,
}) => {
  const [form] = Form.useForm();
  const [dictModalOpen, setDictModalOpen] = useState(false);
  const [dictInputValue, setDictInputValue] = useState('');
  const [dictSubmitLoading, setDictSubmitLoading] = useState(false);

  useEffect(() => {
    if (open) {
      form.resetFields();
      if (values) {
        form.setFieldsValue({
          ...values,
          routeLineIds: splitRouteLineIds(values.routeLineIds),
        });
      } else {
        form.setFieldsValue({
          handleDate: new Date(),
          handler: defaultHandler,
        });
      }
    }
  }, [open, values, defaultHandler, form]);

  const renderVenueTypeDropdown = (menu: React.ReactElement): React.ReactElement => (
    <>
      {menu}
      <Divider style={{ margin: '8px 0' }} />
      <Space style={{ padding: '0 8px 8px' }}>
        <Button
          type="link"
          icon={<PlusOutlined />}
          onMouseDown={(event) => event.preventDefault()}
          onClick={() => {
            setDictInputValue('');
            setDictModalOpen(true);
          }}
        >
          新增场地类型
        </Button>
      </Space>
    </>
  );

  const handleDictModalOk = async () => {
    const dictLabel = dictInputValue.trim();
    if (!dictLabel) {
      return;
    }
    setDictSubmitLoading(true);
    try {
      const success = await onCreateDictOption({
        dictType: VENUE_TYPE_DICT,
        dictLabel,
      });
      if (success) {
        form.setFieldValue('venueType', dictLabel);
        setDictModalOpen(false);
      }
    } finally {
      setDictSubmitLoading(false);
    }
  };

  return (
    <ModalForm
      title={values ? '编辑场地' : '添加场地'}
      form={form}
      open={open}
      width={900}
      modalProps={{ destroyOnClose: true, onCancel }}
      onFinish={async (formValues) => {
        const selectedLineIds = (formValues.routeLineIds || []) as string[];
        const selectedLineNames = lineOptions
          .filter((option) => selectedLineIds.includes(String(option.value)))
          .map((option) => option.label)
          .join(',');
        await onSubmit({
          ...formValues,
          id: values?.id,
          routeLineIds: selectedLineIds,
          routeLineNames: selectedLineNames,
        } as VenueInfoForm);
      }}
    >
      <ProFormText name="id" hidden />
      <ProForm.Group>
        <ProFormSelect
          name="venueType"
          label="场地类型"
          width="md"
          options={venueTypeOptions}
          fieldProps={{
            showSearch: true,
            dropdownRender: renderVenueTypeDropdown,
          }}
          rules={[{ required: true, message: '请选择场地类型' }]}
          placeholder="请选择场地类型"
        />
        <ProFormText
          name="venueName"
          label="场地名称"
          width="md"
          rules={[{ required: true, message: '请输入场地名称' }]}
          placeholder="请输入场地名称"
        />
        <ProFormDigit
          name="venueArea"
          label="场地面积"
          width="sm"
          min={0}
          fieldProps={{ precision: 2 }}
          placeholder="请输入场地面积"
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormDigit
          name="floorCount"
          label="展位数量"
          width="md"
          min={0}
          fieldProps={{ precision: 0 }}
          placeholder="请输入展位数量"
        />
        <ProFormText name="contactPhone" label="联系电话" width="md" placeholder="请输入联系电话" />
      </ProForm.Group>
      <ProFormText
        name="venueAddress"
        label="场地地址"
        rules={[{ required: true, message: '请输入场地地址' }]}
        placeholder="请输入场地地址"
      />
      <ProFormSelect
        name="routeLineIds"
        label="乘坐线路"
        mode="multiple"
        options={lineOptions}
        fieldProps={{
          showSearch: true,
          optionFilterProp: 'label',
        }}
        placeholder="请选择乘坐线路"
      />
      <ProFormTextArea
        name="remark"
        label="备注"
        fieldProps={{ maxLength: 100, showCount: true }}
        placeholder="请输入备注"
      />
      <ProForm.Group>
        <ProFormDatePicker
          name="handleDate"
          label="经办日期"
          width="md"
          fieldProps={{ format: 'YYYY-MM-DD' }}
        />
        <ProFormText name="handleOrg" label="经办机构" width="md" placeholder="请输入经办机构" />
        <ProFormText name="handler" label="经办人" width="md" placeholder="请输入经办人" />
      </ProForm.Group>
      <Modal
        title="新增场地类型"
        open={dictModalOpen}
        confirmLoading={dictSubmitLoading}
        onOk={handleDictModalOk}
        onCancel={() => setDictModalOpen(false)}
        okButtonProps={{ disabled: !dictInputValue.trim() }}
        destroyOnClose
      >
        <Input
          value={dictInputValue}
          maxLength={100}
          showCount
          placeholder="请输入场地类型"
          onChange={(event) => setDictInputValue(event.target.value)}
          onPressEnter={handleDictModalOk}
        />
      </Modal>
    </ModalForm>
  );
};

export default EditModal;
