import { LinkOutlined } from "@ant-design/icons";
import { Button, Input, Space } from "antd";
import { forwardRef, useMemo } from "react";

const HAS_URL_PROTOCOL_REGEX = /^[a-zA-Z][a-zA-Z\d+.-]*:/;
const LOCALHOST_OR_IP_REGEX = /^(localhost|127(?:\.\d{1,3}){3}|\d{1,3}(?:\.\d{1,3}){3})(:\d+)?(\/.*)?$/i;

const getUrlActionHref = (value) => {
  const trimmedValue = String(value ?? "").trim();
  if (!trimmedValue) return null;

  if (HAS_URL_PROTOCOL_REGEX.test(trimmedValue)) return trimmedValue;
  if (trimmedValue.startsWith("//")) return `https:${trimmedValue}`;
  if (LOCALHOST_OR_IP_REGEX.test(trimmedValue)) return `http://${trimmedValue}`;

  return `https://${trimmedValue}`;
};

const FormItemUrl = forwardRef(function FormItemUrl({ value, defaultValue, ...props }, ref) {
  const urlActionHref = useMemo(() => getUrlActionHref(value ?? defaultValue), [defaultValue, value]);

  return (
    <Space.Compact style={{ width: "100%" }}>
      <Input ref={ref} {...props} value={value} defaultValue={defaultValue} />
      {urlActionHref ? (
        <Button icon={<LinkOutlined />} href={urlActionHref} target="_blank" rel="noopener noreferrer" />
      ) : (
        <Button icon={<LinkOutlined />} disabled />
      )}
    </Space.Compact>
  );
});

export default FormItemUrl;
