import React, { useState } from "react";
import { FormInstance } from "antd";

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

import { Paragraph } from "components/Typography";
import { MultistageFormStage, warnAndThrow } from "components/MultistageForm";
import {
  defaultMusicLinks,
  MusicProfileLinkItem,
} from "components/PreReleaseModal";

import PreReleaseLinkList from "./PreReleaseLinkList/PreReleaseLinkList";

interface SmartItemsLinksFormProps {
  isEdit: boolean;
  music?: MusicItem;
}

export const SmartItemLinksForm: React.FC<SmartItemsLinksFormProps> = ({
  isEdit,
  music,
  ...props
}) => {
  const resolvedMusicLinks = React.useMemo(() => {
    if (!music || !isEdit) {
      return defaultMusicLinks;
    }

    const musicLinks = music.links.map(({ type, url, ...musicLink }) => {
      const formLink = {
        url,
        ...musicLink,
      };

      const defaultLink = defaultMusicLinks.find((el) => el.key === type);

      return {
        ...defaultLink,
        ...formLink,
      } as MusicProfileLinkItem;
    });

    return musicLinks;
  }, []);

  const [form, setForm] = useState<FormInstance>();
  const [musicLinks, setMusicLinks] =
    useState<MusicProfileLinkItem[]>(resolvedMusicLinks);

  const onFinish = (values: any) => {
    const musicLinks = values.musicLinks as Record<
      string,
      MusicProfileLinkItem
    >;
    const musicLinkEntries = Object.entries(musicLinks);

    const musicLinkUrls = musicLinkEntries.map(
      ([, /* key */ link]) => link.url
    );

    const isAnyLinkValued = musicLinkUrls.some(Boolean);
    if (!isAnyLinkValued) {
      warnAndThrow("Please add a link for the release");
    }

    const isAnyLinkVisible = musicLinkEntries.some(
      ([, /* key */ link]) => link.isVisible
    );
    if (!isAnyLinkVisible) {
      warnAndThrow("Please make sure that at least one link is visible");
    }

    form?.setFieldsValue({
      musicLinks: values.musicLinks,
    });
  };

  return (
    <MultistageFormStage
      requiredMark="optional"
      onFinish={onFinish}
      setForm={setForm}
      validateTrigger="onSubmit"
      {...props}
    >
      <Paragraph className="m__b--5" preset="semibold18">
        Select Services
      </Paragraph>

      <PreReleaseLinkList
        form={form}
        className="module-music"
        links={musicLinks}
        setMusicLinks={setMusicLinks}
      />
    </MultistageFormStage>
  );
};
