'use client';

import { formatCurrency } from '@/packages/shared/src/utils';
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
import { Loader2 } from 'lucide-react';
import { useFormContext } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

import { Button } from '@kit/ui/button';
import { Card, CardContent, CardHeader } from '@kit/ui/card';
import { Checkbox } from '@kit/ui/checkbox';
import { FormControl, FormField, FormItem, FormLabel } from '@kit/ui/form';
import { Trans } from '@kit/ui/trans';

import { cn } from '~/lib/utils';

import AnalysisLocation from './analysis-location';
import CartItems from './cart-items';
import CartServiceItems from './cart-service-items';
import DiscountCode from './discount-code';
import { EnrichedCartItem, GetBalanceSummarySelection } from './types';

const IS_DISCOUNT_SHOWN = true as boolean;

export default function CartFormContent({
  cart,
  synlabAnalyses,
  ttoServiceItems,
  unavailableLineItemIds,
  isInitiatingSession,
  getBalanceSummarySelection,
}: {
  cart: StoreCart;
  synlabAnalyses: StoreCartLineItem[];
  ttoServiceItems: EnrichedCartItem[];
  unavailableLineItemIds?: string[];
  isInitiatingSession: boolean;
  getBalanceSummarySelection: GetBalanceSummarySelection;
}) {
  const {
    i18n: { language },
  } = useTranslation();
  const { watch } = useFormContext();

  const items = cart?.items ?? [];
  const hasCartItems = cart && Array.isArray(items) && items.length > 0;

  const isLocationsShown = synlabAnalyses.length > 0;

  const useCompanyBenefits = watch('useCompanyBenefits');
  const balanceSummary = getBalanceSummarySelection({ useCompanyBenefits });

  const { benefitsAmount, benefitsAmountTotal, montonioAmount } =
    balanceSummary;

  const hasBenefitsApplied = benefitsAmountTotal > 0 && !!useCompanyBenefits;

  return (
    <>
      <div className="flex flex-col gap-y-6 bg-white">
        <CartItems
          cart={cart}
          items={synlabAnalyses}
          productColumnLabelKey="cart:items.synlabAnalyses.productColumnLabel"
        />
        <CartServiceItems
          cart={cart}
          items={ttoServiceItems}
          productColumnLabelKey="cart:items.ttoServices.productColumnLabel"
          unavailableLineItemIds={unavailableLineItemIds}
        />
      </div>
      {hasCartItems && (
        <>
          <div className="flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4">
            <div className="w-full sm:mr-[42px] sm:w-auto">
              <p className="text-muted-foreground ml-0 text-sm font-bold">
                <Trans i18nKey="cart:order.subtotal" />
              </p>
            </div>
            <div className={`sm:mr-[112px] sm:w-[50px]`}>
              <p className="text-right text-sm">
                {formatCurrency({
                  value: cart.subtotal,
                  currencyCode: cart.currency_code,
                  locale: language,
                })}
              </p>
            </div>
          </div>
          <div
            className={cn(
              'flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4',
              {
                'py-2 sm:py-4': !hasBenefitsApplied,
              },
            )}
          >
            <div className="w-full sm:mr-[42px] sm:w-auto">
              <p className="text-muted-foreground ml-0 text-sm font-bold">
                <Trans i18nKey="cart:order.promotionsTotal" />
              </p>
            </div>
            <div className={`sm:mr-[112px] sm:w-[50px]`}>
              <p className="text-right text-sm">
                {formatCurrency({
                  value: cart.discount_total,
                  currencyCode: cart.currency_code,
                  locale: language,
                })}
              </p>
            </div>
          </div>
          {hasBenefitsApplied && (
            <div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
              <div className="w-full sm:mr-[42px] sm:w-auto">
                <p className="text-muted-foreground ml-0 text-sm font-bold">
                  <Trans i18nKey="cart:order.companyBenefitsTotal" />
                </p>
              </div>
              <div className={`sm:mr-[112px] sm:w-[50px]`}>
                <p className="text-right text-sm">
                  {formatCurrency({
                    value: benefitsAmount,
                    currencyCode: cart.currency_code,
                    locale: language,
                  })}
                </p>
              </div>
            </div>
          )}
          <div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
            <div className="w-full sm:mr-[42px] sm:w-auto">
              <p className="ml-0 text-sm font-bold">
                <Trans i18nKey="cart:order.total" />
              </p>
            </div>
            <div className={`sm:mr-[112px] sm:w-[50px]`}>
              <p className="text-right text-sm">
                {formatCurrency({
                  value: montonioAmount,
                  currencyCode: cart.currency_code,
                  locale: language,
                })}
              </p>
            </div>
          </div>

          {benefitsAmountTotal > 0 && (
            <FormField
              name="useCompanyBenefits"
              render={({ field }) => (
                <FormItem className="mt-8">
                  <div className="flex flex-row items-center gap-2 pb-1">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <FormLabel>
                      <Trans i18nKey={'cart:companyBenefits.label'} />
                    </FormLabel>
                  </div>
                </FormItem>
              )}
            />
          )}
        </>
      )}

      <div className="flex flex-col gap-x-4 gap-y-6 py-4 sm:flex-row sm:py-8">
        {IS_DISCOUNT_SHOWN && (
          <Card className="flex w-full flex-col justify-between sm:w-1/2">
            <CardHeader className="pb-4">
              <h5>
                <Trans i18nKey="cart:discountCode.title" />
              </h5>
            </CardHeader>
            <CardContent className="h-full">
              <DiscountCode cart={{ ...cart }} />
            </CardContent>
          </Card>
        )}

        {isLocationsShown && (
          <Card className="flex w-full flex-col justify-between sm:w-1/2">
            <CardHeader className="pb-4">
              <h5>
                <Trans i18nKey="cart:locations.title" />
              </h5>
            </CardHeader>
            <CardContent className="h-full">
              <AnalysisLocation
                cart={{ ...cart }}
                synlabAnalyses={synlabAnalyses}
              />
            </CardContent>
          </Card>
        )}
      </div>

      <div>
        <Button className="h-10" type="submit" disabled={isInitiatingSession}>
          {isInitiatingSession && (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          )}
          <Trans i18nKey="cart:checkout.goToCheckout" />
        </Button>
      </div>
    </>
  );
}
