"use client";
import { Paperclip } from "lucide-react";
import {
  Credenza,
  CredenzaTrigger,
  CredenzaContent,
  CredenzaBody,
  CredenzaHeader,
  CredenzaDescription,
  CredenzaTitle,
  CredenzaFooter,
  CredenzaClose,
} from "~/components/custom_ui/credenza";
import { Button, buttonVariants } from "~/components/ui/button";
import { api } from "~/utils/api";
import { LoadingPage } from "~/components/loading";
import Link from "next/link";
import { cn } from "~/lib/utils";
import { ExtIcon } from "~/components/area-riservata/allegati";
import type { Session } from "~/server/api/trpc";
import type { ChatUserInfo } from "~/server/services/chat.service";
import { UploadComponent } from "~/components/upload_modal";
import { useTranslation } from "~/providers/I18nProvider";
import { differenceInDays, differenceInMinutes, format } from "date-fns";

type ChatAttachmentsProps = {
  userData: Session;
  chatUserData: ChatUserInfo;
};
export const ChatAttachments = ({
  userData,
  chatUserData,
}: ChatAttachmentsProps) => {
  const { t } = useTranslation();
  const {
    data: attachments,
    isLoading: attachmentsLoading,
    refetch,
  } = api.storage.getUserStorage.useQuery(
    { userId: chatUserData.id },
    { refetchOnMount: true },
  );

  return (
    <Credenza onOpenChange={(o) => o && refetch()}>
      <CredenzaTrigger asChild>
        <Button
          variant="ghost"
          size="icon"
          className="relative size-9"
          aria-label="Allegati Chat"
        >
          {attachments && attachments.length > 0 && (
            <span className="absolute -top-1 right-0 rounded-full bg-blue-500 px-1 text-xs font-bold text-white">
              {attachments.length}
            </span>
          )}
          <Paperclip size={20} className="text-muted-foreground" />
        </Button>
      </CredenzaTrigger>
      <CredenzaContent className="max-h-[90vh]">
        <CredenzaHeader>
          <CredenzaTitle className="sr-only">Allegati</CredenzaTitle>
          <CredenzaDescription className="sr-only">
            Chat Attachments
          </CredenzaDescription>
        </CredenzaHeader>
        <CredenzaBody className="max-h-[80vh] space-y-3 overflow-auto pb-5">
          <UploadComponent
            isAdmin={userData.isAdmin}
            userId={chatUserData.id}
          />

          <div className="h-auto max-h-[40rem] max-w-lg overflow-auto rounded-lg border-2 border-gray-300 py-4">
            {attachmentsLoading ? (
              <LoadingPage />
            ) : (
              <>
                {!attachments || attachments.length == 0 ? (
                  <div className="flex h-full items-center justify-center">
                    <p className="text-center text-lg font-semibold text-gray-500">
                      {t.allegati.nessun_allegato}
                    </p>
                  </div>
                ) : (
                  <ul className="px-2">
                    <h3 className="px-3 text-lg font-semibold text-gray-700">
                      {t.allegati.allegati_recenti}
                    </h3>
                    {attachments?.map((file, idx) => {
                      if (idx >= 3) return null;

                      return (
                        <li
                          key={`${file.filename}-${idx}`}
                          className="flex items-center justify-between border-b px-3 py-1"
                        >
                          <Link
                            aria-label="Visualizza Allegato"
                            href={`/area-riservata/allegato-view/${file.id}`}
                            target="_blank"
                            className={cn(
                              buttonVariants({
                                variant: "link",
                              }),
                              "flex h-8 items-center gap-2 truncate p-0 text-base",
                            )}
                          >
                            {file.ext && <ExtIcon ext={file.ext} />}
                            <span className="truncate">{file.filename}</span>
                          </Link>
                          <span
                            className="text-muted-foreground text-xs"
                            key={new Date().getTime()}
                          >
                            {TimeSince(file.created_at)}
                          </span>
                        </li>
                      );
                    })}
                  </ul>
                )}
              </>
            )}
          </div>
        </CredenzaBody>
        <CredenzaFooter className="flex flex-row items-center justify-between gap-2">
          <Link
            aria-label="Visualizza Allegati"
            href="/area-riservata/allegati"
            className={cn(
              buttonVariants({
                variant: "outline",
              }),
              "relative w-full",
            )}
          >
            <Paperclip /> {t.allegati.i_tuoi_allegati}
            {attachments && attachments.length > 0 && (
              <span className="absolute -top-1 -right-1 flex size-5 items-center justify-center rounded-full bg-red-600 text-xs text-white">
                {attachments.length}
              </span>
            )}
          </Link>
          <CredenzaClose asChild>
            <Button className="w-full">{t.chiudi}</Button>
          </CredenzaClose>
        </CredenzaFooter>
      </CredenzaContent>
    </Credenza>
  );
};

const TimeSince = (date: Date) => {
  const minsSince = Math.abs(differenceInMinutes(date, new Date()));
  const daysSince = Math.abs(differenceInDays(date, new Date()));

  const relevantMinsIncrements = [1, 3, 5, 10, 15, 30, 60, 120];

  if (daysSince === 0) {
    if (minsSince < 1) {
      return "ora";
    }

    const closestToNow = relevantMinsIncrements.reduce((prev, curr) => {
      return Math.abs(curr - minsSince) < Math.abs(prev - minsSince)
        ? curr
        : prev;
    });

    if (closestToNow === 60) {
      return "~1 ora fa";
    }

    if (closestToNow === 120 && minsSince < 121) {
      return "~2 ore fa";
    }

    return `~${closestToNow} min fa`;
  }

  if (daysSince === 1) {
    return "ieri";
  }

  if (daysSince < 30) {
    return `${daysSince} giorni fa`;
  }

  return format(date, "dd/MM/yyyy");
};
