import { useState } from "react";
import { useForm } from "react-hook-form";
import { Link } 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 ForgotPasswordPage() {
    const { t } = useTranslation();
    const { toast } = useToast();
    const [isSuccess, setIsSuccess] = useState(false);

    const forgotPasswordSchema = z.object({
        email: z.string().email(t("validation.email")),
    });

    type ForgotPasswordFormData = z.infer<typeof forgotPasswordSchema>;

    const form = useForm<ForgotPasswordFormData>({
        resolver: zodResolver(forgotPasswordSchema),
        defaultValues: {
            email: "",
        },
    });

    const mutation = useMutation({
        mutationFn: async (data: ForgotPasswordFormData) => {
            const res = await fetch("/api/auth/forgot-password", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(data),
            });
            if (!res.ok) {
                const text = await res.text();
                throw new Error(text || "Failed to send reset email");
            }
            return res.json();
        },
        onSuccess: () => {
            setIsSuccess(true);
            toast({ title: t("auth.resetEmailSent") });
        },
        onError: (error: Error) => {
            toast({
                title: t("common.error"),
                description: "Something went wrong. Please try again.",
                variant: "destructive",
            });
        },
    });

    const onSubmit = (data: ForgotPasswordFormData) => {
        mutation.mutate(data);
    };

    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.forgotPasswordDesc")}
                    </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.forgotPasswordTitle")}</CardTitle>
                        <CardDescription>
                            {t("auth.forgotPasswordDesc")}
                        </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.resetEmailSentDesc")}</p>
                                </div>
                                <p className="text-sm text-neutral-500">{t("auth.checkSpam")}</p>
                            </div>
                        ) : (
                            <Form {...form}>
                                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                                    <FormField
                                        control={form.control}
                                        name="email"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>Email</FormLabel>
                                                <FormControl>
                                                    <Input type="email" placeholder="email@example.com" {...field} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <Button className="w-full" type="submit" disabled={mutation.isPending}>
                                        {mutation.isPending ? t("auth.sending") : t("auth.sendResetLink")}
                                    </Button>
                                </form>
                            </Form>
                        )}
                    </CardContent>
                    <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>
    );
}
