import 'server-only';

import { ImageType } from '@akinon/next/types';
import { getWidgetData } from '@akinon/next/data/server';

import { Link } from '@theme/components';
import { Image } from '@akinon/next/components/image';

function TitleSection({
  mobileTitle,
  mobileSubtitle
}: {
  mobileTitle?: { value: string };
  mobileSubtitle?: { value: string };
}) {
  return (
    <>
      {mobileTitle ? (
        <h2 className="text-5xl text-center font-light px-11 mb-2 lg:hidden">
          {mobileTitle.value}
        </h2>
      ) : null}
      {mobileSubtitle ? (
        <p className="text-sm text-center mb-2 lg:hidden">
          {mobileSubtitle.value}
        </p>
      ) : null}
    </>
  );
}

function MobileLinks({ mobileLinks }: { mobileLinks?: MobileLink[] }) {
  return (
    <ul className="flex justify-center text-sm font-medium underline mb-4 lg:hidden">
      {mobileLinks?.map((item, index) => (
        <li className="mr-4 first:ml-4" key={`${item?.value?.text}__${index}`}>
          <Link href={item?.value?.url}>{item?.value?.text}</Link>
        </li>
      ))}
    </ul>
  );
}

type StoryData = {
  value: {
    url: string;
    alt: string;
    image: string;
  };
  kwargs: {
    data_type: 'nested';
    value: {
      image: ImageType;
    };
  };
};

type MobileLink = {
  value: {
    url: string;
    text: string;
  };
};

type HomeStoriesEngType = {
  mobileTitle?: {
    value: string;
  };
  mobileSubtitle?: {
    value: string;
  };
  stories: StoryData[];
  mobileLinks: MobileLink[];
};

export default async function HomeStoriesEng() {
  const data = await getWidgetData<HomeStoriesEngType>({
    slug: 'home-storieseng'
  });

  return (
    <section className="my-8">
      <TitleSection
        mobileTitle={data?.attributes?.mobileTitle}
        mobileSubtitle={data?.attributes?.mobileSubtitle}
      />
      <MobileLinks mobileLinks={data?.attributes?.mobileLinks} />

      <div className="flex items-center overflow-x-auto pb-4 md:justify-center">
        {data?.attributes?.stories?.map((story, index) => {
          return (
            <div
              className="mr-4 flex-shrink-0 first:ms-4 w-32 md:w-32"
              key={`story__${index}`}
            >
              <Link href={story?.value?.url} aria-label={story?.value?.alt}>
                <Image
                  src={story?.kwargs?.value?.image?.url}
                  alt={story?.value?.alt}
                  aspectRatio={1}
                  sizes="(max-width: 768px) 112px, 140px"
                  imageClassName="rounded-full mb-2" // TODO: Fix width and height
                  fill
                />
              </Link>

              <Link
                href={story?.value?.url}
                className="block text-center underline text-sm font-medium"
                aria-label={story?.value?.alt}
              >
                {story?.value?.alt}
              </Link>
            </div>
          );
        })}
      </div>
    </section>
  );
}
