import React, { useEffect, useState } from 'react';
import { Api, AccountDetailRespond, RoleModel } from '../client/auth_client';
import { UnAuthorized } from '../Auth/Auth';
import { useNavigate } from 'react-router-dom';
import './UserAccountList.css';
import CreateUserModal from './Module/CreateUserModal';
import EditUserModal from './Module/EditUserModal';
import EditPasswordModal from './Module/EditPasswordModal';
import EditRolesModal from './Module/EditRolesModal';
import ConfirmDeleteUserModal from './Module/ConfirmDeleteUserModal'

const UserAccountList: React.FC = () => {
    const [creatingUser, setCreatingUser] = useState<boolean>(false);
    const [editingUser, setEditingUser] = useState<AccountDetailRespond | null>(null);
    const [userToDelete, setUserToDelete] = useState<AccountDetailRespond | null>(null);
    const [editingPassword, setEditingPassword] = useState<AccountDetailRespond | null>(null);
    const [editingRolesUser, setEditingRolesUser] = useState<AccountDetailRespond | null>(null);
    const [users, setUsers] = useState<AccountDetailRespond[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);
    const [availableRoles, setAvailableRoles] = useState<RoleModel[]>([]);
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [nextPageExists, setNextPageExists] = useState<boolean>(false);
    const navigate = useNavigate();
    const [isDeletingUser, setIsDeletingUser] = useState<boolean>(false)

    const pageSize = 10;

    useEffect(() => {
        fetchUsers(currentPage).then();
    }, [currentPage]);

    useEffect(() => {
        fetchRoles().then();
    }, []);

    const fetchUsers = async (page: number) => {
        try {
            setLoading(true);
            const token = localStorage.getItem("authToken");
            const client = new Api({
                baseUrl: "/auth",
                securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
            });

            const result = await client.account.getListOfUsersCreate({ page, pageSize });

            if (result.status === 401) {
                await UnAuthorized(navigate);
            } else if (result?.data && result.data.accountsDetail) {
                setUsers(result.data.accountsDetail);
                setCurrentPage(page);
                setNextPageExists(result.data.nextPageExist || false);
            }
        } catch (e) {
            setError('Failed to load user accounts. Please try again later.');
            console.error('Error fetching user accounts:', e);
        } finally {
            setLoading(false);
        }
    };

    const fetchRoles = async () => {
        try {
            const token = localStorage.getItem("authToken");
            const client = new Api({
                baseUrl: "/auth",
                securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
            });

            const rolesResult = await client.role.getRolesCreate();
            if (rolesResult?.data?.roles) {
                setAvailableRoles(rolesResult.data.roles);
            }
        } catch (e) {
            console.error('Error fetching roles:', e);
        }
    };

    const closeAllWindows = () => {
        setCreatingUser(false);
        setEditingUser(null);
        setEditingPassword(null);
        setEditingRolesUser(null);
    };

    const handleDeleteUser = (user: AccountDetailRespond) => {
        setUserToDelete(user);
        setIsDeletingUser(true);
    };

    const handleConfirmDeleteUser = async () => {
        if (!userToDelete) return;

        try {
            const token = localStorage.getItem("authToken");
            const client = new Api({
                baseUrl: "/auth",
                securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
            });

            await client.account.deleteUserDelete({userId: userToDelete.id})
            fetchUsers(currentPage).then();
            alert(`User ${userToDelete.userName} deleted successfully!`);
        } catch (e) {
            console.error('Error deleting user:', e);
            alert('Failed to delete user. Please try again.');
        } finally {
            handleCloseDeleteUserModal();
        }
    };

    const handleCloseDeleteUserModal = () => {
        setUserToDelete(null);
        setIsDeletingUser(false);
    };

    return (
        <div className="user-list-container">
            {loading ? (
                <div className="loading-screen">
                    <div className="spinner">
                        <div className="lds-ring">
                            <div></div>
                            <div></div>
                            <div></div>
                            <div></div>
                        </div>
                    </div>
                </div>
            ) : error ? (
                <div className="error">{error}</div>
            ) : (
                <>
                    <div className="header-container">
                        <h2>User Accounts</h2>
                        <button className="btn-create" onClick={() => setCreatingUser(true)}>Create User</button>
                    </div>
                    <table className="user-list-table">
                        <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        {users.map((user) => (
                            <tr key={user.id}>
                                <td>{user.userName}</td>
                                <td>{user.email}</td>
                                <td>{user.phone}</td>
                                <td>
                                    <button className="btn-edit" onClick={() => setEditingUser(user)}>Edit</button>
                                    <button className="btn-password" onClick={() => setEditingPassword(user)}>Edit Password</button>
                                    <button className="btn-role" onClick={() => setEditingRolesUser(user)}>Edit Roles</button>
                                    <button
                                        className="btn-delete"
                                        onClick={() => handleDeleteUser(user)}>
                                        Delete
                                    </button>
                                </td>
                            </tr>
                        ))}
                        </tbody>
                    </table>
                    <div className="pagination-container">
                    <button className="pagination-button" disabled={currentPage === 1} onClick={() => setCurrentPage(currentPage - 1)}>Previous</button>
                        <span className="page-info">Page {currentPage}</span>
                        <button className="pagination-button" disabled={!nextPageExists} onClick={() => setCurrentPage(currentPage + 1)}>Next</button>
                    </div>

                    {creatingUser && <CreateUserModal closeModal={closeAllWindows} availableRoles={availableRoles} refreshList={()=> fetchUsers(currentPage)} />}
                    {editingUser && <EditUserModal user={editingUser} closeModal={closeAllWindows} />}
                    {editingPassword && <EditPasswordModal user={editingPassword} closeModal={closeAllWindows} />}
                    {editingRolesUser && <EditRolesModal user={editingRolesUser} availableRoles={availableRoles} closeModal={closeAllWindows} />}
                    {isDeletingUser && (
                        <ConfirmDeleteUserModal
                            userName={userToDelete?.userName ?? ''}
                            confirmDelete={handleConfirmDeleteUser}
                            closeModal={handleCloseDeleteUserModal}
                        />
                    )}

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

export default UserAccountList;
