import { useServizioAnnuncio } from "~/providers/ServizioProvider";
import { Interactions } from "~/components/servizio/interactions";
import type { Annunci } from "~/schemas/public/Annunci";
import { useTranslation } from "~/providers/I18nProvider";
import { cn, formatCurrency } from "~/lib/utils";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
import { ImageFlbk } from "~/components/ImageWithFallback";
import { Button } from "~/components/ui/button";
import { ExternalLink, UnfoldVertical } from "lucide-react";
import Link from "next/link";
import { handleConsegna } from "~/lib/annuncio_details";
import {
  Credenza,
  CredenzaBody,
  CredenzaClose,
  CredenzaContent,
  CredenzaDescription,
  CredenzaFooter,
  CredenzaHeader,
  CredenzaTitle,
  CredenzaTrigger,
} from "~/components/custom_ui/credenza";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "~/components/ui/carousel";
import { AnnuncioActions } from "~/components/servizio/annuncio_actions";

export const AnnuncioCard = ({ className }: { className?: string }) => {
  const { data } = useServizioAnnuncio();

  return (
    <BasicAnnuncioCard
      data={data}
      className={className}
      actions={<AnnuncioActions />}
      interactions={<Interactions />}
    />
  );
};
export const BasicAnnuncioCard = ({
  actions,
  interactions,
  className,
  data,
}: {
  actions?: React.ReactNode;
  interactions?: React.ReactNode;
  className?: string;
  data: Pick<
    Annunci,
    | "id"
    | "codice"
    | "prezzo"
    | "desc_en"
    | "desc_it"
    | "url_immagini"
    | "titolo_en"
    | "titolo_it"
    | "tipo"
    | "consegna"
    | "stato"
    | "web"
  >;
}) => {
  const { t } = useTranslation();

  return (
    <Card className={cn("w-full border-white py-5", className)}>
      <CardHeader className="flex flex-row flex-wrap items-center justify-between space-y-0 pb-0">
        <CardTitle className="text-2xl">Codice: {data.codice}</CardTitle>
        {actions}
      </CardHeader>
      <CardContent className="px-4">
        <div className="flex w-full flex-col gap-4 md:flex-row md:gap-10">
          <ImageFlbk
            src={
              (data.url_immagini &&
                `/go-api/images/get/${data.url_immagini[0]}`) ||
              "/fallback-image.png"
            }
            priority
            width={1920}
            height={1080}
            className="h-auto w-full rounded-md object-contain sm:max-w-xs"
            alt={data.codice}
          />
          <div className="flex w-full flex-col gap-5">
            {interactions}

            <div className="flex flex-wrap items-center gap-3">
              <TipoBadge tipo={data.tipo} />
              <span>
                {handleConsegna({
                  consegna: data.consegna,
                  consegna_da: t.card.consegna_da,
                  mesi: t.preferenze.mesi,
                  subito: t.card.consegna_subito,
                  aggiornamento: t.card.in_aggiornamento,
                })}
              </span>
              <span>{formatCurrency(data.prezzo / 1e2)}</span>
            </div>
            <div className="flex w-full flex-wrap items-center gap-5">
              <span className="text-wrap">{data.titolo_it || data.codice}</span>
              <div className="flex flex-wrap items-center gap-2">
                <AnnuncioDettaglio data={data} />
                {data.stato !== "Sospeso" && data.web && (
                  <Link
                    href={`/annuncio/${data.codice}`}
                    aria-label="Pagina Annuncio"
                  >
                    <Button
                      variant="outline"
                      className="flex items-center gap-2"
                    >
                      <ExternalLink className="size-6" />
                    </Button>
                  </Link>
                )}
              </div>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

const TipoBadge = ({ tipo }: { tipo: Annunci["tipo"] }) => {
  return (
    <div
      className={cn(
        "flex w-fit items-center justify-center rounded-md px-3",
        tipo === "Transitorio" && "bg-orange-400",
        tipo === "Stabile" && "bg-red-400",
        tipo === "Cessione" && "bg-blue-400",
        tipo === "Vendita" && "bg-green-400",
      )}
    >
      <div className="font-semibold text-white">{tipo}</div>
    </div>
  );
};

const AnnuncioDettaglio = ({
  data,
}: {
  data: Pick<
    Annunci,
    | "id"
    | "codice"
    | "prezzo"
    | "desc_en"
    | "desc_it"
    | "url_immagini"
    | "titolo_en"
    | "titolo_it"
    | "tipo"
    | "consegna"
    | "stato"
    | "web"
  >;
}) => {
  const { locale, t } = useTranslation();
  function replaceWithBr(text: string) {
    return text.replace(/\n/g, "<br />");
  }
  return (
    <Credenza>
      <CredenzaTrigger asChild>
        <Button
          variant="outline"
          className="flex items-center gap-2"
          aria-label="Dettagli Annuncio"
        >
          <UnfoldVertical className="size-6" /> Dettagli annuncio
        </Button>
      </CredenzaTrigger>
      <CredenzaContent className="max-h-[90vh] md:max-w-6xl">
        <CredenzaHeader>
          <CredenzaTitle className="text-xl">
            Annuncio {data.codice}
          </CredenzaTitle>
          <CredenzaDescription className="sr-only">
            Annuncio {data.codice}
          </CredenzaDescription>
        </CredenzaHeader>
        <CredenzaBody className="scrollbar-default max-h-[80vh] overflow-y-auto pb-5">
          <div className="flex flex-col gap-2 px-2">
            <Carousel opts={{ loop: true }}>
              <CarouselContent>
                {data.url_immagini &&
                  data.url_immagini.map((img, idx) => (
                    <CarouselItem key={img}>
                      <ImageFlbk
                        alt={`${data.codice} - ${idx}`}
                        width={400}
                        height={200}
                        priority={idx === 0}
                        src={`/go-api/images/get/${img}`}
                        className={"h-80 w-full object-contain sm:h-[35rem]"}
                      />
                    </CarouselItem>
                  ))}
              </CarouselContent>
              <div
                onKeyDown={(e) => e.stopPropagation()}
                role="button"
                tabIndex={0}
                onClick={(e) => e.preventDefault()}
                className="block opacity-0 transition-all duration-200 group-hover:opacity-60 disabled:group-hover:opacity-0"
              >
                <CarouselPrevious
                  className="left-2 cursor-pointer"
                  disabled={
                    !data.url_immagini || data.url_immagini.length === 1
                  }
                />
                <CarouselNext
                  className="right-2 cursor-pointer"
                  disabled={
                    !data.url_immagini || data.url_immagini.length === 1
                  }
                />
              </div>
            </Carousel>
            <div>
              <TipoBadge tipo={data.tipo} />

              <div className="mt-1 space-y-2">
                <div className="flex flex-row justify-around">
                  <div className="text-center">
                    <dt className="sr-only">{t.card.codice}</dt>

                    <dd className="text-lg font-semibold">
                      Cod: {data.codice}
                    </dd>
                  </div>
                  <div className="text-center">
                    <dt className="sr-only">{t.card.prezzo}</dt>

                    <dd className="text-lg font-semibold">
                      {formatCurrency(data.prezzo / 1e2)}
                    </dd>
                  </div>
                </div>

                <div className="mb-3">
                  <dt className="sr-only">{t.card.titolo}</dt>

                  <dd className="text-base font-semibold md:text-lg">
                    {locale === "it" ? data.titolo_it : data.titolo_en}
                  </dd>
                </div>

                <div className="mb-3">
                  <dd
                    className="text-base"
                    dangerouslySetInnerHTML={{
                      __html: replaceWithBr(
                        (locale === "it" ? data.desc_it : data.desc_it) || "",
                      ),
                    }}
                  />
                </div>
              </div>
            </div>
          </div>
        </CredenzaBody>
        <CredenzaFooter>
          <CredenzaClose asChild>
            <Button aria-label="Chiudi Credenza">Chiudi</Button>
          </CredenzaClose>
        </CredenzaFooter>
      </CredenzaContent>
    </Credenza>
  );
};
