import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { registerFormSchema, RegisterFormValues } from '@/lib/validations';
import { zodResolver } from '@hookform/resolvers/zod';
import { Link, router } from '@inertiajs/react';
import axios from 'axios';
import { motion } from 'framer-motion';
import { LoaderCircle } from 'lucide-react';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';

export default function RegisterForm() {
    const [currentStage, setCurrentStage] = useState(1); // 1 for personal info, 2 for account details

    const form = useForm<RegisterFormValues>({
        resolver: zodResolver(registerFormSchema),
        defaultValues: {
            username: '', // Pre-filled as per image
            name: '',
            email: '',
            password: '',
            usdt_account: '',
            btc_account: '',
            eth_account: '',
            terms: false,
        },
        mode: 'onTouched', // Validate on blur/touch
    });

    const processing = form.formState.isSubmitting;

    const handleNext = async () => {
        let isValid = false;
        if (currentStage === 1) {
            isValid = await form.trigger(['username', 'name', 'email', 'password']);
        }
        // Add more stages here if needed
        // else if (currentStage === 2) {
        //   isValid = await form.trigger(["fieldA", "fieldB"]);
        // }

        if (isValid) {
            setCurrentStage((prev) => prev + 1);
        }
    };

    const handlePrevious = () => {
        setCurrentStage((prev) => prev - 1);
    };

    async function onSubmit(values: RegisterFormValues) {
        await axios
            .post(route('register'), values)
            .then(() => {
                toast.success('Registration Successful!', {
                    description: 'Your account has been created. Please check your email for verification.',
                });
                router.visit(route('verification.notice'));
            })
            .catch((error) => {
                if (error?.response?.data) {
                    const { errors, message } = error.response.data;

                    if(errors){

                        Object.keys(errors).forEach((field) => {
                            form.setError(field as keyof RegisterFormValues, {
                                type: 'server',
                                message: errors[field],
                            });
                        });
                    }else{
                        toast.error(message || 'An error occurred during registration. Please try again later.');
                    }
                }
            });
    }

    const formVariants = {
        hidden: { opacity: 0, y: 20 },
        visible: { opacity: 1, y: 0, transition: { duration: 0.5, ease: 'easeOut' } },
    };

    return (
        <motion.div className="w-full max-w-md space-y-4" initial="hidden" animate="visible" variants={formVariants}>
            {/* Logo */}
            <div className="">
                <div className="flex items-center justify-center gap-2">
                    <img src="/logo.png" alt="" className="w-12" />

                    <p className="text-xl font-bold text-gray-800">FairTrust Fund</p>
                </div>
            </div>

            <div className="space-y-1 text-center">
                <h1 className="text-xl font-semibold">Create an account</h1>
                <p className="text-center text-sm text-muted-foreground">Enter your details below to create your account</p>
            </div>

            <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                    {currentStage === 1 && (
                        <motion.div
                            key="stage1"
                            initial={{ opacity: 0, x: 50 }}
                            animate={{ opacity: 1, x: 0 }}
                            exit={{ opacity: 0, x: -50 }}
                            transition={{ duration: 0.3 }}
                            className="space-y-4"
                        >
                            <FormField
                                control={form.control}
                                name="username"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormControl>
                                            <Input placeholder="Enter your Username" {...field} disabled={processing} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="name"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormControl>
                                            <Input placeholder="Enter Full Name" {...field} disabled={processing} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="email"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormControl>
                                            <Input type="email" placeholder="Email" {...field} disabled={processing} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="password"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormControl>
                                            <Input type="password" placeholder="Password" {...field} disabled={processing} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="terms"
                                render={({ field }) => (
                                    <FormItem className="">
                                        <div className="flex items-center gap-2">
                                            <FormControl>
                                                <Checkbox checked={field.value} onCheckedChange={field.onChange} />
                                            </FormControl>
                                            <div className="space-y-1 text-left leading-none">
                                                <FormLabel className="inline-flex font-normal text-gray-600">
                                                    I have read and agreed to the{' '}
                                                    <Link href="/about" className="text-green-600 hover:underline">
                                                        terms and conditions
                                                    </Link>
                                                </FormLabel>
                                            </div>
                                        </div>
                                        <FormMessage className="text-xs italic" />
                                    </FormItem>
                                )}
                            />

                            <Button
                                type="submit"
                                className="w-full rounded-full bg-green-500 px-8 py-3 font-semibold text-white transition-all duration-300 hover:scale-105 hover:bg-green-600"
                                disabled={processing}
                            >
                                {processing && <LoaderCircle className="h-4 w-4 animate-spin" />} Sign Up
                            </Button>
                        </motion.div>
                    )}

                    {/* {currentStage === 2 && (
                        <motion.div
                            key="stage2"
                            initial={{ opacity: 0, x: 50 }}
                            animate={{ opacity: 1, x: 0 }}
                            exit={{ opacity: 0, x: -50 }}
                            transition={{ duration: 0.3 }}
                            className="space-y-4"
                        >
                            <FormField
                                control={form.control}
                                name="usdt_account"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormControl>
                                            <Input placeholder="Your USDT TRC 20 Account" {...field} disabled={processing} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="btc_account"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormControl>
                                            <Input placeholder="Your BITCOIN Account ID" {...field} disabled={processing} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="eth_account"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormControl>
                                            <Input placeholder="Your ETHEREUM Account" {...field} disabled={processing} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <div className="space-y-2">
                              <label htmlFor="upline" className="sr-only">
                                  Upline
                              </label>
                              <Input id="upline" placeholder="Upline - (n/a)" value="Upline - (n/a)" disabled className="text-gray-500" />
                          </div>

                            <FormField
                                control={form.control}
                                name="terms"
                                render={({ field }) => (
                                    <FormItem className="">
                                        <div className="flex items-center gap-2">
                                            <FormControl>
                                                <Checkbox checked={field.value} onCheckedChange={field.onChange} />
                                            </FormControl>
                                            <div className="space-y-1 text-left leading-none">
                                                <FormLabel className="font-normal text-gray-600">
                                                    I have read and agreed to the{' '}
                                                    <Link href="#" className="text-blue-600 hover:underline">
                                                        Terms And Conditions
                                                    </Link>
                                                </FormLabel>
                                            </div>
                                        </div>
                                        <FormMessage className="text-xs italic" />
                                    </FormItem>
                                )}
                            />
                            <div className="flex gap-4">
                                <Button
                                    type="button"
                                    onClick={handlePrevious}
                                    className="flex-1 rounded-full bg-gray-300 px-8 py-3 font-semibold text-gray-800 transition-all duration-300 hover:scale-105 hover:bg-gray-400"
                                >
                                    Previous
                                </Button>
                                <Button
                                    type="submit"
                                    className="flex-1 rounded-full bg-green-500 px-8 py-3 font-semibold text-white transition-all duration-300 hover:scale-105 hover:bg-green-600"
                                    disabled={processing}
                                >
                                    {processing && <LoaderCircle className="h-4 w-4 animate-spin" />} Sign Up
                                </Button>
                            </div>
                        </motion.div>
                    )} */}
                </form>
            </Form>

            <div className="mt-6 text-sm">
                <p className="text-gray-600">
                    Already have an account?{' '}
                    <Link href="/login" className="font-medium text-red-500 hover:underline">
                        Sign In
                    </Link>
                </p>
            </div>
        </motion.div>
    );
}
