import KFModal from '@/components/KFModal';
import { type CodeConfigData } from '@/pages/CodeConfig/List';
import { addCodeConfigReq, updateCodeConfigReq } from '@/services/codeConfig';
import { to } from '@/utils/promise';
import { Form, Input, Radio, message, type FormRule, type ModalProps } from 'antd';
import { omit } from 'lodash';
import { useMemo } from 'react';

export enum VerifyMode {
  Password = 0, // 用户名密码
  SSH = 1, // SSH Key
}

export enum OperationType {
  Create = 0, // 新建
  Update = 1, // 更新
}

type FormData = Partial<CodeConfigData>;

interface AddCodeConfigModalProps extends Omit<ModalProps, 'onOk'> {
  opType: OperationType;
  codeConfigData?: CodeConfigData;
  onOk: () => void;
}

function AddCodeConfigModal({ opType, codeConfigData, onOk, ...rest }: AddCodeConfigModalProps) {
  const [form] = Form.useForm();
  const isPublic = Form.useWatch('is_public', form) as boolean;

  const urlExample = useMemo(
    () =>
      isPublic
        ? 'https://gitlink.org.cn/ci4s/ci4sManagement-cloud.git'
        : 'git@code.gitlink.org.cn:ci4s/ci4sManagement-cloud.git',
    [isPublic],
  );

  // /^(git@[\w.-]+:[\w./-]+\.git)$/
  const urlRules: FormRule[] = useMemo(
    () =>
      isPublic
        ? [
            {
              type: 'url',
              message: '请输入正确的 Git 地址',
            },
          ]
        : ([] as FormRule[]),
    [isPublic],
  );

  // 创建
  const createCodeConfig = async (formData: FormData) => {
    const params: FormData & { id?: number } = {
      ...formData,
    };
    // 清除多余的信息
    if (formData.is_public) {
      omit(params, ['verify_mode', 'git_user_name', 'git_password', 'ssh_key']);
    }
    if (formData.verify_mode === VerifyMode.Password) {
      omit(params, ['ssh_key']);
    } else if (formData.verify_mode === VerifyMode.SSH) {
      omit(params, ['git_user_name', 'git_password']);
    }
    if (opType === OperationType.Update) {
      params.id = codeConfigData?.id;
    }
    const request = opType === OperationType.Create ? addCodeConfigReq : updateCodeConfigReq;
    const [res] = await to(request(params));
    if (res) {
      message.success(opType === OperationType.Create ? '创建成功' : '修改成功');
      onOk?.();
    }
  };

  // 提交
  const onFinish = (formData: FormData) => {
    createCodeConfig(formData);
  };

  // 设置初始值
  const initialValues: FormData = codeConfigData ?? {
    is_public: true,
    verify_mode: VerifyMode.Password,
  };
  if (initialValues.verify_mode === undefined || initialValues.verify_mode === null) {
    initialValues.verify_mode = VerifyMode.Password;
  }

  return (
    <KFModal
      {...rest}
      title={opType === OperationType.Create ? '新建代码配置' : '修改代码配置'}
      image={require('@/assets/img/create-experiment.png')}
      width={825}
      okButtonProps={{
        htmlType: 'submit',
        form: 'form',
      }}
      destroyOnClose
    >
      <Form
        name="form"
        form={form}
        layout="vertical"
        onFinish={onFinish}
        initialValues={initialValues}
        autoComplete="off"
      >
        <Form.Item
          label="代码仓库名称"
          name="code_repo_name"
          required
          rules={[
            {
              required: true,
              message: '请输入代码仓库名称',
            },
          ]}
        >
          <Input placeholder="请输入代码仓库名称" showCount allowClear maxLength={64} />
        </Form.Item>
        <Form.Item
          label="代码仓库可见性"
          name="is_public"
          rules={[
            {
              required: true,
              message: '请选择代码仓库可见性',
            },
          ]}
        >
          <Radio.Group>
            <Radio value={true}>公开</Radio>
            <Radio value={false}>私有</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="Git 地址"
          name="git_url"
          rules={[
            {
              required: true,
              message: '请输入 Git 地址',
            },
            ...urlRules,
          ]}
        >
          <Input
            placeholder={`请输入 Git 地址，如: ${urlExample}`}
            showCount
            allowClear
            maxLength={256}
          />
        </Form.Item>
        <Form.Item
          label="代码分支/Tag"
          name="git_branch"
          rules={[
            {
              required: true,
              message: '请输入代码分支/Tag',
            },
          ]}
        >
          <Input placeholder="请输入代码分支/Tag" showCount allowClear maxLength={64} />
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) =>
            prevValues?.is_public !== currentValues?.is_public
          }
        >
          {({ getFieldValue }) => {
            return getFieldValue('is_public') === false ? (
              <>
                <Form.Item
                  label="验证方式"
                  name="verify_mode"
                  rules={[
                    {
                      required: true,
                      message: '请选择验证方式',
                    },
                  ]}
                >
                  <Radio.Group>
                    <Radio value={VerifyMode.Password}>用户名/密码</Radio>
                    <Radio value={VerifyMode.SSH}>SSH Key</Radio>
                  </Radio.Group>
                </Form.Item>
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, currentValues) =>
                    prevValues?.verify_mode !== currentValues?.verify_mode
                  }
                >
                  {({ getFieldValue }) => {
                    return getFieldValue('verify_mode') === VerifyMode.Password ? (
                      <>
                        <Form.Item
                          label="Git 用户名"
                          name="git_user_name"
                          rules={[
                            {
                              required: true,
                              message: '请输入 Git 用户名',
                            },
                          ]}
                        >
                          <Input
                            placeholder="请输入 Git 用户名"
                            autoComplete="off"
                            showCount
                            allowClear
                            maxLength={64}
                          />
                        </Form.Item>
                        <Form.Item
                          label="Git 密码"
                          name="git_password"
                          rules={[
                            {
                              required: true,
                              message: '请输入 Git 密码',
                            },
                          ]}
                        >
                          <Input.Password
                            autoComplete="new-password"
                            placeholder="请输入 Git 密码"
                            allowClear
                          />
                        </Form.Item>
                      </>
                    ) : (
                      <Form.Item
                        label="SSH Key"
                        name="ssh_key"
                        rules={[
                          {
                            required: true,
                            message: '请输入 SSH Key',
                          },
                        ]}
                      >
                        <Input.TextArea
                          placeholder="请输入 SSH Key"
                          showCount
                          maxLength={4096}
                          autoSize={{ minRows: 4, maxRows: 8 }}
                          allowClear
                        />
                      </Form.Item>
                    );
                  }}
                </Form.Item>
              </>
            ) : null;
          }}
        </Form.Item>
      </Form>
    </KFModal>
  );
}

export default AddCodeConfigModal;
