'use client'
import React, { useState } from 'react'
import Link from 'next/link'
import TopNavOne from '@/components/Header/TopNav/TopNavOne'
import MenuOne from '@/components/Header/Menu/MenuOne'
import Breadcrumb from '@/components/Breadcrumb/Breadcrumb'
import Footer from '@/components/Footer/Footer'
import * as Icon from "@phosphor-icons/react/dist/ssr";
import axios from 'axios'
import { BaseURL } from '../../../utils/BaseUrl'
import { useRouter } from 'next/navigation'

const Register = () => {

    const router = useRouter()

    const [form, setForm] = useState({
        name: '',
        email: '',
        password: '',
        confirmPassword: '',
        agree: false,
    });
    const [errors, setErrors] = useState<{ [k: string]: string }>({});

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value, type, checked } = e.target;
        setForm(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value,
        }));
    };

    const validate = () => {
        const errs: { [k: string]: string } = {};
        if (!form.name.trim()) errs.name = 'Name is required';
        if (!form.email.trim()) errs.email = 'Email is required';
        if (!form.password) errs.password = 'Password is required';
        if (form.password !== form.confirmPassword) errs.confirmPassword = 'Passwords do not match';
        if (!form.agree) errs.agree = 'You must agree to the terms';
        return errs;
    };

    const handleSubmit = async (e: React.FormEvent | React.MouseEvent) => {
        e.preventDefault();
        const v = validate();
        setErrors(v);
        if (Object.keys(v).length > 0) return;

        // log the required fields
        const Body = {
            name: form.name,
            email: form.email,
            password: form.password,
        };

        try {
            const res = await axios?.post(`${BaseURL}/auth/register`, Body)
            console.log("res", res)
            // reset full form (including confirmPassword & agree)
            router?.push("/login")
            setForm({
                name: "",
                email: "",
                password: "",
                confirmPassword: "",
                agree: false,
            });
            setErrors({});
        } catch (error: any) {
            let msg = "Registration failed";
            if (error?.response?.data) {
                // common patterns: { message: "..."} or { error: "..."} or nested
                msg =
                    error.response.data.message ||
                    error.response.data.error ||
                    JSON.stringify(error.response.data) ||
                    msg;
            } else if (error?.message) {
                msg = error.message;
            }

            // Optionally show toast: toast.error(msg);
            setErrors((prev) => ({ ...prev, submit: msg }));
        }

        // TODO: continue with registration logic (API call / redirect)
    };

    return (
        <>
            <TopNavOne props="style-one bg-black" slogan="New customers save 10% with the code GET10" />
            <div id="header" className='relative w-full'>
                <MenuOne props="bg-transparent" />
                <Breadcrumb heading='Create An Account' subHeading='Create An Account' />
            </div>
            <div className="register-block md:py-20 py-10">
                <div className="container">
                    <div className="content-main flex gap-y-8 max-md:flex-col">
                        <div className="left md:w-1/2 w-full lg:pr-[60px] md:pr-[40px] md:border-r border-line">
                            <div className="heading4">Register</div>
                            <form className="md:mt-7 mt-4" onSubmit={handleSubmit} noValidate>
                                <div className="email ">
                                    <input
                                        className="border-line px-4 pt-3 pb-3 w-full rounded-lg"
                                        id="username"
                                        name="name"
                                        type="text"
                                        placeholder="Username or name *"
                                        value={form.name}
                                        onChange={handleChange}
                                        required
                                        aria-invalid={!!errors.name}
                                        aria-describedby="error-name"
                                    />
                                    {errors.name && <div id="error-name" className="text-danger mt-1">{errors.name}</div>}
                                </div>

                                <div className="email mt-5">
                                    <input
                                        className="border-line px-4 pt-3 pb-3 w-full rounded-lg"
                                        id="email"
                                        name="email"
                                        type="email"
                                        placeholder="Email Address *"
                                        value={form.email}
                                        onChange={handleChange}
                                        required
                                        aria-invalid={!!errors.email}
                                        aria-describedby="error-email"
                                    />
                                    {errors.email && <div id="error-email" className="text-danger mt-1">{errors.email}</div>}
                                </div>

                                <div className="pass mt-5">
                                    <input
                                        className="border-line px-4 pt-3 pb-3 w-full rounded-lg"
                                        id="password"
                                        name="password"
                                        type="password"
                                        placeholder="Password *"
                                        value={form.password}
                                        onChange={handleChange}
                                        required
                                        aria-invalid={!!errors.password}
                                        aria-describedby="error-password"
                                    />
                                    {errors.password && <div id="error-password" className="text-danger mt-1">{errors.password}</div>}
                                </div>

                                <div className="confirm-pass mt-5">
                                    <input
                                        className="border-line px-4 pt-3 pb-3 w-full rounded-lg"
                                        id="confirmPassword"
                                        name="confirmPassword"
                                        type="password"
                                        placeholder="Confirm Password *"
                                        value={form.confirmPassword}
                                        onChange={handleChange}
                                        required
                                        aria-invalid={!!errors.confirmPassword}
                                        aria-describedby="error-confirmPassword"
                                    />
                                    {errors.confirmPassword && (
                                        <div id="error-confirmPassword" className="text-danger mt-1">{errors.confirmPassword}</div>
                                    )}
                                </div>

                                <div className='flex items-center mt-5'>
                                    <div className="block-input relative">
                                        <input
                                            type="checkbox"
                                            name='agree'
                                            id='remember'
                                            checked={form.agree}
                                            onChange={handleChange}
                                            className="opacity-0 absolute inset-0 z-10 cursor-pointer"
                                            aria-invalid={!!errors.agree}
                                            aria-describedby="error-agree"
                                        />
                                        <Icon.CheckSquare size={20} weight='fill' className='icon-checkbox' />
                                    </div>
                                    <label htmlFor='remember' className="pl-2 cursor-pointer text-secondary2">
                                        I agree to the
                                        <Link href={'#!'} className='text-black hover:underline pl-1'>Terms of User</Link>
                                    </label>
                                </div>
                                {errors.agree && <div id="error-agree" className="text-danger mt-1">{errors.agree}</div>}

                                <div className="block-button md:mt-7 mt-4">
                                    <a
                                        href="#"
                                        onClick={(e) => handleSubmit(e)}
                                        role="button"
                                        className="button-main block-button inline-block text-center"
                                        aria-label="Register"
                                    >
                                        Register
                                    </a>
                                </div>
                            </form>
                        </div>

                        <div className="right md:w-1/2 w-full lg:pl-[60px] md:pl-[40px] flex items-center">
                            <div className="text-content">
                                <div className="heading4">Already have an account?</div>
                                <div className="mt-2 text-secondary">
                                    Welcome back. Sign in to access your personalized experience, saved preferences, and more. We{String.raw`'re`} thrilled to have you with us again!
                                </div>
                                <div className="block-button md:mt-7 mt-4">
                                    <Link href={'/login'} className="button-main">Login</Link>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
            <Footer />
        </>
    )
}

export default Register
