import { Button, Form, Input } from "antd";
import { FormInstance } from "antd/lib";
import React, { useRef, useState } from "react";

export default function LinkForm({
  title,
  value,
  onCancel,
  onConfirm,
}: {
  title?: string;
  value?: string;
  onCancel: () => void;
  onConfirm: (data: { title?: string; value?: string }) => void;
}) {
  const formRef = useRef<FormInstance>(null);
  const [formModel, setFormModel] = useState({
    title,
    value,
  });

  const handleSetValue = (val: string) => {
    if(!val.includes('http://') || !val.includes('http://')) {
      // 自动补齐http://
      val = 'http://' + val;
    }
    setFormModel((state) => ({ ...state, value: val }));
  }

  const handleSubmit = async () => {
    await formRef.current?.validateFields();
    onConfirm(formModel);
  };

  return (
    <Form size="small" ref={formRef} colon={false} requiredMark={false}>
      <Form.Item
        name="value"
        label="链接"
        rules={[
          { required: true, message: "请输入链接" },
          { type: "url", message: "请输入正确的链接地址" },
        ]}
      >
        <Input
          placeholder="输入链接地址"
          value={formModel.value}
          onChange={(e) =>
            handleSetValue(e.target.value)
          }
        />
      </Form.Item>
      <Form.Item name="title" label="标题">
        <Input
          placeholder="输入文本(非必填)"
          value={formModel.title}
          onChange={(e) =>
            setFormModel((state) => ({ ...state, title: e.target.value }))
          }
        />
      </Form.Item>
      <Form.Item>
        <div className="flex justify-end">
          <Button onClick={onCancel}>取消</Button>
          <Button type="primary" className="ml-8px" onClick={handleSubmit}>
            确定
          </Button>
        </div>
      </Form.Item>
    </Form>
  );
}
