"use client";

import {
  type LabMetaV2,
  tidbEnvironmentLocaleKey,
} from "@/components/labs/hooks-v2";
import { useMe } from "@/components/me-context";
import { NextLink } from "@/components/next-link";
import { PinnedLabsSections } from "@/components/pages/home/labs-section";
import { Separator } from "@/components/ui/separator";
import { useLocaleFunction } from "@/hooks/use-localed";
import { useLoginUrl } from "@/hooks/use-url";
import type { LabMetaExtra } from "@/lib/api/labs";
import { transformPathLocale } from "@/lib/locale";
import {
  BadgeIcon,
  CircleSlashIcon,
  ClockIcon,
  DatabaseIcon,
  TagIcon,
  UsersIcon,
  CheckCircleIcon,
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { Fragment, type ReactNode } from "react";
import { cn } from "@/lib/utils";

export function LabOverviewContent({
  lab,
  labs,
}: {
  lab: LabMetaV2 & LabMetaExtra;
  labs: LabMetaV2[];
}) {
  return (
    <div className="grid grid-cols-12 gap-4 md:gap-6 lg:gap-8">
      <LabOverviewMainContent lab={lab} />
      <Separator className="col-span-12" />
      <PinnedLabsSections className="col-span-12 mt-4" labs={labs} />
    </div>
  );
}

function LabOverviewMainContent({ lab }: { lab: LabMetaV2 & LabMetaExtra }) {
  const { data: me } = useMe();
  const t = useLocaleFunction();
  const loginUrl = useLoginUrl();

  return (
    <>
      <div className="col-span-12 md:col-span-6">
        <Image
          className="w-full aspect-video"
          src={t(lab, "splash_image")}
          alt="Splash Image"
          width={240}
          height={135}
          unoptimized
        />
      </div>
      <div className="col-span-12 md:col-span-6 px-4 lg:px-8 py-6 bg-card border shadow-lg flex flex-col items-stretch">
        <div className="flex flex-col gap-2 flex-1  mb-2">
          <h1 className="text-2xl leading-7 font-semibold mb-2">
            {t(lab, "title")}
          </h1>
          <div className="flex gap-4">
            <ProductLine lab={lab} />
            <DurationLine lab={lab} />
          </div>
          <CategoriesLine lab={lab} />
          <AudienceLine lab={lab} />
          <AuthorizedInfoLines lab={lab} />
        </div>
        {!!me ? (
          <NextLink
            className="w-full"
            href={`/lab?preview=${encodeURIComponent(lab.lab_code)}`}
          >
            {t("lab.enter")}
          </NextLink>
        ) : (
          <div>
            <NextLink className="w-full" href={loginUrl}>
              {t("lab.login-to-enter")}
            </NextLink>
          </div>
        )}
      </div>
      <section className="space-y-4 col-span-12">
        <h2 className="text-lg md:text-xl lg:text-2xl font-semibold">
          {t("lab.description")}
        </h2>
        <p className="text-muted-foreground whitespace-pre-wrap">
          {t(lab, "description")}
        </p>
      </section>
    </>
  );
}

function ProductLine({ lab }: { lab: LabMetaV2 }) {
  const t = useLocaleFunction();

  return (
    <InfoLine>
      <DatabaseIcon />
      {lab.tidb_environments.map((environment, index) => (
        <Fragment key={environment}>
          {index > 0 && ", "}
          <Link
            key={environment}
            className="hover:underline font-semibold text-foreground"
            href={transformPathLocale(`/labs?product=${environment}`, t.locale)}
            prefetch={false}
          >
            {t(tidbEnvironmentLocaleKey(environment) as never)}
          </Link>
        </Fragment>
      ))}
    </InfoLine>
  );
}

function DurationLine({ lab }: { lab: LabMetaV2 }) {
  const t = useLocaleFunction();

  return (
    <InfoLine>
      <ClockIcon />
      {t("lab.duration-minutes", lab.estimated_duration_minutes)}
    </InfoLine>
  );
}

function CategoriesLine({ lab }: { lab: LabMetaV2 }) {
  const t = useLocaleFunction();

  return (
    <InfoLine className="items-baseline">
      <TagIcon />
      <div className="flex gap-2 flex-wrap">
        {([] as string[]).concat(t(lab, "category")).map((category, index) => (
          <Fragment key={category}>
            <Link
              className="hover:bg-blue-100 text-sm font-medium text-blue-600 bg-blue-50 px-2 py-1 rounded"
              href={transformPathLocale(
                `/labs?category=${encodeURIComponent(category)}`,
                t.locale
              )}
              prefetch={false}
            >
              {category}
            </Link>
          </Fragment>
        ))}
      </div>
    </InfoLine>
  );
}

function AudienceLine({ lab }: { lab: LabMetaV2 }) {
  const t = useLocaleFunction();

  return (
    <InfoLine>
      <UsersIcon />
      {lab.target_audience.map((target, index) => (
        <Fragment key={target}>
          <Link
            className="hover:bg-gray-100 text-sm font-medium text-gray-600 bg-gray-50 px-2 py-1 rounded"
            href={transformPathLocale(
              `/labs?target=${encodeURIComponent(target)}`,
              t.locale
            )}
            prefetch={false}
          >
            {t(`lab.meta.audience:${target}`)}
          </Link>
        </Fragment>
      ))}
    </InfoLine>
  );
}

function AuthorizedInfoLines({ lab }: { lab: LabMetaV2 & LabMetaExtra }) {
  const t = useLocaleFunction();

  let infoLine: ReactNode;
  let infoIcon: ReactNode;

  if (lab.can_start) {
    infoLine = (
      <span className="text-sm font-medium text-green-500">
        {t("lab.alerts.ready-to-start")}
      </span>
    );
    infoIcon = <CheckCircleIcon className="text-green-500" />;
  } else if (lab.credit_redeemable) {
    infoLine = (
      <span className="text-sm font-medium text-amber-500">
        {t("lab.alerts.need-credits-to-start", lab.credits)}
      </span>
    );
    infoIcon = <BadgeIcon className="text-amber-500" />;
  } else {
    infoLine = (
      <span className="text-sm font-medium text-red-500">
        {t("lab.alerts.not-eligible-to-start")}
      </span>
    );
    infoIcon = <CircleSlashIcon className="text-red-500" />;
  }

  return (
    <>
      <InfoLine>
        {infoIcon}
        {infoLine}
      </InfoLine>
    </>
  );
}

function InfoLine({
  className,
  children,
}: {
  className?: string;
  children?: ReactNode;
}) {
  return (
    <div
      className={cn(
        "text-muted-foreground flex gap-2 items-center [&>svg:first-of-type]:size-4 [&>svg:first-of-type]:shrink-0",
        className
      )}
    >
      {children}
    </div>
  );
}
