import { JSX } from 'react';

import { StoreProduct } from '@medusajs/types';
import { QuestionMarkCircledIcon } from '@radix-ui/react-icons';
import { VisuallyHidden } from '@radix-ui/react-visually-hidden';
import { Check, X } from 'lucide-react';

import { PackageHeader } from '@kit/shared/components/package-header';
import { AnalysisPackageWithVariant } from '@kit/shared/components/select-analysis-package';
import { InfoTooltip } from '@kit/shared/components/ui/info-tooltip';
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogTrigger,
} from '@kit/ui/dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@kit/ui/table';

import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
import { withI18n } from '~/lib/i18n/with-i18n';

import ComparePackagesAddToCartButtons from './compare-packages-add-to-cart-buttons';
import DefaultPackageFeaturesRows from './default-package-features-rows';

export type AnalysisPackageElement = Pick<
  StoreProduct,
  'title' | 'id' | 'description'
> & {
  isIncludedInStandard: boolean;
  isIncludedInStandardPlus: boolean;
  isIncludedInPremium: boolean;
};

export const CheckWithBackground = () => {
  return (
    <div className="bg-primary w-min rounded-full p-1 text-white">
      <Check className="size-3 stroke-2" />
    </div>
  );
};

const PackageTableHead = async ({
  product,
}: {
  product: AnalysisPackageWithVariant;
}) => {
  const { t, language } = await createI18nServerInstance();

  const { title, price, nrOfAnalyses } = product;

  return (
    <TableHead className="xs:content-normal content-start py-2">
      <PackageHeader
        title={t(title)}
        tagColor="bg-cyan"
        analysesNr={t('product:nrOfAnalyses', { nr: nrOfAnalyses })}
        language={language}
        price={price}
      />
    </TableHead>
  );
};

const ComparePackagesModal = async ({
  analysisPackages,
  analysisPackageElements,
  triggerElement,
  countryCode,
}: {
  analysisPackages: AnalysisPackageWithVariant[];
  analysisPackageElements: AnalysisPackageElement[];
  triggerElement: JSX.Element;
  countryCode: string;
}) => {
  const { t } = await createI18nServerInstance();

  const standardPackage = analysisPackages.find(({ isStandard }) => isStandard);
  const standardPlusPackage = analysisPackages.find(
    ({ isStandardPlus }) => isStandardPlus,
  );
  const premiumPackage = analysisPackages.find(({ isPremium }) => isPremium);

  if (!standardPackage || !standardPlusPackage || !premiumPackage) {
    return null;
  }

  return (
    <Dialog>
      <DialogTrigger asChild>{triggerElement}</DialogTrigger>
      <DialogContent
        className="min-h-screen max-w-fit min-w-screen"
        customClose={
          <div className="inline-flex place-items-center-safe gap-1 align-middle">
            <p className="text-sm font-medium text-black">
              {t('common:close')}
            </p>
            <X className="text-black" />
          </div>
        }
        preventAutoFocus
      >
        <VisuallyHidden>
          <DialogTitle>{t('common:comparePackages')}</DialogTitle>
        </VisuallyHidden>
        <div className="m-auto">
          <div className="space-y-6 text-center">
            <h3>{t('product:healthPackageComparison.label')}</h3>
            <p className="text-muted-foreground mx-auto w-3/5 text-sm">
              {t('product:healthPackageComparison.description')}
            </p>
            <div className="max-h-[50vh] overflow-y-auto rounded-md border sm:max-h-[70vh]">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead></TableHead>
                    <PackageTableHead product={standardPackage} />
                    <PackageTableHead product={standardPlusPackage} />
                    <PackageTableHead product={premiumPackage} />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  <DefaultPackageFeaturesRows />

                  {analysisPackageElements.map(
                    ({
                      title,
                      id,
                      description,
                      isIncludedInStandard,
                      isIncludedInStandardPlus,
                      isIncludedInPremium,
                    }) => {
                      if (!title) {
                        return null;
                      }

                      return (
                        <TableRow key={id}>
                          <TableCell className="py-6 sm:w-[30vw]">
                            {title}{' '}
                            {description && (
                              <InfoTooltip
                                content={description}
                                icon={<QuestionMarkCircledIcon />}
                              />
                            )}
                          </TableCell>
                          <TableCell align="center" className="py-6">
                            {isIncludedInStandard && <CheckWithBackground />}
                          </TableCell>
                          <TableCell align="center" className="py-6">
                            {isIncludedInStandardPlus && (
                              <CheckWithBackground />
                            )}
                          </TableCell>
                          <TableCell align="center" className="py-6">
                            {isIncludedInPremium && <CheckWithBackground />}
                          </TableCell>
                        </TableRow>
                      );
                    },
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
          <ComparePackagesAddToCartButtons
            countryCode={countryCode}
            standardPackage={standardPackage}
            premiumPackage={premiumPackage}
            standardPlusPackage={standardPlusPackage}
          />
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default withI18n(ComparePackagesModal);
