import { useState, useEffect } from 'react';
import { useCookies } from 'react-cookie';
import { GUESTS } from '../constants/constants';
import useFetchUser from '../utils/fetchUser'; // Import your custom hook
import { useNotification } from '../NotificationContext';
import ApologyMessage from './Attendance';

const InitialSetup = () => {
    const [cookie, setCookie] = useCookies();
    const [selectedName, setSelectedName] = useState<string | undefined>(undefined);
    //const [token] = useState<string | undefined>(cookie.apiToken)
    const [isSubmitted, setIsSubmitted] = useState(false);
    const [password, setPassword] = useState('');
    const [isPasswordSet, setIsPasswordSet] = useState(false); // To track if password is set
    const [userAttendance, setUserAttendance] = useState<boolean | null>(null);

    const { userSet, passwordCreate, signUser, validToken, getAttendance } = useFetchUser(); // Destructure functions from the hook
    const notify = useNotification();

    const checkUserPassword = async (name: string) => {
        const passwordStatus = await userSet(name);
        setIsPasswordSet(passwordStatus);
    };

    const handleSelect = (event: React.ChangeEvent<HTMLSelectElement>) => {
        const name = event.target.value;
        setCookie('userName', name, { path: '/' });
        setSelectedName(name);
        checkUserPassword(name);
    };

    const validateToken = async () => {
        const isTokenValid = await validToken(cookie.apiToken);
        setIsSubmitted(isTokenValid);
    };

    const getUserAttendance = async () => {
        const attendance = await getAttendance()
        setUserAttendance(attendance)
    }

    useEffect(() => {
        if (cookie.apiToken !== undefined) { 
            getUserAttendance()
            validateToken();
        }
    }, [cookie.apiToken]); 


    const handlePasswordCreate = async () => {
        const message= await passwordCreate(selectedName!, password);
        if (message !== '') {
            notify(message, 'error')
            return
        }
        
    };

    const handleSignIn = async () => {
        const signedIn = await signUser(selectedName!, password); // Implement your sign-in logic here
        if (!signedIn) {
            notify('Не удалось войти. Может пароль не тот?', 'error')
            return
        }
        validateToken()
    };
    
    if (isSubmitted && userAttendance !== false) {
        console.log('Selected', selectedName);
        return null; // or you can redirect to another component or page
    }

    if (userAttendance == false) {
        return (
            <ApologyMessage/>
        )
    }

    return (
        <div style={styles.container}>
            <h2 style={styles.title}>Выбери себя</h2>
            <select style={styles.dropdown} onChange={handleSelect} value={selectedName || ''}>
                <option value="" disabled>{(cookie.userName == undefined) ? 'Пятка' : cookie.userName}</option>
                {GUESTS.map((name) => (
                    <option key={name} value={name}>
                        {name}
                    </option>
                ))}
            </select>
             {(selectedName !== undefined) && (
                <>
                    <h3>{isPasswordSet ? 'Войдите' : 'Создайте свой пароль'}</h3>
                    <input
                        type="password"
                        placeholder="Ввести пароль"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        style={styles.input}
                        />
                        {isPasswordSet ? (
                            <>
                                <button onClick={handleSignIn}>
                                    Войти
                                </button>
                            </>
                        ) : (<>
                                            <button  
                        onClick={handlePasswordCreate} 
                        disabled={!password} // Disables the button if no password is entered
                    >
                        Создать пароль
                    </button>
                        </>)}

                </>
            )}
        </div>
    );
};

const styles = {
    container: {
        position: 'fixed' as 'fixed',
        top: 0,
        left: 0,
        width: '100vw',
        height: '100vh',
        backgroundColor: 'rgba(0, 0, 0, 1)',
        display: 'flex',
        flexDirection: 'column' as 'column',
        justifyContent: 'center',
        alignItems: 'center',
        color: '#fff',
        zIndex: 1000,
        overflow: 'hidden',
    },
    title: {
        marginBottom: '20px',
    },
    dropdown: {
        padding: '10px',
        fontSize: '16px',
        cursor: 'pointer',
        border: 'none',
        borderRadius: '5px',
        outline: 'none',
        marginBottom: '10px',
    },
    input: {
        padding: '10px',
        fontSize: '16px',
        border: 'none',
        borderRadius: '5px',
        outline: 'none',
        marginBottom: '10px',
        width: '200px', // Set a width
    }
}

export default InitialSetup;