import {useContext, useState, ChangeEvent, useEffect} from "react";
import Modal from "../../../../components/ui/Modal/Modal";
import Button from "../../../../components/ui/Button/Button";
import styles from "./SettingsModal.module.css";
import ThemeSwitcher from "../../../../components/ui/ThemeSwitcher/ThemeSwitcher";
import {AuthContext} from "../../../../contexts/Auth/AuthContext";
import TextInput from "../../../../components/ui/Input/Input";
import updateUser from "../../../../utils/users/updateUser.js";
import deleteUser from "../../../../utils/users/deleteUser.js";
import ExportCalendarBtn from "../../../../components/ExportCalendarBtn/ExportBtn";
import { useNavigate } from "react-router";
import toggleEmailNotifications from "../../../../utils/users/toggleEmailNotifications";
import toggleWebNotifications from "../../../../utils/users/toggleWebNotifications";


interface TaskType {
    id: number;
    title?: string;
    completed?: boolean;

    [key: string]: unknown;
}

interface User {
    id: number;
    name: string;
    lastname: string;
    role: string;
    email: string;
    phone: string | null;
    created_at: string;
    isAdmin: boolean;
    tasks: TaskType[],
    email_notifications: number,
    web_notifications: number;
}

interface AuthContextType {
    user: User;
    update: () => void;
    logout: () => void;
}

export default function SettingsModal() {
    const navigate = useNavigate();
    const {user, logout, update} = useContext(AuthContext) as unknown as AuthContextType;

    const [open, setOpen] = useState<boolean>(false);
    const [isDelete, setIsDelete] = useState<boolean>(false);

    const [name, setName] = useState<string>(user?.name ?? "");
    const [lastname, setLastName] = useState<string>(user?.lastname ?? "");
    const [phone, setPhone] = useState<string>(user?.phone ?? "");

    const [emailNotifications, setEmailNotifications] = useState<number>(user?.email_notifications ?? 0);
    const [webNotifications, setWebNotifications] = useState<number>(user?.web_notifications ?? 0);

    const handleLogout = (): void => {
        logout();
    };

    const handleSubmit = async (): Promise<void> => {
        await updateUser(name, lastname, phone || null);
        update();
        setOpen(false);
    };

    const handleDelete = async (): Promise<void> => {
        await deleteUser();
        logout();
        navigate('/');
        update();
    };

    const handleNameChange = (e: ChangeEvent<HTMLInputElement>): void => {
        setName(e.target.value);
    };

    const handleLastnameChange = (e: ChangeEvent<HTMLInputElement>): void => {
        setLastName(e.target.value);
    };

    const handlePhoneChange = (e: ChangeEvent<HTMLInputElement>): void => {
        setPhone(e.target.value);
    };

    const handleEmailToggle = async () => {
        try {
            await toggleEmailNotifications(user.id);
            setEmailNotifications(prev => prev === 0 ? 1 : 0);
            update();
        } catch (err) {
            console.error(err);
        }
    };

    const handleWebToggle = async () => {
        try {
            await toggleWebNotifications(user.id);
            setWebNotifications(prev => prev === 0 ? 1 : 0);
            update();
        } catch (err) {
            console.error(err);
        }
    };


    return (
        <>
            <Button variant="transparent" onClick={() => setOpen((prev) => !prev)}>
                <img
                    src="/icons/settings-wheel.svg"
                    alt="Modify btn"
                    className={styles.modifyIcon}
                />
            </Button>

            <Modal
                title="Paramètres"
                open={open}
                onClose={() => setOpen(false)}
            >
                <div className={styles.content}>
                    <div className={`glassBorder ${styles.section}`}>
                        <h3>Modifier les informations du compte</h3>
                        <div className={styles.test}>
                            <h4>Changer de Prénom</h4>
                            <TextInput
                                value={name}
                                onChange={handleNameChange}
                                type="text"
                            />
                        </div>

                        <div className={styles.test}>
                        <h4>Changer de nom</h4>
                            <TextInput
                                value={lastname}
                                onChange={handleLastnameChange}
                                type="text"
                            />
                        </div>

                        <div className={styles.test}>
                        <h4>Changer de numéro de téléphone</h4>
                            <TextInput
                                value={phone}
                                onChange={handlePhoneChange}
                                type="text"
                            />
                        </div>

                        <Button
                            className={styles.submitBtn}
                            onClick={handleSubmit}
                        >
                            Confirmer
                        </Button>
                    </div>

                    <div className={`glassBorder ${styles.section}`}>
                        <h3>Apparence</h3>
                        <ThemeSwitcher/>
                    </div>

                    <div className={`glassBorder ${styles.section}`}>
                        <h3>Notifications</h3>

                        <div className={styles.test}>
                            <h4>Notifications par email</h4>
                            <input
                                type="checkbox"
                                checked={emailNotifications === 1}
                                onChange={handleEmailToggle}
                            />
                        </div>

                        <div className={styles.test}>
                            <h4>Notifications sur le site</h4>
                            <input
                                type="checkbox"
                                checked={webNotifications === 1}
                                onChange={handleWebToggle}
                            />
                        </div>
                    </div>


                    <div className={`glassBorder ${styles.section}`}>
                        <h3>Divers</h3>
                        <ExportCalendarBtn />
                    </div>

                    <div className={`glassBorder ${styles.section}`}>
                        <h3>Sécurité du compte</h3>

                        <Button variant="danger" onClick={handleLogout}>
                            Déconnexion
                        </Button>

                        <Button
                            variant="danger"
                            onClick={() => setIsDelete(true)}
                        >
                            Supprimer le compte
                        </Button>
                    </div>
                </div>
            </Modal>

            <Modal
                title="Validation"
                open={isDelete}
                onClose={() => setIsDelete(false)}
            >
                <div className={styles.section}>
                    <p className={styles.alignText}>
                        Êtes vous vraiment sûr de vouloir supprimer votre compte ?
                    </p>
                    <Button
                        variant="danger"
                        className={styles.submitBtn}
                        onClick={handleDelete}
                    >
                        Confirmer
                    </Button>
                </div>
            </Modal>
        </>
    );
}
