import {
  categoryOther,
  categorySocialMedia,
  categoryStreaming,
} from "@komi-app/creator-ui";
import {
  FLAGS,
  IfFeatureDisabled,
  IfFeatureEnabled,
} from "@komi-app/flags-sdk";
import { Button, Col, Row } from "antd";
import { Icon } from "components/Icon";
import Modal from "components/Modal";
import { Paragraph } from "components/Typography";
import { OTHER, SOCIAL_MEDIA, STREAMING } from "constants/social";
import isEmpty from "lodash/isEmpty";
import { useCallback, useEffect, useMemo, useState } from "react";
import { SocialProfileLinkItem } from "redux/User/types";
import { JSONService } from "utils/json-patch";
import AddSocialLink from "./AddSocialLink";
import SocialTags from "./SocialTags";
import SocialTagsV2 from "./SocialTagsV2";

interface ProfileSocialLinksModalProps {
  visible?: boolean;
  onClose?: () => void;
  links?: SocialProfileLinkItem[];
  onDone?: (links: SocialProfileLinkItem[]) => void;
}

const ProfileSocialLinksModal = ({
  visible,
  onClose,
  links = [],
  onDone,
}: ProfileSocialLinksModalProps) => {
  const [step, setStep] = useState(1);
  const [socialLinks, setSocialLinks] = useState(links);

  const [showError, setShowError] = useState(false);
  const [selectedItem, setSelectedItem] = useState<SocialProfileLinkItem>();
  const isUpdate = useMemo(() => {
    const patch = JSONService.getPatch(
      {
        links: socialLinks,
      },
      { links },
      {
        actions: ["add", "remove", "replace"], // actions
        ignoreFields: [], // ignoreFieldss
      }
    );
    return !isEmpty(patch);
  }, [socialLinks, links]);

  useEffect(() => {
    if (links && visible) {
      setSocialLinks(links);
    }
  }, [links, visible]);
  const handleRemoveTag = useCallback((key: string) => {
    setSocialLinks((values) => values.filter((el) => el.key !== key));
    setShowError(false);
  }, []);
  const handleAddTag = useCallback(
    (item: SocialProfileLinkItem) => {
      if (socialLinks.length >= 7) {
        setShowError(true);
        return;
      }
      setStep(2);
      setSelectedItem(item);
    },
    [socialLinks]
  );
  const handleClose = useCallback(() => {
    setSelectedItem(undefined);
    setStep(1);
    setShowError(false);
    onClose?.();
  }, [onClose]);
  const handleCloseAddItem = useCallback(() => {
    setStep(1);
    setSelectedItem(undefined);
  }, []);
  const onSubmit = useCallback(
    (item: SocialProfileLinkItem) => {
      setSocialLinks((values) => [...values, item]);
      handleCloseAddItem();
    },
    [handleCloseAddItem]
  );
  const handleDone = useCallback(() => {
    onDone?.(socialLinks);
    handleClose();
  }, [onDone, socialLinks]);
  const renderContent = () => {
    if (step === 2) {
      return (
        <AddSocialLink
          onClose={handleCloseAddItem}
          item={selectedItem}
          onSubmit={onSubmit}
        />
      );
    }
    return (
      <div>
        <Paragraph className="text--grey4 opacity--80" preset="regular14">
          You can add up to 7 social profile links to your page.
        </Paragraph>
        <IfFeatureEnabled feature={FLAGS.FEAT_SB_186_ADDITIONAL_SOCIAL_LINKS}>
          <SocialTagsV2
            socials={categorySocialMedia}
            className="m__t--24"
            title="Social Media"
            socialLinks={socialLinks}
            onRemoveTag={handleRemoveTag}
            onAddTag={handleAddTag}
          />
          <SocialTagsV2
            socials={categoryStreaming}
            className="m__t--24"
            title="Streaming"
            socialLinks={socialLinks}
            onRemoveTag={handleRemoveTag}
            onAddTag={handleAddTag}
          />
          <SocialTagsV2
            socials={categoryOther}
            className="m__t--24"
            title="Other"
            socialLinks={socialLinks}
            onRemoveTag={handleRemoveTag}
            onAddTag={handleAddTag}
          />
        </IfFeatureEnabled>
        <IfFeatureDisabled feature={FLAGS.FEAT_SB_186_ADDITIONAL_SOCIAL_LINKS}>
          <SocialTags
            socials={SOCIAL_MEDIA}
            className="m__t--24"
            title="Social Media"
            socialLinks={socialLinks}
            onRemoveTag={handleRemoveTag}
            onAddTag={handleAddTag}
          />
          <SocialTags
            socials={STREAMING}
            className="m__t--24"
            title="Streaming"
            socialLinks={socialLinks}
            onRemoveTag={handleRemoveTag}
            onAddTag={handleAddTag}
          />
          <SocialTags
            socials={OTHER}
            className="m__t--24"
            title="Other"
            socialLinks={socialLinks}
            onRemoveTag={handleRemoveTag}
            onAddTag={handleAddTag}
          />
        </IfFeatureDisabled>
        {showError && (
          <Paragraph className="text--red m__t--24" preset="regular12">
            Only 7 links can be added at one time, please delete a link in order
            to add a new one
          </Paragraph>
        )}
        {isUpdate && (
          <Button
            className="ant-btn-xl ant-btn-uppercase m__t--24 full-width"
            size="large"
            type="primary"
            onClick={handleDone}
          >
            Done
          </Button>
        )}
      </div>
    );
  };
  return (
    <>
      <Modal
        width={664}
        title={
          <Row gutter={12} align="middle">
            {step !== 1 && (
              <Col
                onClick={handleCloseAddItem}
                className="height--24 cursor-pointer"
              >
                <Icon name="back" />
              </Col>
            )}
            <Col>
              <Paragraph preset="semibold18">Add Social Link</Paragraph>
            </Col>
          </Row>
        }
        visible={visible}
        zIndex={100}
        onCancel={handleClose}
        maskClosable={false}
        centered
      >
        <div>{renderContent()}</div>
      </Modal>
    </>
  );
};

export default ProfileSocialLinksModal;
