import { useState } from 'react';

import type { LookupService } from '~/lib/songwhipLookup/types';
import type { ServiceTypes } from '~/lib/types';

import Box from '~/src/components/Box';
import Clickable from '~/src/components/Clickable';
import ExternalLinkIcon from '~/src/components/Icon/ExternalLinkIcon';
import Text from '~/src/components/Text';
import TextInput from '~/src/components/TextInput';
import getServiceDisplayData from '~/src/lib/getServiceDisplayData';
import { useI18n } from '~/src/lib/i18n';
import { isValidServiceLink } from '~/src/lib/lookup';

interface CustomServiceLinkProps {
  testId?: string;
  service: LookupService;
  link?: string | null;
}

export const CustomServiceLink = ({
  testId,
  service,
  link,
}: CustomServiceLinkProps) => {
  const { t } = useI18n('prerelease');

  const [validatedLink, setValidatedLink] = useState({
    link,
    isValid: isValidServiceLink(service, link),
  });

  const serviceData = getServiceDisplayData(service as ServiceTypes);
  if (!serviceData) return null;

  return (
    <Box flexColumn gap="0.5rem" testId={testId}>
      <Box flexRow alignCenter gap="0.7rem">
        <serviceData.Icon size="2.2rem" />

        <Text flexRow alignCenter flexGrow withEllipsis size="1.35rem">
          <Text isInline>{serviceData.name}</Text>
        </Text>
      </Box>

      <Box flexRow alignCenter gap="1rem">
        <TextInput
          flexGrow
          testId={`${service}CustomLinkInput`}
          defaultValue={link ?? undefined}
          name={service}
          placeholder={t('customLinkPlaceholder', {
            serviceName: serviceData.name,
          })}
          required={false}
          toValidationMessage={({ value }) => {
            const isValid = isValidServiceLink(service, value);
            setValidatedLink({ link: value, isValid });

            if (value && !isValid) {
              return t('invalidServiceLink', { serviceName: serviceData.name });
            }

            return undefined;
          }}
        />
        <Clickable
          testId={`${service}CustomLinkButton`}
          href={
            validatedLink.isValid && validatedLink.link
              ? validatedLink.link
              : undefined
          }
          inNewTab
          isDisabled={!validatedLink.isValid}
          width="auto"
        >
          <ExternalLinkIcon />
        </Clickable>
      </Box>
    </Box>
  );
};
