import React, { useCallback, useEffect } from "react";
import { Form, Row, Col } from "antd";
import { FormListFieldData } from "antd/lib/form/FormList";

import { MediaUpload } from "redux/Common/types";

import { MusicItem } from "models/talent/talent-profile-module.model";

import { Icon } from "components/Icon";
import { Input } from "components/Input";
import { Paragraph } from "components/Typography";
import { MultistageFormStage, warnAndThrow } from "components/MultistageForm";

import { ReactComponent as TrashIcon } from "icons/trash.svg";

import CoverUpload from "../../../CoverUpload";

// TODO: Upgrade Antd to allow custom classes for validation
// import { Rule } from 'antd/lib/form';

interface MusicItemArtistFieldProps extends FormListFieldData {
  index: number;
  removeButton: React.ReactNode;
}

export const MusicItemArtistField: React.FC<MusicItemArtistFieldProps> = ({
  name,
  removeButton,
  ...rest
}) => {
  return (
    <Form.Item
      {...rest}
      name={[name, "name"]}
      // https://ant.design/changelog#4.18.0
      // fieldKey={[key, "name"]}
      rules={[
        {
          required: true,
          message: "Artist name is required",
        },
      ]}
    >
      <Input placeholder="e.g. John Doe" suffix={removeButton} />
    </Form.Item>
  );
};

interface MusicItemInformationFormProps {
  initialStageValues?: any;
  isEdit: boolean;
  music?: MusicItem;
  photo: MediaUpload;
  title?: string;
  setPhoto: (file: MediaUpload) => void;
}

export const MusicItemInformationForm: React.FC<
  MusicItemInformationFormProps
> = ({ initialStageValues, isEdit, music, photo, setPhoto, ...props }) => {
  const initialValues = React.useMemo(() => {
    const artists = initialStageValues?.artists ||
      music?.metadata?.artists || [{ name: "" }];
    const title = initialStageValues?.title || music?.metadata?.name || "";

    return {
      artists,
      title,
    };
  }, [isEdit, music, setPhoto]);

  useEffect(() => {
    if (isEdit && music) {
      setPhoto({ url: music.metadata.images[0].url });
    }
  }, []);

  const onFinish = useCallback(
    (values) => {
      if (!photo.url) {
        warnAndThrow("Please add the Cover Photo");
      }

      if (values.artists.length === 0) {
        warnAndThrow("Please add at least one artist");
      }
    },
    [photo]
  );

  const removePhoto = useCallback(() => setPhoto({}), [photo]);
  // TODO: Upgrade Antd to allow custom classes for validation
  //
  // const photoRules: Rule[] = [{
  //   validator: () => {},
  //   className: '',
  // }]

  return (
    <MultistageFormStage
      requiredMark="optional"
      initialValues={initialValues}
      onFinish={onFinish}
      validateTrigger="onSubmit"
      {...props}
    >
      <div className="p__t--8">
        <Form.Item
        // TODO: Upgrade Antd to allow custom classes for validation
        // rules={}
        >
          <CoverUpload
            photo={photo}
            onUploadSuccess={setPhoto}
            onRemove={removePhoto}
            data-testid="smart-link--customize-cover-upload"
          />
        </Form.Item>
      </div>

      <Paragraph className="m__b--8 m__t--32" preset="regular14">
        Title
      </Paragraph>

      <Form.Item
        rules={[{ required: true, message: "Title is required" }]}
        name="title"
      >
        <Input size="large" placeholder="e.g. My New Track" />
      </Form.Item>

      <Paragraph className="m__b--8 m__t--32" preset="regular14">
        Artists
      </Paragraph>

      <Form.List name={"artists"}>
        {(fields, { add, remove }) => {
          return (
            <>
              {fields.map(({ key, ...props }, index) => {
                const removeButton =
                  index > 0 ? (
                    <TrashIcon
                      className="trash--red"
                      onClick={() => remove(index)}
                      role="button"
                    />
                  ) : null;

                return (
                  <MusicItemArtistField
                    key={key}
                    index={index}
                    removeButton={removeButton}
                    {...props}
                  />
                );
              })}

              <Row
                onClick={() => add()}
                className="cursor-pointer"
                gutter={8}
                align="middle"
              >
                <Col className="height--32">
                  <Icon name="add-blue" />
                </Col>
                <Col>
                  <Paragraph className="text--blue m__b--0" preset="semibold18">
                    Add another artist
                  </Paragraph>
                </Col>
              </Row>
            </>
          );
        }}
      </Form.List>
    </MultistageFormStage>
  );
};
