import React, { useEffect, useRef, useState } from 'react';
import { Api as Auth, AccountDetailRespond } from '../../client/auth_client';
import './PhoneInputComponent';
import PhoneInputComponent from './PhoneInputComponent.tsx';

interface EditUserModalProps {
    user: AccountDetailRespond;
    closeModal: () => void;
}

const EditUserModal: React.FC<EditUserModalProps> = ({ user, closeModal }) => {
    const modalRef = useRef<HTMLDivElement>(null);
    const [editingUser, setEditingUser] = useState(user);
    const [dialCode, setDialCode] = useState<string | null>(user.dialCode ?? "");
    const [phoneNumber, setPhoneNumber] = useState<string | null>(user.phone ?? "");
    const [successMessage, setSuccessMessage] = useState<string | null>(null);
    const [loading, setLoading] = useState<boolean>(false);

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape') {
                closeModal();
            }
        };

        const handleClickOutside = (e: MouseEvent) => {
            if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
                closeModal();
            }
        };

        document.addEventListener('keydown', handleKeyDown);
        document.addEventListener('mousedown', handleClickOutside);

        return () => {
            document.removeEventListener('keydown', handleKeyDown);
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [closeModal]);

    const editUser = async () => {
        setLoading(true); // Start loading
        const token = localStorage.getItem("authToken");
        const client = new Auth({
            baseUrl: "/auth",
            securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
        });

        try {
            const result = await client.account.editAccountCreate({
                userId: user.id,
                newDialCode: dialCode,
                newEmail: editingUser.email,
                newPhone: phoneNumber,
                newUserName: editingUser.userName,
            });

            if (result.status === 200) {
                setSuccessMessage("Operation successful!");
                setTimeout(() => {
                    setSuccessMessage(null);
                    closeModal();
                }, 2000);
            } else {
                alert("Failed to update user details. Please try again.");
            }
        } catch (error) {
            console.error("Error updating user details:", error);
            alert("Failed to update user details. Please try again.");
        } finally {
            setLoading(false); // Stop loading
        }
    };

    return (
        <div className="edit-user-window">
            <div className="edit-user-content" ref={modalRef}>
                <h3>Edit User</h3>
                {successMessage && <div className="success-message">{successMessage}</div>}
                <label>
                    Name:
                    <input
                        type="text"
                        value={editingUser.userName ?? ''}
                        onChange={(e) => setEditingUser({ ...editingUser, userName: e.target.value })}
                        className="form-control"
                    />
                </label>
                <label>
                    Email:
                    <input
                        type="email"
                        value={editingUser.email ?? ''}
                        onChange={(e) => setEditingUser({ ...editingUser, email: e.target.value })}
                        className="form-control"
                    />
                </label>
                <label>
                    Phone:
                    <PhoneInputComponent
                        value={`${dialCode}${phoneNumber}`}
                        onChange={(phone, data) => {
                            let lenOfDialCode: number = 0;
                            if ("dialCode" in data) {
                                lenOfDialCode = data.dialCode.length;
                                setDialCode(data.dialCode);
                            }

                            const phoneNumber = phone.slice(lenOfDialCode, phone.length);
                            setPhoneNumber(phoneNumber);
                        }}
                    />
                </label>
                <div className="edit-user-actions">
                    <button
                        className="btn-save"
                        onClick={editUser}
                        disabled={loading}
                    >
                        {loading && (<span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>)}
                        Save
                    </button>
                    <button
                        className="btn-cancel"
                        onClick={closeModal}
                        disabled={loading}
                    >
                        Cancel
                    </button>
                </div>
            </div>
        </div>
    );
};

export default EditUserModal;
