import { Col, Form, Input, Row } from "antd";
import classNames from "classnames";
import LabelTooltip from "components/LabelTooltip/LabelTooltip";
import * as React from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";
import { validURL } from "../../utils";
import DragDropButton from "../Button/DragDropButton";
import { Icon, IconName } from "../Icon";
import { Text } from "../Typography";
import "./MusicItem.scss";

interface MusicItemProps {
  defaultValue?: string;
  className?: string;
  title?: string;
  name?: string;
  value?: string;
  edit?: boolean;
  isDisableDragged?: boolean;
  icon?: IconName;
  disableDrag?: boolean;
  required?: boolean;
  onSetItem?: (value: any) => void;
  onRemoveItem?: () => void;
  onChangeText?: (value: string) => void;
  dragHandleProps?: DraggableProvidedDragHandleProps;
}

const MusicItem = ({
  className,
  title,
  icon,
  onChangeText,
  name,
  dragHandleProps,
  edit,
  onSetItem,
  defaultValue = "",
  isDisableDragged,
  onRemoveItem,
  required = true,
}: MusicItemProps) => {
  const ref = useRef<Input>(null);
  const [value, setValue] = useState(defaultValue);
  const handleChange = useCallback((event) => {
    const regex = /^(https?|ftp):\/\//i;
    const text = event.target.value;
    if (
      !regex.test(text) &&
      ("https://".includes(text) || "http://".includes(text))
    ) {
      setValue(text);
      onChangeText?.(text);
      return;
    }
    if (!regex.test(text) && text.trim().length) {
      onChangeText?.("https://" + text);
      setValue("https://" + text);
      return;
    }
    setValue(text);
    onChangeText?.(text);
  }, []);
  const handleBlur = useCallback(() => {
    if (validURL(value)) {
      onSetItem?.({ edit: false, value });
    } else {
      onRemoveItem?.();
    }
  }, [value, onSetItem]);
  const handleEnableEdit = useCallback(() => {
    onSetItem?.({ edit: true });
    setTimeout(() => {
      ref?.current?.focus();
    }, 200);
  }, [ref, onSetItem]);
  useEffect(() => {
    if (defaultValue?.length) {
      setValue(defaultValue);
    }
  }, [defaultValue]);
  return (
    <div className={classNames("music-item", className)}>
      <Row align="middle" wrap={false}>
        <Col className="music-item--left" flex={1}>
          <Row>
            <Icon name={icon || "apple-music"} />
            <Text className="m__l--10" ellipsis={true} preset="semibold16">
              {title}
            </Text>
          </Row>
        </Col>
        <Col>
          <DragDropButton
            className="p__x--0 p__y--0"
            dragType="vertical"
            dragHandleProps={dragHandleProps}
            disabled={isDisableDragged}
            onClick={(event) => event.stopPropagation()}
          />
        </Col>
      </Row>
      {!edit && (
        <div onClick={handleEnableEdit} className={"cursor-pointer m__t--4"}>
          <LabelTooltip
            label={value}
            maxLength={90}
            className="text--grey4"
            preset="regular14"
          />
        </div>
      )}
      <Form.Item
        rules={
          required
            ? [
                {
                  required: true,
                  message: "Please enter this field",
                },
                {
                  type: "url",
                  message: "This field must be a valid url.",
                },
              ]
            : [
                {
                  type: "url",
                  message: "This field must be a valid url.",
                },
              ]
        }
        name={name}
        className={classNames("m__t--20 m__b--20", !edit && "d--none")}
      >
        <Input
          ref={ref}
          autoFocus
          onBlur={handleBlur}
          onChange={handleChange}
          placeholder="https://"
        />
      </Form.Item>
    </div>
  );
};

export default React.memo(MusicItem);
