import React, { useEffect } from 'react';
import type { Dayjs } from 'dayjs';
import { Button, Col, DatePicker, Form, Input, Modal, Row, Select, Space } from 'antd';
import type {
  RecruitmentFairExportChannel,
  RecruitmentFairExportParams,
  RecruitmentFairExportType,
} from '@/services/jobfair/recruitmentFairExport';

const { RangePicker } = DatePicker;

interface Option {
  label?: React.ReactNode;
  text?: React.ReactNode;
  value: string | number | boolean;
}

interface FormValues {
  exportType: RecruitmentFairExportType;
  title?: string;
  hostUnit?: string;
  fairType?: string;
  region?: string;
  venueId?: number;
  address?: string;
  startRange?: [Dayjs, Dayjs];
  endRange?: [Dayjs, Dayjs];
  applyRange?: [Dayjs, Dayjs];
  createRange?: [Dayjs, Dayjs];
  fairStatus?: RecruitmentFairExportParams['fairStatus'];
  isCrossDomain?: string;
  onlineApply?: boolean;
  reviewStatus?: RecruitmentFairExportParams['reviewStatus'];
}

interface Props {
  open: boolean;
  channel: RecruitmentFairExportChannel;
  fairTypeOptions?: Option[];
  regionOptions?: Option[];
  venueOptions?: Option[];
  onCancel: () => void;
  onExport: (params: RecruitmentFairExportParams) => Promise<void>;
}

const toOptions = (options: Option[] = []) =>
  options.map((item) => ({
    label: item.label ?? item.text,
    value: item.value,
  }));

const dateRange = (range?: [Dayjs, Dayjs]) =>
  range
    ? {
        start: range[0].format('YYYY-MM-DD HH:mm:ss'),
        end: range[1].format('YYYY-MM-DD HH:mm:ss'),
      }
    : undefined;

const FairExportModal: React.FC<Props> = ({
  open,
  channel,
  fairTypeOptions,
  regionOptions,
  venueOptions,
  onCancel,
  onExport,
}) => {
  const [form] = Form.useForm<FormValues>();
  const isOnline = channel === 'online';

  useEffect(() => {
    if (open) {
      form.resetFields();
      form.setFieldsValue({ exportType: 'companies' });
    }
  }, [form, open]);

  const submit = async (values: FormValues) => {
    const start = dateRange(values.startRange);
    const end = dateRange(values.endRange);
    const apply = dateRange(values.applyRange);
    const create = dateRange(values.createRange);
    await onExport({
      exportType: values.exportType,
      title: values.title?.trim() || undefined,
      hostUnit: values.hostUnit?.trim() || undefined,
      fairType: values.fairType,
      region: values.region,
      venueId: values.venueId,
      address: values.address?.trim() || undefined,
      startTime: start?.start,
      endTime: end?.end,
      applyStartTime: apply?.start,
      applyEndTime: apply?.end,
      createStartTime: create?.start,
      createEndTime: create?.end,
      fairStatus: values.fairStatus,
      isCrossDomain: isOnline ? values.isCrossDomain : undefined,
      onlineApply: isOnline ? undefined : values.onlineApply,
      reviewStatus: values.reviewStatus,
    });
  };

  return (
    <Modal
      title={`${isOnline ? '线上' : '户外'}招聘会参会数据导出`}
      open={open}
      width={820}
      destroyOnClose
      footer={null}
      onCancel={onCancel}
    >
      <Form<FormValues>
        form={form}
        layout="vertical"
        initialValues={{ exportType: 'companies' }}
        onFinish={submit}
      >
        <Form.Item
          label="导出内容"
          name="exportType"
          rules={[{ required: true, message: '请选择导出内容' }]}
        >
          <Select
            options={[
              { label: '导出所有参会企业', value: 'companies' },
              { label: '导出所有参加岗位', value: 'jobs' },
              { label: '导出企业和岗位（每个企业一个 sheet）', value: 'companyJobs' },
            ]}
          />
        </Form.Item>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item label="招聘会标题" name="title">
              <Input allowClear placeholder="支持模糊查询" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="举办单位" name="hostUnit">
              <Input allowClear placeholder="支持模糊查询" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="招聘会类型" name="fairType">
              <Select allowClear options={toOptions(fairTypeOptions)} placeholder="全部" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label={isOnline ? '区域类型' : '举办区域'} name="region">
              <Select allowClear options={toOptions(regionOptions)} placeholder="全部" />
            </Form.Item>
          </Col>
          {!isOnline && (
            <Col span={8}>
              <Form.Item label="场地" name="venueId">
                <Select
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  options={toOptions(venueOptions)}
                  placeholder="全部"
                />
              </Form.Item>
            </Col>
          )}
          <Col span={8}>
            <Form.Item label="举办地址" name="address">
              <Input allowClear placeholder="支持模糊查询" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item label="招聘会开始时间范围" name="startRange">
              <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="招聘会结束时间范围" name="endRange">
              <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="报名时间范围" name="applyRange">
              <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="创建时间范围" name="createRange">
              <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item label="举办状态" name="fairStatus">
              <Select
                allowClear
                placeholder="全部"
                options={[
                  { label: '未举办', value: 'NOT_STARTED' },
                  { label: '正在举办', value: 'ONGOING' },
                  { label: '已举办', value: 'ENDED' },
                ]}
              />
            </Form.Item>
          </Col>
          {isOnline ? (
            <Col span={8}>
              <Form.Item label="是否跨域" name="isCrossDomain">
                <Select
                  allowClear
                  placeholder="全部"
                  options={[
                    { label: '是', value: 'Y' },
                    { label: '否', value: 'N' },
                  ]}
                />
              </Form.Item>
            </Col>
          ) : (
            <Col span={8}>
              <Form.Item label="是否开启线上申请" name="onlineApply">
                <Select
                  allowClear
                  placeholder="全部"
                  options={[
                    { label: '是', value: true },
                    { label: '否', value: false },
                  ]}
                />
              </Form.Item>
            </Col>
          )}
          <Col span={8}>
            <Form.Item label="审核状态" name="reviewStatus">
              <Select
                allowClear
                placeholder="全部"
                options={[
                  { label: '待审核', value: '0' },
                  { label: '审核通过', value: '1' },
                  { label: '审核不通过', value: '2' },
                ]}
              />
            </Form.Item>
          </Col>
        </Row>

        <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
          <Button onClick={onCancel}>取消</Button>
          <Button type="primary" htmlType="submit">
            开始导出
          </Button>
        </Space>
      </Form>
    </Modal>
  );
};

export default FairExportModal;
