import { JSX } from 'react';

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

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 { PackageHeader } from '@kit/shared/components/package-header';
import { InfoTooltip } from '@kit/shared/components/ui/info-tooltip';
import { StoreProduct } from '@medusajs/types';
import { getAnalysisElementMedusaProductIds } from '@/utils/medusa-product';
import { withI18n } from '@/lib/i18n/with-i18n';

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, nrOfAnalyses }: { product: StoreProduct, nrOfAnalyses: number }) => {
  const { t, language } = await createI18nServerInstance();
  const variant = product.variants?.[0];
  const titleKey = product.title;
  const price = variant?.calculated_price?.calculated_amount ?? 0;
  return (
    <TableHead className="py-2">
      <PackageHeader
        title={t(titleKey)}
        tagColor='bg-cyan'
        analysesNr={t('product:nrOfAnalyses', { nr: nrOfAnalyses })}
        language={language}
        price={price}
      />
    </TableHead>
  )
}

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

  const standardPackage = analysisPackages.find(({ metadata }) => metadata?.analysisPackageTier === 'standard')!;
  const standardPlusPackage = analysisPackages.find(({ metadata }) => metadata?.analysisPackageTier === 'standard-plus')!;
  const premiumPackage = analysisPackages.find(({ metadata }) => metadata?.analysisPackageTier === 'premium')!;

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

  const standardPackageAnalyses = getAnalysisElementMedusaProductIds([standardPackage]);
  const standardPlusPackageAnalyses = getAnalysisElementMedusaProductIds([standardPlusPackage]);
  const premiumPackageAnalyses = getAnalysisElementMedusaProductIds([premiumPackage]);

  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="rounded-md border max-h-[80vh] overflow-y-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead></TableHead>
                    <PackageTableHead product={standardPackage} nrOfAnalyses={standardPackageAnalyses.length} />
                    <PackageTableHead product={standardPlusPackage} nrOfAnalyses={standardPlusPackageAnalyses.length} />
                    <PackageTableHead product={premiumPackage} nrOfAnalyses={premiumPackageAnalyses.length} />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {analysisPackageElements.map(
                    (
                      {
                        title,
                        id,
                        description,
                      },
                      index,
                    ) => {
                      if (!title) {
                        return null;
                      }
                      const includedInStandard = standardPackageAnalyses.includes(id);
                      const includedInStandardPlus = standardPlusPackageAnalyses.includes(id);
                      const includedInPremium = premiumPackageAnalyses.includes(id);
                      return (
                        <TableRow key={index}>
                          <TableCell className="py-6">
                            {title}{' '}
                            {description && (<InfoTooltip content={description} icon={<QuestionMarkCircledIcon />} />)}
                          </TableCell>
                          <TableCell align="center" className="py-6">
                            {includedInStandard && <CheckWithBackground />}
                          </TableCell>
                          <TableCell align="center" className="py-6">
                            {(includedInStandard || includedInStandardPlus) && <CheckWithBackground />}
                          </TableCell>
                          <TableCell align="center" className="py-6">
                            {(includedInStandard || includedInStandardPlus || includedInPremium) && <CheckWithBackground />}
                          </TableCell>
                        </TableRow>
                      );
                    })}
                </TableBody>
              </Table>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default withI18n(ComparePackagesModal);
