import { PasswordInput } from '@/components/PasswordInput'
import { Label } from '@/components/ui/label'
import RenderError, { ErrorClass } from './Error'
import { FormProps } from '.'
import { ChangeEvent, useState } from 'react'
import { KeyboardEvent } from 'react';
import Image from "next/image"

export default function ResetPw({
    formData,
    isSubmitting = false,
    error =  {},
    handleContinue = () => { },
    handleInputChange
}: FormProps) {
    const [passwordError, setPasswordError] = useState<string | null>(null);
    const [confirmPasswordError, setConfirmPasswordError] = useState<string | null>(null);
    const [newpw, setNewpw] = useState<string>("")

    const validatePassword = (password: string) => {
        const requirements = [
            password.length >= 8,
            /[A-Z]/.test(password),
            /[a-z]/.test(password),
            /\d/.test(password),
            /[!@#$%^&*(),.?":{}|<>]/.test(password),
        ];
        if (!requirements.every(Boolean) && password.length !== 0) {
            setPasswordError('Password does not meet the requirements.');
        } else {
            setPasswordError(null);
        }
    };

    const validateConfirmPassword = (password: string, confirmPassword: string) => {
        console.log(`Password: '${password}' \\ New password: '${confirmPassword}'`)
        if (password !== confirmPassword) {
            setConfirmPasswordError('Passwords do not match.');
        } else {
            setConfirmPasswordError(null);
        }
    };

    const handlePasswordChange = (value: string) => {
        setNewpw(value)
        validatePassword(value);
        validateConfirmPassword(value, formData.newpw || '');
    };

    const handleConfirmPasswordChange = (value: string) => {
        handleInputChange('newpw', value);
        validateConfirmPassword(newpw || '', value);
    };

    const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
        if (event.key === 'Enter') {
            const isDisabled = confirmPasswordError !== null ||
                passwordError !== null ||
                formData.newpw.length === 0 ||
                newpw.length === 0 ||
                isSubmitting;

            if (!isDisabled) {
                handleContinue();
            }
        }
    };

    return (
        <div className='gap-6 flex flex-col pb-6'>
            <div className='w-full flex flex-col justify-center gap-4'>
                <Image src={'/shield.svg'} width={86} height={86} alt='logo' priority />
                <h2 className='text-[28px]'>Reset your password</h2>
                <p className='text-muted-foreground font-cbtext text-sm'>Be sure to include the following requirements:</p>
                <ul className='flex flex-col text-[14px] text-muted-foreground list-disc text-start self-start px-4 py-3 gap-3 list-inside'>
                    <li>A minimum of 8 characters.</li>
                    <li>Have both uppercase and lowercase letters.</li>
                    <li>Must include a number.</li>
                    <li>Include at least one special character.</li>
                </ul>
            </div>
            <div className='flex flex-col gap-3'>
                <Label
                    htmlFor='passwd'
                    className='font-semibold leading-5 py-1 text-[14px]'
                >
                    Old Password
                </Label>
                <PasswordInput
                    id='passwd'
                    name='passwd'
                    disabled={isSubmitting}
                    className={
                        error.oldpw
                            ? `${ErrorClass} focus-visible:!ring-0 focus-visible:border-[rgb(rgb(240,97,109)]`
                            : ''
                    }
                    onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => handleKeyDown(event)}
                    onChange={(value: ChangeEvent<HTMLInputElement>) =>
                        handleInputChange('oldpw', value.target.value)
                    }
                    value={formData.oldpw || ''}
                    placeholder='Old password'
                />
                <RenderError error={error.oldpw} />
                <Label
                    htmlFor='passwd'
                    className='font-semibold leading-5 py-1 text-[14px]'
                >
                    New Password
                </Label>
                <PasswordInput
                    id='newpw'
                    name='newpw'
                    disabled={isSubmitting}
                    className={passwordError ? `${ErrorClass}` : ''}
                    onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => handleKeyDown(event)}
                    onChange={(event: ChangeEvent<HTMLInputElement>) => handlePasswordChange(event.target.value)}
                    placeholder='Enter your new password'
                    value={newpw}
                />
                {passwordError && <RenderError2 error={passwordError} />}
                <Label
                    htmlFor='passwd'
                    className='font-semibold leading-5 py-1 text-[14px]'
                >
                    Confirm Password
                </Label>
                <PasswordInput
                    id='newpw2'
                    name='newpw2'
                    disabled={isSubmitting}
                    placeholder='Re-enter your new password'
                    className={confirmPasswordError ? `${ErrorClass}` : ''}
                    onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => handleKeyDown(event)}
                    onChange={(event: ChangeEvent<HTMLInputElement>) => handleConfirmPasswordChange(event.target.value)}
                    value={formData.newpw || ''}
                />
                {confirmPasswordError && <RenderError2 error={confirmPasswordError} />}
            </div>
            <button
                className={`-mb-3 disabled:bg-transparent border border-transparent disabled:border-[rgba(138,145,158,0.66)] disabled:text-muted-foreground transition-all duration-150 ease-in-out bg-[rgb(87,139,250)] h-[56px] text-black p-2 font-[600] min-w-[100px] flex justify-center items-center rounded-full w-full hover:bg-blue-600 ${isSubmitting ? 'bg-[rgb(75,120,214)] pointer-events-none' : ''
                    }`}
                disabled={confirmPasswordError !== null || passwordError !== null || (formData.newpw.length === 0 || newpw.length === 0)}
                onClick={handleContinue}
            >
                {isSubmitting ? (
                    <div
                        className={
                            '!border-b-[rgb(10,11,13)] loader w-[24px] h-[24px] border-[2px] border-[rgba(20,21,25,0)] rounded-full animate-spin'
                        }
                    ></div>
                ) : (
                    'Continue'
                )}
            </button>
        </div>
    )
}

function RenderError2({ error }: { error?: string }) {
    return error ? (
        <span className='text-start block text-[14px] leading-5 font-cbsans text-[rgb(240,97,109)]'>
            <span className='pr-1 inline-block'>
                <div className='relative flex'>
                    <div className='w-[12px] h-[12px]'>
                        <span
                            aria-hidden='false'
                            aria-label='error'
                            className='text-[rgb(240,97,109)] text-[12px] font-cbicons'
                            data-icon-name='info'
                            role='img'
                        >
                            
                        </span>
                    </div>
                </div>
            </span>
            {error}
        </span>
    ) : null;
}
