import { useCookies } from 'react-cookie';
import { API_URL } from '../constants/constants';
import { hashPassword } from './hashPassword';

const useFetchUser = () => {
    const [apiCookie, setApiCookie] = useCookies(['apiToken']);
    const [, setUserNameCookie] = useCookies(['userName'])

    const userSet = async (userName: string): Promise<boolean> => {
        try {
            const response = await fetch(`${API_URL}/users/isSet?userName=${encodeURIComponent(userName)}`);
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            const data = await response.json();
            return data; // Assuming the server returns true/false
        } catch (error) {
            console.error('Error checking user password status:', error);
            return false;
        }
    };

    const passwordCreate = async (userName: string, password: string): Promise<string> => {
        // Simple validation: password should not be empty and should have a minimum length
        if (!password || password.length < 6) {
            console.error('Password should be at least 6 characters long.');
            return 'Пароль должен иметь, как минимум 6 символов';
        }

        try {
            const hashedPassword = hashPassword(password)
            const response = await fetch(`${API_URL}/users/createPassword`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    userName,
                    password: hashedPassword,
                }),
            });

            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            const data = await response.json();

            if (data.success) {
                setApiCookie('apiToken', data.token, { path: '/' });
                console.log(`Password created for ${userName}`);
                return ''; // Password creation success
            }
            return 'Не удалось создать пароль'; // Password creation failure
        } catch (error) {
            console.error('Error creating password:', error);
            return 'Пароль не создан:' + error;
        }
    };

    const signUser = async (userName: string, password: string): Promise<boolean> => {
        try {
            const hashedPassword = hashPassword(password); // Implement this function to hash the password
            const response = await fetch(`${API_URL}/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    userName,
                    password: hashedPassword,
                }),
            });

            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            const data = await response.json();

            if (data.token) {
                setApiCookie('apiToken', data.token, { path: '/' });
                console.log(`User ${userName} signed in.`);
                return true; // Sign-in success
            }
            return false; // Sign-in failed
        } catch (error) {
            console.error('Error logging in:', error);
            return false;
        }
    };

    const validToken = async (token: string | undefined): Promise<boolean> => {
        try {
            const response = await fetch(`${API_URL}/login/validateToken`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    token
                }),
            });

            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            const data = await response.json();

            if (!data.userName) throw new Error(`Could not retrieve userName from token`);

            setUserNameCookie('userName', data.userName, { path: '/' });

            return data.tokenValid
        } catch (error) {
            console.error('Error validating token:', error);
            return false;
        }
    }

    const updateAttendance = async (attendanceStatus: boolean): Promise<boolean> => {
        const token = apiCookie.apiToken
        try {
            const response = await fetch(`${API_URL}/users/attendance`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    token,
                    attendance: attendanceStatus,
                }),
            });

            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            const data = await response.json();

            if (!data.success) throw new Error(data.message);

            return true; // Attendance updated successfully
        } catch (error) {
            console.error('Error updating attendance:', error);
            return false; // Attendance update failed
        }
    }

    const getAttendance = async (): Promise<boolean | null> => {
        const token = apiCookie.apiToken
        try {
            const response = await fetch(`${API_URL}/users/attendance?token=${encodeURIComponent(token)}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            const data = await response.json();

            if (!data.success) throw new Error(data.message);
            
            return data.attendance; // Returns attendance status (true/false)
        } catch (error) {
            console.error('Error retrieving attendance:', error);
            return null; // In case of error or if attendance status is not found
        }
    }

    return { userSet, passwordCreate, signUser, validToken, updateAttendance, getAttendance };
};

export default useFetchUser;
