import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import { ToastContainer, toast } from 'react-toastify';
import Head from 'next/head';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import BaseIcon from "../components/BaseIcon";
import { mdiShieldCheck, mdiEye, mdiEyeOff } from '@mdi/js';
import LayoutGuest from '../layouts/Guest';
import { Field, Form, Formik } from 'formik';
import FormField from '../components/FormField';
import { useRouter } from 'next/router';
import { getPageTitle } from '../config';
import Link from 'next/link';
import axios from "axios";
import { getPexelsImage, getPexelsVideo } from '../helpers/pexels'
import Logo from '../components/Logo'

export default function Register() {
    const [loading, setLoading] = React.useState(false);
    const [showPassword, setShowPassword] = useState(false);
    const router = useRouter();
    const notify = (type, msg) => toast(msg, { type, position: "bottom-center" });

    const [illustrationImage, setIllustrationImage] = useState({
        src: undefined,
        photographer: undefined,
        photographer_url: undefined,
    })
    const [illustrationVideo, setIllustrationVideo] = useState({ video_files: [] })
    const [contentType, setContentType] = useState('video');

    useEffect(() => {
        async function fetchData() {
            const image = await getPexelsImage()
            const video = await getPexelsVideo()
            setIllustrationImage(image);
            setIllustrationVideo(video);
        }
        fetchData();
    }, []);

    const togglePasswordVisibility = () => {
        setShowPassword(!showPassword);
    };

    const handleSubmit = async (values) => {
        if (values.password !== values.confirm) {
            notify('error', 'Passwords do not match');
            return;
        }
        setLoading(true)
        try {
            await axios.post('/auth/signup', values);
            setLoading(false)
            notify('success', 'Please check your email for verification link')
            setTimeout(() => {
                router.push('/login')
            }, 2000);
        } catch (error) {
            setLoading(false)
            console.log('error: ', error)
            notify('error', error.response?.data?.message || 'Something went wrong. Try again')
        }
    };

    const imageBlock = (image) => (
        <div className="hidden lg:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/2 overflow-hidden"
            style={{
                backgroundImage: `${image ? `url(${image.src?.original})` : 'linear-gradient(rgba(16, 185, 129, 0.1), rgba(6, 78, 59, 0.2))'}`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                backgroundRepeat: 'no-repeat',
            }}>
            <div className="absolute inset-0 bg-emerald-900/20 backdrop-brightness-75"></div>
            <div className="relative z-10 p-12 text-white">
                <h1 className="text-4xl font-black mb-4">Start Your Professional Journey.</h1>
                <p className="text-lg text-emerald-50/80 max-w-md leading-relaxed">
                    Get listed, get verified, and connect with clients looking for high-quality, trusted services.
                </p>
            </div>
            <div className="flex justify-center w-full bg-black/40 py-2 relative z-10">
                <a className="text-[10px] text-white/60 hover:text-white transition-colors" href={image?.photographer_url} target="_blank" rel="noreferrer">
                    Photo by {image?.photographer} on Pexels
                </a>
            </div>
        </div>
    )

    const videoBlock = (video) => {
        if (video?.video_files?.length > 0) {
            return (
                <div className='hidden lg:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/2 overflow-hidden'>
                    <video
                        className='absolute top-0 left-0 w-full h-full object-cover'
                        autoPlay
                        loop
                        muted
                    >
                        <source src={video.video_files[0]?.link} type='video/mp4' />
                        Your browser does not support the video tag.
                    </video>
                    <div className="absolute inset-0 bg-emerald-900/20 backdrop-brightness-75"></div>
                    <div className="relative z-10 p-12 text-white">
                        <h1 className="text-4xl font-black mb-4">Start Your Professional Journey.</h1>
                        <p className="text-lg text-emerald-50/80 max-w-md leading-relaxed">
                            Get listed, get verified, and connect with clients looking for high-quality, trusted services.
                        </p>
                    </div>
                    <div className='flex justify-center w-full bg-black/40 py-2 relative z-10'>
                        <a
                            className='text-[10px] text-white/60 hover:text-white transition-colors'
                            href={video.user.url}
                            target='_blank'
                            rel='noreferrer'
                        >
                            Video by {video.user.name} on Pexels
                        </a>
                    </div>
                </div>)
        }
        return imageBlock(illustrationImage);
    };

    return (
        <div className="min-h-screen bg-slate-50 font-sans">
            <Head>
                <title>{getPageTitle('Register')}</title>
            </Head>

            <div className="flex flex-row min-h-screen">
                {contentType === 'video' ? videoBlock(illustrationVideo) : imageBlock(illustrationImage)}

                <div className="w-full lg:w-1/2 flex items-center justify-center p-8 lg:p-16">
                    <div className="w-full max-w-md space-y-8">
                        {/* Branding */}
                        <div className="flex flex-col items-center mb-8">
                            <Link href="/" className="flex items-center gap-3 group mb-6">
                                <Logo className="h-12 w-auto" />
                            </Link>
                            <h2 className="text-3xl font-bold text-slate-900">Create Account</h2>
                            <p className="text-slate-500 mt-2 text-center">Join the most trusted service network today</p>
                        </div>

                        <CardBox className="shadow-2xl border-none rounded-[2rem] p-4 lg:p-6">
                            <Formik
                                initialValues={{
                                    email: '',
                                    password: '',
                                    confirm: ''
                                }}
                                onSubmit={(values) => handleSubmit(values)}
                            >
                                <Form className="space-y-4">
                                    <FormField
                                        label='Email Address'
                                        labelColor="text-slate-700 font-bold"
                                    >
                                        <Field name='email' type='email' placeholder="name@company.com" className="rounded-xl border-slate-200 focus:border-emerald-500 focus:ring-emerald-500" />
                                    </FormField>

                                    <div className='relative'>
                                        <FormField
                                            label='Password'
                                            labelColor="text-slate-700 font-bold"
                                        >
                                            <Field name='password' type={showPassword ? 'text' : 'password'} placeholder="••••••••" className="rounded-xl border-slate-200 focus:border-emerald-500 focus:ring-emerald-500" />
                                        </FormField>
                                        <div
                                            className='absolute top-[42px] right-0 pr-4 flex items-center cursor-pointer'
                                            onClick={togglePasswordVisibility}
                                        >
                                            <BaseIcon
                                                className='text-slate-400 hover:text-emerald-500'
                                                size={20}
                                                path={showPassword ? mdiEyeOff : mdiEye}
                                            />
                                        </div>
                                    </div>

                                    <FormField
                                        label='Confirm Password'
                                        labelColor="text-slate-700 font-bold"
                                    >
                                        <Field name='confirm' type={showPassword ? 'text' : 'password'} placeholder="••••••••" className="rounded-xl border-slate-200 focus:border-emerald-500 focus:ring-emerald-500" />
                                    </FormField>

                                    <div className="pt-6">
                                        <BaseButton
                                            className={'w-full py-4 rounded-xl font-bold text-lg shadow-lg shadow-emerald-500/20'}
                                            type='submit'
                                            label={loading ? 'Creating Account...' : 'Register'}
                                            color='success'
                                            disabled={loading}
                                        />
                                    </div>

                                    <div className="text-center pt-4">
                                        <p className="text-slate-500 text-sm">
                                            Already have an account?{' '}
                                            <Link className="font-bold text-emerald-600 hover:text-emerald-700" href={'/login'}>
                                                Sign in here
                                            </Link>
                                        </p>
                                    </div>
                                </Form>
                            </Formik>
                        </CardBox>

                        <div className="text-center text-slate-400 text-xs pt-8">
                            By creating an account, you agree to our <Link href='/terms-of-use' className="underline">Terms</Link> and <Link href='/privacy-policy' className="underline">Privacy Policy</Link>. <br />
                            © 2026 Fix-It-Local™. All rights reserved.
                        </div>
                    </div>
                </div>
            </div>
            <ToastContainer />
        </div>
    );
}

Register.getLayout = function getLayout(page: ReactElement) {
    return <LayoutGuest>{page}</LayoutGuest>;
};