import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { Link, useLocation } from "wouter";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";
import { useTranslation } from "react-i18next";
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
    CardFooter,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form";
import { BrainCircuit, ArrowLeft } from "lucide-react";

export default function ResetPasswordPage() {
    const { t } = useTranslation();
    const { toast } = useToast();
    const [location, setLocation] = useLocation();
    const [isSuccess, setIsSuccess] = useState(false);

    // Parse query params manually since wouter doesn't have a hook for it built-in easily for this version?
    // Actually window.location.search is easy enough
    const searchParams = new URLSearchParams(window.location.search);
    const token = searchParams.get("token");

    const resetPasswordSchema = z.object({
        password: z.string().min(6, t("validation.minLength", { min: 6 })),
        confirmPassword: z.string(),
    }).refine((data) => data.password === data.confirmPassword, {
        message: t("validation.passwordMatch"),
        path: ["confirmPassword"],
    });

    type ResetPasswordFormData = z.infer<typeof resetPasswordSchema>;

    const form = useForm<ResetPasswordFormData>({
        resolver: zodResolver(resetPasswordSchema),
        defaultValues: {
            password: "",
            confirmPassword: "",
        },
    });

    const mutation = useMutation({
        mutationFn: async (data: ResetPasswordFormData) => {
            const res = await fetch("/api/auth/reset-password", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ token, newPassword: data.password }),
            });
            if (!res.ok) {
                const json = await res.json();
                throw new Error(json.error || "Failed to reset password");
            }
            return res.json();
        },
        onSuccess: () => {
            setIsSuccess(true);
            toast({ title: t("auth.resetSuccess") });
            setTimeout(() => setLocation("/auth"), 3000);
        },
        onError: (error: Error) => {
            toast({
                title: t("common.error"),
                description: error.message,
                variant: "destructive",
            });
        },
    });

    const onSubmit = (data: ResetPasswordFormData) => {
        if (!token) {
            toast({ title: t("auth.invalidToken"), description: t("auth.missingToken"), variant: "destructive" });
            return;
        }
        mutation.mutate(data);
    };

    if (!token) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-background">
                <Card className="w-full max-w-md shadow-xl border-border/50">
                    <CardHeader className="text-center">
                        <CardTitle className="text-destructive">{t("auth.invalidToken")}</CardTitle>
                        <CardDescription>{t("auth.missingToken")}</CardDescription>
                    </CardHeader>
                    <CardFooter className="justify-center">
                        <Link href="/auth">
                            <Button variant="link">{t("auth.backToLogin")}</Button>
                        </Link>
                    </CardFooter>
                </Card>
            </div>
        )
    }

    return (
        <div className="min-h-screen grid lg:grid-cols-2">
            <div className="hidden lg:flex flex-col justify-center items-center bg-zinc-900 p-12 text-white">
                <div className="max-w-md space-y-4 text-center">
                    <div className="bg-white/10 p-4 rounded-2xl inline-block mb-4 backdrop-blur-sm">
                        <BrainCircuit className="w-16 h-16 text-primary-foreground" />
                    </div>
                    <h1 className="text-4xl font-bold tracking-tight">{t("app.title")}</h1>
                    <p className="text-lg text-zinc-400">
                        {t("auth.resetPasswordDesc")}
                    </p>
                </div>
            </div>

            <div className="flex items-center justify-center p-4 bg-background">
                <Card className="w-full max-w-md shadow-xl border-border/50">
                    <CardHeader className="text-center space-y-2">
                        <div className="lg:hidden mx-auto bg-primary/10 p-3 rounded-xl w-fit mb-2">
                            <BrainCircuit className="w-8 h-8 text-primary" />
                        </div>
                        <CardTitle className="text-2xl font-bold">{t("auth.resetPasswordTitle")}</CardTitle>
                        <CardDescription>
                            {t("auth.resetPasswordDesc")}
                        </CardDescription>
                    </CardHeader>
                    <CardContent>
                        {isSuccess ? (
                            <div className="text-center space-y-4">
                                <div className="p-4 bg-green-500/10 text-green-600 rounded-lg">
                                    <p>{t("auth.resetSuccess")}</p>
                                    <p className="text-sm mt-2">{t("auth.redirecting")}</p>
                                </div>
                            </div>
                        ) : (
                            <Form {...form}>
                                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                                    <FormField
                                        control={form.control}
                                        name="password"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>{t("auth.newPassword")}</FormLabel>
                                                <FormControl>
                                                    <Input type="password" placeholder="******" {...field} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="confirmPassword"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>{t("auth.confirmPassword")}</FormLabel>
                                                <FormControl>
                                                    <Input type="password" placeholder="******" {...field} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <Button className="w-full" type="submit" disabled={mutation.isPending}>
                                        {mutation.isPending ? t("auth.resetting") : t("auth.resetBtn")}
                                    </Button>
                                </form>
                            </Form>
                        )}
                    </CardContent>
                    {isSuccess && (
                        <CardFooter className="justify-center">
                            <Link href="/auth">
                                <Button variant="link" className="text-sm text-neutral-500">
                                    <ArrowLeft className="w-4 h-4 mr-2" /> {t("auth.backToLogin")}
                                </Button>
                            </Link>
                        </CardFooter>
                    )}
                </Card>
            </div>
        </div>
    );
}
