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 { withI18n } from '~/lib/i18n/with-i18n';
import { PackageHeader } from '@/components/package-header';
import { InfoTooltip } from '@/components/ui/info-tooltip';
import { StoreProduct } from '@medusajs/types';
import type { AnalysisElement } from '~/lib/services/analysis-element.service';
import { getAnalysisElementOriginalIds } from '@lib/data/products';

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

const ComparePackagesModal = async ({
  analysisElements,
  analysisPackages,
  triggerElement,
}: {
  analysisElements: AnalysisElement[];
  analysisPackages: StoreProduct[];
  triggerElement: JSX.Element;
}) => {
  const { t, language } = 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 = await getAnalysisElementOriginalIds([standardPackage]);
  const standardPlusPackageAnalyses = await getAnalysisElementOriginalIds([standardPlusPackage]);
  const premiumPackageAnalyses = await getAnalysisElementOriginalIds([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>
                    {analysisPackages.map(
                      (product) => {
                        const variant = product.variants?.[0];
                        const titleKey = product.title;
                        const price = variant?.calculated_price?.calculated_amount ?? 0;
                        return (
                          <TableHead key={titleKey} className="py-2">
                            <PackageHeader
                              title={t(titleKey)}
                              tagColor='bg-cyan'
                              analysesNr={t('product:nrOfAnalyses', {
                                nr: product?.metadata?.nrOfAnalyses ?? 0,
                              })}
                              language={language}
                              price={price}
                            />
                          </TableHead>
                        )
                      })}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {analysisElements.map(
                    (
                      {
                        analysis_name_lab: analysisName,
                        analysis_id_original: analysisId,
                      },
                      index,
                    ) => {
                      if (!analysisName) {
                        return null;
                      }
                      const includedInStandard = standardPackageAnalyses.includes(analysisId);
                      const includedInStandardPlus = standardPlusPackageAnalyses.includes(analysisId);
                      const includedInPremium = premiumPackageAnalyses.includes(analysisId);
                      return (
                        <TableRow key={index}>
                          <TableCell className="py-6">
                            {analysisName}{' '}
                            {/* <InfoTooltip
                              content={t(tooltipContentKey)}
                              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);
