import React from 'react';
import { useTranslation } from 'react-i18next';
import { Avatar, AvatarFallback, AvatarImage, Button, Icon, Icons, Text } from 'folds';
import { useUserImagePack } from '../../../hooks/useImagePacks';
import { SettingTile } from '../../../components/setting-tile';
import { SettingsSection } from '../SettingsSection';
import { ImagePack, ImageUsage } from '../../../plugins/custom-emoji';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { mxcUrlToHttp } from '../../../utils/matrix';
import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';

type UserPackProps = {
  onViewPack: (imagePack: ImagePack) => void;
};
export function UserPack({ onViewPack }: UserPackProps) {
  const { t } = useTranslation();
  const mx = useMatrixClient();
  const useAuthentication = useMediaAuthentication();

  const userPack = useUserImagePack();
  const avatarMxc = userPack?.getAvatarUrl(ImageUsage.Emoticon);
  const avatarUrl = avatarMxc ? mxcUrlToHttp(mx, avatarMxc, useAuthentication) : undefined;

  const handleView = () => {
    if (userPack) {
      onViewPack(userPack);
    } else {
      const defaultPack = new ImagePack(mx.getSafeUserId(), {}, undefined);
      onViewPack(defaultPack);
    }
  };

  return (
    <SettingsSection label={t('Settings.default_pack')}>
      <SettingTile
        title={userPack?.meta.name ?? t('Settings.unknown')}
        description={userPack?.meta.attribution}
        before={
          <Avatar size="300" radii="300">
            {avatarUrl ? (
              <AvatarImage style={{ objectFit: 'contain' }} src={avatarUrl} />
            ) : (
              <AvatarFallback>
                <Icon size="400" src={Icons.Sticker} filled />
              </AvatarFallback>
            )}
          </Avatar>
        }
        after={
          <Button
            variant="Secondary"
            fill="Soft"
            size="300"
            radii="300"
            outlined
            onClick={handleView}
          >
            <Text size="B300">{t('Settings.view')}</Text>
          </Button>
        }
      />
    </SettingsSection>
  );
}
