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

type EditUserProps = {
	userId: UsersId;
};

/**
 * Pagina di modifica utente per admin: /area-riservata/admin/user-view/edit-user/[userId]
 */
const EditUser: NextPageWithLayout<EditUserProps> = ({
	userId,
}: EditUserProps) => {
	const router = useRouter();
	const utils = api.useUtils();
	const { data: userData, isLoading } = api.users.getClientProfilo.useQuery({
		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({
				userId,
			});
			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 className="w-full space-y-6" defaultValue="account">
				<div className="flex flex-row flex-wrap justify-between gap-2">
					<div className="flex flex-col gap-2">
						<h3 className="font-bold text-2xl">Profilo</h3>
						<div>
							<TabsList>
								<TabsTrigger
									className="flex items-center gap-1"
									value="account"
								>
									<UserCircle className="size-5" /> Account
								</TabsTrigger>
								<TabsTrigger
									className="flex items-center gap-1"
									value="anagrafica"
								>
									<Fingerprint className="size-5" />
									Anagrafica
								</TabsTrigger>
								<TabsTrigger
									className="flex items-center gap-1"
									value="documenti"
								>
									<IdCard className="size-5" />
									Documenti
								</TabsTrigger>
								<TabsTrigger
									className="flex items-center gap-1"
									value="password"
								>
									<KeyRound className="size-5" />
									Password
								</TabsTrigger>
								<TabsTrigger
									className="flex items-center gap-1"
									value="fatture"
								>
									<Landmark className="size-5" />
									Fatture
								</TabsTrigger>
							</TabsList>
						</div>
					</div>
				</div>

				<TabsContent value="account">
					<Card>
						<CardContent className="space-y-6">
							<ProfileFormAccount
								cognome={userData.cognome}
								email={userData.email}
								extra_telefono_numero={userData.extra_telefono_numero}
								extra_telefono_titolo={userData.extra_telefono_titolo}
								id={userData.id}
								isAdmin={userData.isAdmin}
								nome={userData.nome}
								telefono={userData.telefono}
							/>
							<Separator />
							<div className="flex flex-wrap items-end gap-2">
								<AlertDialog>
									<AlertDialogTrigger asChild>
										<Button variant={userData.isBlocked ? "success" : "orange"}>
											{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">
											<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>
						</CardContent>
					</Card>
				</TabsContent>
				<TabsContent value="anagrafica">
					<CatastoProvider>
						<Card>
							<CardContent>
								<ProfileFormAnagrafica userData={userData} />
							</CardContent>
						</Card>
					</CatastoProvider>
				</TabsContent>
				<TabsContent value="documenti">
					<DocumentiPersonali userData={userData} />
				</TabsContent>
				<TabsContent className="space-y-4" value="password">
					<Card>
						<CardContent>
							<MustChangePasswordForm
								id={userData.id}
								mustChangePassword={userData.mustChangePassword}
							/>
						</CardContent>
					</Card>
					<Card>
						<CardContent>
							<OverridePasswordForm id={userData.id} />
						</CardContent>
					</Card>
				</TabsContent>
				<TabsContent className="space-y-6" value="fatture">
					{userData.codice_fiscale ? (
						<FatturazioneData
							cf={userData.codice_fiscale}
							userId={userData.id}
						/>
					) : (
						<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("it-IT")}</p>
					{userData.isAdminMade && <p>Utente creato da Admin</p>}
				</div>
			</Tabs>
		</div>
	);
};
export default EditUser;

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

	const parsed = zUserId.safeParse(userId);

	if (!parsed.success) {
		return {
			notFound: true,
		};
	}
	const access_token = context.req.cookies.access_token;

	const helpers = await TrpcAuthedFetchingIstance({ access_token });
	if (helpers) {
		await helpers.trpc.users.getClientProfilo.prefetch({
			userId: parsed.data,
		});
		return {
			props: {
				userId: parsed.data,
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		notFound: true,
	};
}) satisfies GetServerSideProps<EditUserProps>;

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

const FatturazioneData = ({ userId, cf }: { userId: UsersId; cf: string }) => {
	const { data, isLoading } = api.fatture.getClientFromCF.useQuery({
		cf,
	});
	const utils = api.useUtils();
	const { mutate: export_mutate } = api.fatture.addToFIC.useMutation({
		onSuccess: async () => {
			await utils.users.getClientProfilo.invalidate();
			await utils.fatture.getClientFromCF.invalidate();
			toast.success("Utente esportato con successo su Fatture In Cloud");
		},
		onError: (error) => {
			toast.error(
				`Errore durante l'esportazione su Fatture In Cloud: ${error.message}`,
			);
		},
	});

	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, i) => (
					<div className="space-y-4" key={client.id || i}>
						<h3 className="font-semibold text-lg">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>
				))
			) : (
				<div className="space-y-4">
					<p>Nessun dato trovato per il codice fiscale {cf}</p>

					<Button
						onClick={() => {
							export_mutate({
								userId,
							});
						}}
					>
						Esporta su Fatture In Cloud
					</Button>
				</div>
			)}
		</>
	);
};
