import { useAuth, useClerk } from '@clerk/nextjs';
import { useDynamicConfig } from '@statsig/react-bindings';
import { clsx } from 'clsx';
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { twMerge } from 'tailwind-merge';

import ImpressionLogger, {
  ImpressionLoggerConfig,
} from '@/components/ImpressionLogger';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import { FeedListContextProps } from '@/components/feed/FeedItemList';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import Link from '@/components/link/Link';
import SpinnerSVG from '@/components/svg/SpinnerSVG';
import VerifiedBadge from '@/components/timbaland/VerifiedBadge';
import { UserAddIcon, UserAddedIcon } from '@/icons';
import { useApiClient } from '@/lib/apiClient';
import { components } from '@/lib/gen';
import logWebUserEvent from '@/logging/logWebUserEvent';
import {
  SMALL_IMAGE,
  TYPOGRAPHY_DISCOVER_FEED_BODY_1_CLASSNAME,
  TYPOGRAPHY_DISCOVER_FEED_BODY_2_CLASSNAME,
} from '@/utils/constants';
import {
  getClerkSignInRedirectProps,
  getCountString,
  isVerifiedProfile,
} from '@/utils/utils';

export const FollowButton = ({
  artistHandle,
  followersCount,
  onFollowerCountChange,
}: {
  artistHandle: string;
  followersCount: number;
  onFollowerCountChange: ({
    followersCount,
    isFollowing,
  }: {
    followersCount: number;
    isFollowing: boolean;
  }) => void;
}) => {
  const [isFollowing, setIsFollowing] = useState(false);
  const [isFollowLoading, setIsFollowLoading] = useState(false);
  const { isSignedIn } = useAuth();
  const clerk = useClerk();
  const apiClient = useApiClient();
  const { t } = useTranslation();

  const handleFollow = async () => {
    if (!isSignedIn) {
      clerk.openSignIn({
        withSignUp: true,
        ...getClerkSignInRedirectProps(`/profile/${artistHandle}`),
      });
    } else {
      if (isFollowing) {
        onFollowerCountChange({
          followersCount: followersCount - 1,
          isFollowing,
        });
      } else {
        onFollowerCountChange({
          followersCount: followersCount + 1,
          isFollowing,
        });
      }
      setIsFollowLoading(true);
      await apiClient.POST('/api/profiles/follow', {
        body: {
          unfollow: isFollowing,
          handle: artistHandle,
        },
      });
      setIsFollowLoading(false);
      setIsFollowing(!isFollowing);
    }
  };

  return (
    <Button
      variant={ButtonVariant.Secondary}
      size={ButtonSize.Mini}
      shape={ButtonShape.Pill}
      onClick={handleFollow}
      icon={
        isFollowLoading ? (
          <SpinnerSVG
            className={clsx('h-4 w-4', {
              'text-background-tertiary': isFollowing,
            })}
          />
        ) : isFollowing ? (
          UserAddedIcon
        ) : (
          UserAddIcon
        )
      }
      active={isFollowing}
    >
      {isFollowing ? t('profile.following') : t('profile.follow')}
    </Button>
  );
};

export type SuggestedCreatorFeedItemProps = {
  artistImage: string;
  artistName: string;
  artistHandle: string;
  artistId: string;
  numberOfFollowers: number;
};

export const getPropsForSuggestedCreatorFeedItem = ({
  item,
}: {
  item: components['schemas']['SimpleProfileInfoSchema'];
}): SuggestedCreatorFeedItemProps & { key: string } => {
  return {
    key: item.external_user_id,
    artistImage: item.avatar_image_url ?? '',
    artistName: item.display_name ?? '',
    artistHandle: item.handle ?? '',
    artistId: item.external_user_id,
    numberOfFollowers: item.stats?.followers_count ?? 0,
  };
};

export type Props = Omit<
  React.HTMLAttributes<HTMLDivElement>,
  keyof SuggestedCreatorFeedItemProps
> &
  SuggestedCreatorFeedItemProps &
  FeedListContextProps & { index: number };

export const SuggestedCreatorFeedItem = ({
  artistImage,
  artistName,
  artistHandle,
  artistId,
  index,
  numberOfFollowers,
  listId,
  listTitle,
}: Props) => {
  const [followersCount, setFollowersCount] = useState(numberOfFollowers);
  const { t } = useTranslation();
  const { value: verifiedProfiles } = useDynamicConfig('verified-profiles');
  const handles = (verifiedProfiles?.handles as string[]) || [];

  const handleFollowerCountChange = ({
    followersCount,
    isFollowing,
  }: {
    followersCount: number;
    isFollowing: boolean;
  }) => {
    setFollowersCount(followersCount);
    logWebUserEvent({
      actionName: 'SuggestedCreatorFeedItemFollowClicked',
      principalObjectType: 'artist',
      principalObjectValue: artistId,
      context: {
        index,
        artistName,
        artistHandle,
        followersCount,
        sectionId: listId,
        sectionTitle: listTitle,
        isFollowing,
      },
    });
  };

  const impressionLoggerConfig = useMemo<ImpressionLoggerConfig[]>(() => {
    return [
      {
        event: {
          actionName: 'SuggestedCreatorFeedItemSeen',
          principalObjectType: 'artist',
          principalObjectValue: artistId,
          context: {
            index: index,
            artistName,
            artistHandle,
            followersCount,
            sectionId: listId,
            sectionTitle: listTitle,
          },
        },
        threshold: 0.9,
      },
    ];
  }, [
    artistId,
    index,
    artistName,
    artistHandle,
    followersCount,
    listId,
    listTitle,
  ]);
  return (
    <ImpressionLogger configs={impressionLoggerConfig}>
      <div
        className={twMerge(
          clsx(
            'group flex w-full flex-row items-center rounded-lg p-2',
            'transition-colors duration-150',
            'focus-within:bg-background-secondary-glass hover:bg-background-secondary-glass'
          )
        )}
      >
        <div className='flex min-w-0 flex-1 flex-row gap-4'>
          <Link
            href={`/@${artistHandle}`}
            className='shrink-0'
            onClick={() => {
              logWebUserEvent({
                actionName: 'SuggestedCreatorFeedItemImageClicked',
                principalObjectType: 'artist',
                principalObjectValue: artistId,
                context: {
                  index,
                  artistName,
                  artistHandle,
                  followersCount,
                  sectionId: listId,
                  sectionTitle: listTitle,
                },
              });
            }}
          >
            <ImageWithFallback
              className='h-16 w-12 rounded-lg object-cover'
              src={artistImage}
              alt={artistName}
              imageSize={SMALL_IMAGE}
            />
          </Link>
          <div className='flex min-w-0 flex-col justify-center gap-1'>
            <Link
              href={`/@${artistHandle}`}
              className='flex flex-row items-center gap-2'
              onClick={() => {
                logWebUserEvent({
                  actionName: 'SuggestedCreatorFeedItemTitleClicked',
                  principalObjectType: 'artist',
                  principalObjectValue: artistId,
                  context: {
                    index,
                    artistName,
                    artistHandle,
                    followersCount,
                    sectionId: listId,
                    sectionTitle: listTitle,
                  },
                });
              }}
            >
              <div
                className={clsx(
                  TYPOGRAPHY_DISCOVER_FEED_BODY_1_CLASSNAME,
                  'line-clamp-1 cursor-pointer text-foreground-primary hover:underline'
                )}
              >
                {artistName}
              </div>
              {isVerifiedProfile({ handle: artistHandle }, handles) && (
                <VerifiedBadge className='h-4 w-4 shrink-0' />
              )}
            </Link>
            <div
              className={clsx(
                TYPOGRAPHY_DISCOVER_FEED_BODY_2_CLASSNAME,
                'line-clamp-1 text-foreground-secondary'
              )}
            >
              {getCountString(followersCount)} followers
            </div>
            <div
              className={clsx(
                TYPOGRAPHY_DISCOVER_FEED_BODY_2_CLASSNAME,
                'line-clamp-1 text-foreground-tertiary'
              )}
            >
              {`@${artistHandle} · ${t('feed.suggested')}`}
            </div>
          </div>
        </div>
        <FollowButton
          artistHandle={artistHandle}
          followersCount={followersCount}
          onFollowerCountChange={handleFollowerCountChange}
        />
      </div>
    </ImpressionLogger>
  );
};

export default SuggestedCreatorFeedItem;
