import * as React from 'react';

import { ServiceData, VCardData, ServiceDataTypes } from './getServiceData';

function getLinkHref(url: string) {
  return url.includes('@') ? `mailto:${url}` : url;
}

const VCard = ({ data }: { data: VCardData }) => {
  if (!data.name && !data.address) {
    return null;
  }

  return (
    <div className="uc-text-14">
      {data.name && <div className="uc-mb-1">{data.name}</div>}
      {data.address && <div>{data.address}</div>}
    </div>
  );
};

const List = ({ items }: { items: string[] }) => {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index} className="uc-mb-1 uc-text-14">{`- ${item}`}</li>
      ))}
    </ul>
  );
};

const ExternalLink = ({ href, children }: React.PropsWithChildren<{ href: string }>) => {
  return (
    <a
      href={getLinkHref(href)}
      className="uc-text-primary hover:uc-text-primary-dark uc-text-14 uc-break-all"
      target="_blank"
      rel="noopener noreferrer"
    >
      {children}
    </a>
  );
};

const LinkSection = ({ url, children }: React.PropsWithChildren<{ url: string }>) => {
  return (
    <div className="uc-mb-6">
      <p className="uc-font-medium">{children}</p>
      <div>
        <ExternalLink href={getLinkHref(url)}>{url}</ExternalLink>
      </div>
    </div>
  );
};

const SwitchContent = ({ content }: { content: ServiceData<ServiceDataTypes> }) => {
  switch (content.componentType) {
    case 'v-card':
      return <VCard data={content.data as VCardData} />;
    case 'list':
      return <List items={content.data as string[]} />;
    case 'text-link':
      return <ExternalLink href={content.data as string}>{content.data}</ExternalLink>;
    default:
      return <div>{content.data}</div>;
  }
};

export const SectionWithTitle = ({
  title,
  description,
  children,
}: React.PropsWithChildren<{ title: string; description?: string }>): JSX.Element => {
  return (
    <div className="uc-mb-6">
      <h4 className="uc-font-medium uc-mb-2">{title}</h4>
      {description && <p className="uc-mb-4 uc-text-14">{description}</p>}
      <div className="uc-text-14">{children}</div>
    </div>
  );
};

export const ContentSection = ({ content }: { content: ServiceData<ServiceDataTypes> }): JSX.Element => {
  if (!content.data) {
    return <></>;
  }

  if (content.componentType === 'link') {
    return <LinkSection url={content.data as string}>{content.title}</LinkSection>;
  }

  return (
    <SectionWithTitle title={content.title} description={content.description}>
      <SwitchContent content={content} />
    </SectionWithTitle>
  );
};
