import { Button } from "@/shared/components/ui/button";
import { useTransition } from "react";
import { toast } from "sonner";
import { useUnsyncSite } from "../hooks/use-unsync-site";
import { Field, FieldContent, FieldLabel } from "@/shared/components/ui/field";
import { Typography } from "@/shared/components/ui/typography";
import { APP_NAME } from "@/shared/config/app";
import { resendCode } from "../api/resend-code";
import { useAlert } from "@/shared/hooks/use-alert";
import { HTTPError } from "ky";

interface UnsyncSiteFormProps {
	siteId: string;
	isConfirmed: boolean;
}

export const UnsyncSiteForm = ({
	siteId,
	isConfirmed,
}: UnsyncSiteFormProps) => {
	const { mutateAsync } = useUnsyncSite(siteId);
	const [isPending, startTransition] = useTransition();
	const alert = useAlert();

	return (
		<form>
			<Field>
				<FieldContent>
					<FieldLabel>Синхронизация с сайтом</FieldLabel>
				</FieldContent>
				{isConfirmed ? (
					<Button
						variant={"destructive"}
						disabled={isPending}
						onClick={() => {
							startTransition(async () => {
								try {
									const t = await mutateAsync();
									toast.info(t.message);
								} catch (error) {
									if (
										error instanceof HTTPError &&
										error.response.status === 403
									) {
										toast.error("У вас недостаточно прав для этого");
									} else {
										toast.error("Что то пошло не так");
									}
								}
							});
						}}
					>
						Рассинхронизировать
					</Button>
				) : (
					<Button
						variant={"secondary"}
						disabled={isPending}
						onClick={() => {
							startTransition(async () => {
								const t = await (resendCode({
									pathParams: { id: siteId },
								}) as Promise<{
									otp: string;
									expiresAt: string;
								}>);
								alert.alert({
									title: "Код подтверждения синхронизации",
									content: () => (
										<div>
											<Typography variant="large">
												Осталось совсем чуть-чуть!
											</Typography>
											<div className="prose dark:prose-invert">
												<ol>
													<li>Скопируйте код ниже</li>
													<li>
														Зайдите в админ-панель вашего сайта и перейдите в
														раздел {APP_NAME}
													</li>
													<li>
														Вставьте скопированный код и нажмите
														синхронизировать
													</li>
													<li>Готово!</li>
												</ol>
											</div>
											<div className="flex gap-4 justify-center items-center">
												<Typography variant="code" className="text-2xl">
													{t.otp}
												</Typography>
												{/*<Button variant='secondary' size='sm'>
                                      Копировать
                                      <CopyIcon />
                                    </Button>*/}
											</div>
										</div>
									),
								});
							});
						}}
					>
						Получить код подтверждения
					</Button>
				)}
			</Field>
		</form>
	);
};
