import { LoadingPage } from "~/components/loading";
import { api } from "~/utils/api";
import { Separator } from "~/components/ui/separator";
import type { GetStaticProps } from "next";
import type { NextPageWithLayout } from "~/pages/_app";
import { OverridePasswordForm } from "~/forms/FormOverridePassword";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "~/components/ui/alert-dialog";
import toast from "react-hot-toast";
import { useRouter } from "next/router";
import { Button } from "~/components/ui/button";
import {
  Fingerprint,
  KeyRound,
  Landmark,
  Lock,
  Trash2,
  Unlock,
  UserCircle,
} from "lucide-react";
import { AreaRiservataLayoutUserView } from "~/components/Layout";
import { Status500 } from "~/components/status-page";
import type { UsersId } from "~/schemas/public/Users";
import { ProfileFormAccount } from "~/forms/FormProfilo_Account";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs";
import { ProfileFormAnagrafica } from "~/forms/FormProfilo_Anagrafica";
import { zUserId } from "~/server/utils/zod_types";

type EditUserProps = {
  userId: UsersId;
};

const EditUser: NextPageWithLayout<EditUserProps> = ({
  userId,
}: EditUserProps) => {
  const router = useRouter();
  const utils = api.useUtils();
  const { data: userData, isLoading } = api.users.getClientProfilo.useQuery({
    id: userId,
  });
  const { mutate: delete_mutate } = api.users.deleteUser.useMutation({
    onSuccess: async () => {
      await utils.users.getUsers.invalidate();
      //await refreshUsers();
      toast.success("Utente eliminato con successo");
      await router.push("/area-riservata/admin/utenti");
    },
  });

  const { mutate: ban_mutate } = api.users.blockUser.useMutation({
    onSuccess: async (data) => {
      await utils.users.getUsers.invalidate();
      await utils.users.getClientProfilo.invalidate();
      if (data[0]?.isBlocked) {
        toast("Utente bloccato con successo", { icon: "🔒" });
      } else {
        toast("Utente sbloccato con successo", { icon: "🔓" });
      }
    },
  });

  if (isLoading) return <LoadingPage />;
  if ((!isLoading && !userData) || userData == null) return <Status500 />;

  return (
    <div className="w-full space-y-6">
      <Tabs defaultValue="account" className="w-full space-y-6">
        <div className="flex flex-row flex-wrap justify-between gap-2">
          <div className="flex flex-col gap-2">
            <h3 className="text-2xl font-bold">Profilo</h3>
            <div>
              <TabsList>
                <TabsTrigger
                  value="account"
                  className="flex items-center gap-1"
                >
                  <UserCircle className="size-5" /> Account
                </TabsTrigger>
                <TabsTrigger
                  value="anagrafica"
                  className="flex items-center gap-1"
                >
                  <Fingerprint className="size-5" />
                  Anagrafica
                </TabsTrigger>
                <TabsTrigger
                  value="password"
                  className="flex items-center gap-1"
                >
                  <KeyRound className="size-5" />
                  Password
                </TabsTrigger>
                <TabsTrigger
                  value="fatture"
                  className="flex items-center gap-1"
                >
                  <Landmark className="size-5" />
                  Fatture
                </TabsTrigger>
              </TabsList>
            </div>
          </div>
        </div>

        <TabsContent value="account" className="mt-5 space-y-6">
          <ProfileFormAccount
            id={userData.id}
            nome={userData.nome}
            cognome={userData.cognome}
            email={userData.email}
            telefono={userData.telefono}
            isAdmin={userData.isAdmin}
          />
          <Separator />
          <div className="flex flex-wrap items-end gap-2">
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button
                  variant={userData.isBlocked ? "success" : "orange"}
                  className="flex items-center gap-2"
                >
                  {userData.isBlocked ? (
                    <>
                      <Unlock className="size-4" />
                      <span>Sblocca accesso al sito</span>
                    </>
                  ) : (
                    <>
                      <Lock className="size-4" />
                      <span>Blocca accesso al sito</span>
                    </>
                  )}
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Sei sicuro?</AlertDialogTitle>
                  <AlertDialogDescription>
                    Vuoi procedere a bloccare/sbloccare l&apos;utente?
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Annulla</AlertDialogCancel>
                  <AlertDialogAction
                    onClick={() => ban_mutate({ id: userData.id })}
                  >
                    Continua
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button
                  variant="destructive"
                  className="flex items-center gap-2"
                >
                  <Trash2 className="size-4" /> Elimina utente permanentemente
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Sei sicuro?</AlertDialogTitle>
                  <AlertDialogDescription>
                    Questa azione non può essere annullata.
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Annulla</AlertDialogCancel>
                  <AlertDialogAction
                    onClick={() => delete_mutate({ id: userData.id })}
                  >
                    Continua
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </div>
        </TabsContent>
        <TabsContent value="anagrafica" className="mt-5 h-full space-y-6">
          <ProfileFormAnagrafica userData={userData} />
        </TabsContent>
        <TabsContent value="password" className="mt-5 space-y-6">
          <OverridePasswordForm id={userData.id} />
        </TabsContent>
        <TabsContent value="fatture" className="mt-5 space-y-6">
          {userData.codice_fiscale ? (
            <FatturazioneData cf={userData.codice_fiscale} />
          ) : (
            <p>Codice Fiscale non disponibile per questo utente.</p>
          )}
        </TabsContent>
        <Separator />
        <div className="flex flex-col gap-2">
          <h4 className="font-medium">Utente registrato il:</h4>
          <p>{userData.created_at?.toLocaleString()}</p>
          {userData.isAdminMade && <p>Utente creato da Admin</p>}
        </div>
      </Tabs>
    </div>
  );
};
export default EditUser;

export const getStaticProps: GetStaticProps = (context) => {
  const userId = context.params?.userId;
  if (typeof userId !== "string") {
    return {
      notFound: true,
    };
  }

  const parsed = zUserId.safeParse(userId);

  if (!parsed.success) {
    {
      return {
        notFound: true,
      };
    }
  }

  return {
    props: {
      userId: parsed.data,
    },
  };
};

export const getStaticPaths = () => {
  return { paths: [], fallback: "blocking" };
};

EditUser.getLayout = function getLayout(page) {
  return <AreaRiservataLayoutUserView>{page}</AreaRiservataLayoutUserView>;
};

const FatturazioneData = ({ cf }: { cf: string }) => {
  const { data, isLoading } = api.fatture.getClientFromCF.useQuery({
    cf,
  });

  if (isLoading) return <LoadingPage />;
  if (!data)
    return (
      <span>
        Errore nel recupero dei dati per il codice fiscale {cf}. Assicurati che
        sia corretto.
      </span>
    );

  return (
    <>
      {data.data && data.data.length > 0 ? (
        data.data.map((client, idx) => (
          <div className="space-y-4" key={idx}>
            <h3 className="text-lg font-semibold">Dati Fatturazione</h3>
            <p>Nome: {client.name}</p>
            <p>Codice Fiscale: {client.tax_code}</p>
            <p>Partita IVA: {client.vat_number}</p>
            <p>
              Indirizzo: {client.address_street}, {client.address_city}
            </p>
            <p>CAP: {client.address_postal_code}</p>
            <p>Provincia: {client.address_province}</p>
          </div>
        ))
      ) : (
        <span>Nessun dato trovato per il codice fiscale {cf}</span>
      )}
    </>
  );
};
