import SectionContainer from '../../components/SectionContainer';
import { useEffect, useState, useRef } from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { Typography, Button, Dialog, DialogTitle, DialogContent, IconButton, Box } from '@mui/material';
import EditRoundedIcon from '@mui/icons-material/EditRounded';
import DeleteRoundedIcon from '@mui/icons-material/DeleteRounded';
import AddOrEditUserForm from './AddOrEditUserForm';
import UserApi from '../../api/userApi';
import { useAuth } from '../../context/AuthContext';
import useApiToast from '../../hooks/useApiToast';
import '../../App.css';

const columnsBase = [
    { field: 'email', headerName: 'Email', width: 260 },
    { field: 'name', headerName: 'Name', width: 140 },
    { field: 'middleName', headerName: 'Middle Name', width: 140 },
    { field: 'lastName', headerName: 'Last Name', width: 160 },
    { field: 'displayName', headerName: 'Display Name', width: 180, valueGetter: (params) => params?.row?.displayName ?? '—' },
    { field: 'tenantId', headerName: 'Tenant Id', width: 240, valueGetter: (params) => params?.row?.tenantId ?? '—' },
    { field: 'roleId', headerName: 'Role Id', width: 240, valueGetter: (params) => params?.row?.roleId ?? '—' },
    {
        field: 'lastLogIn',
        headerName: 'Last Login',
        width: 180,
        valueFormatter: (params) => {
            const date = params?.value;
            return date ? new Date(date).toLocaleString() : '—';
        }
    },
    {
        field: 'lastLogOut',
        headerName: 'Last Logout',
        width: 180,
        valueFormatter: (params) => {
            const date = params?.value;
            return date ? new Date(date).toLocaleString() : '—';
        }
    },
    { field: 'status', headerName: 'Status', width: 120 },
    {
        field: 'createdAt',
        headerName: 'Created At',
        width: 180,
        valueFormatter: (params) => {
            const date = params?.value;
            return date ? new Date(date).toLocaleString() : '—';
        }
    },
    { field: 'createdBy', headerName: 'Created By', width: 160, valueGetter: (p) => p?.row?.createdBy ?? '—' },
    {
        field: 'updatedAt',
        headerName: 'Updated At',
        width: 180,
        valueFormatter: (params) => {
            const date = params?.value;
            return date ? new Date(date).toLocaleString() : '—';
        }
    },
    { field: 'updatedBy', headerName: 'Updated By', width: 160, valueGetter: (p) => p?.row?.updatedBy ?? '—' },
];

export default function UserManagement() {
    const { user } = useAuth();
    const thalosToken = user?.thalosToken || localStorage.getItem('thalosToken');
    const apiRef = useRef(null);

    const [rows, setRows] = useState([]);
    const [open, setOpen] = useState(false);
    const [editingData, setEditingData] = useState(null);
    const [confirmOpen, setConfirmOpen] = useState(false);
    const [rowToDelete, setRowToDelete] = useState(null);
    const { handleError } = useApiToast();

    const hasLoaded = useRef(false);

    useEffect(() => {
        if (thalosToken) {
            apiRef.current = new UserApi(thalosToken);
        }
    }, [thalosToken]);

    useEffect(() => {
        if (!hasLoaded.current) {
            loadData();
            hasLoaded.current = true;
        }
    }, []);

    const handleEditClick = (params) => {
        if (!params || !params.row) return;
        const r = params.row;
        const normalized = {
            _id: r._id || r._Id || '',
            id: r.id || r.Id || '',
            email: r.email ?? '',
            name: r.name ?? '',
            middleName: r.middleName ?? '',
            lastName: r.lastName ?? '',
            displayName: r.displayName ?? '',
            tenantId: r.tenantId ?? '',
            roleId: r.roleId ?? '',
            status: r.status ?? 'Active',
            companies: Array.isArray(r.companies) ? r.companies : [],
            projects: Array.isArray(r.projects) ? r.projects : [],
          };
        setEditingData(normalized);
        setOpen(true);
    };

    const handleDeleteClick = (row) => {
        if (!row) return;
        setRowToDelete(row);
        setConfirmOpen(true);
    };

    const handleConfirmDelete = async () => {
        try {
            if (!apiRef.current || !rowToDelete?._id) throw new Error('Missing API or user id');

            const payload = {
                _Id: rowToDelete._id || rowToDelete._Id,
                email: rowToDelete.email ?? '',
                name: rowToDelete.name ?? '',
                middleName: rowToDelete.middleName ?? '',
                lastName: rowToDelete.lastName ?? '',
                roleId: '68407642ec46a0e6fe1e8ec9',
                tenantId: '6894f9ddfb7072bdfc881613',
                status: 'Inactive',
            };

            await apiRef.current.updateUser(payload);
            await loadData();
        } catch (error) {
            console.error('Delete failed:', error);
        } finally {
            setConfirmOpen(false);
            setRowToDelete(null);
        }
    };

    const loadData = async () => {
        try {
            if (!apiRef.current) throw new Error('Missing Thalos token or API not initialized');
            const data = await apiRef.current.getAllUsers();
            const safeData = Array.isArray(data) ? data : [];
            setRows(safeData);
        } catch (error) {
            console.error('Error loading data:', error);
            handleError(error, 'Failed to load users');
            setRows([]);
        }
    };

    const columns = [
        {
            field: 'actions',
            headerName: '',
            width: 130,
            renderCell: (params) => (
                <Box display="flex" alignItems="center" justifyContent="flex-start" height="100%" gap={1}>
                    <IconButton
                        size="small"
                        sx={{
                            backgroundColor: '#DFCCBC',
                            color: '#26201A',
                            '&:hover': { backgroundColor: '#C2B2A4' },
                            borderRadius: 2,
                            p: 1,
                        }}
                        onClick={() => handleEditClick(params)}
                    >
                        <EditRoundedIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                        size="small"
                        sx={{
                            backgroundColor: '#FBE9E7',
                            color: '#C62828',
                            '&:hover': { backgroundColor: '#EF9A9A' },
                            borderRadius: 2,
                            p: 1,
                        }}
                        onClick={() => handleDeleteClick(params?.row)}
                    >
                        <DeleteRoundedIcon fontSize="small" />
                    </IconButton>
                </Box>
            )
        },
        ...columnsBase,
    ];

    return (
        <SectionContainer sx={{ width: '100%' }}>
            <Dialog open={open} onClose={() => { setOpen(false); setEditingData(null); }} maxWidth="md" fullWidth>
                <DialogTitle>{editingData ? 'Edit User' : 'Add User'}</DialogTitle>
                <DialogContent>
                    <AddOrEditUserForm
                        key={editingData?._id || editingData?.id || (open ? 'editing' : 'new')}
                        onAdd={async () => {
                            await loadData();
                            setOpen(false);
                            setEditingData(null);
                        }}
                        initialData={editingData}
                        onCancel={() => {
                            setOpen(false);
                            setEditingData(null);
                        }}
                    />
                </DialogContent>
            </Dialog>

            <Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)}>
                <DialogTitle>Confirm Delete</DialogTitle>
                <DialogContent>
                    <Typography>
                        Are you sure you want to delete <strong>{rowToDelete?.email || rowToDelete?.name}</strong>?
                    </Typography>
                    <Box mt={2} display="flex" justifyContent="flex-end" gap={1}>
                        <Button onClick={() => setConfirmOpen(false)} className='button-transparent'>Cancel</Button>
                        <Button variant="contained" onClick={handleConfirmDelete} className="button-gold">Delete</Button>
                    </Box>
                </DialogContent>
            </Dialog>

            <Box mt={2} sx={{ width: '100%', overflowX: 'auto' }}>
                <Box sx={{ width: '100%', overflowX: 'auto' }}>
                    <DataGrid
                        rows={rows}
                        columns={columns}
                        pageSize={5}
                        rowsPerPageOptions={[5]}
                        getRowSpacing={() => ({ top: 4, bottom: 4 })}
                        getRowId={(row) => row._id || row.id || row.email}
                        autoHeight
                        disableColumnMenu
                        getRowHeight={() => 'auto'}
                        sx={{
                            '& .MuiDataGrid-cell': {
                                display: 'flex',
                                alignItems: 'center',
                            },
                            '& .MuiDataGrid-columnHeader': {
                                display: 'flex',
                                alignItems: 'center',
                            }
                        }}
                    />
                </Box>

                <Box display="flex" justifyContent="flex-end" mt={2}>
                    <Button variant="contained" className="button-gold" onClick={() => setOpen(true)} >
                        Add User
                    </Button>
                </Box>
            </Box>
        </SectionContainer>
    );
}