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 AddOrEditAdminForm from './AddOrEditAdminForm';
import { getExternalData, deleteExternalData } from '../../api/mongo/actions';
import useApiToast from '../../hooks/useApiToast';

const columnsBase = [
    { field: 'name', headerName: 'Name', flex: 2 },
    { field: 'description', headerName: 'Description', flex: 2 },
    { field: 'status', headerName: 'Status', width: 120 },
    {
        field: 'createdAt',
        headerName: 'Created At',
        width: 120,
        valueFormatter: (params) => {
            const date = params?.value;
            return date ? new Date(date).toLocaleString() : '—';
        }
    },
    { field: 'createdBy', headerName: 'Created By', flex: 1 },
    {
        field: 'updatedAt',
        headerName: 'Updated At',
        width: 120,
        valueFormatter: (params) => {
            const date = params?.value;
            return date ? new Date(date).toLocaleString() : '—';
        }
    },
    { field: 'updatedBy', headerName: 'Updated By', flex: 1 },
];

export default function Admin() {
    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 (!hasLoaded.current) {
    loadData();
    hasLoaded.current = true;
  }
}, []);

    const handleEditClick = (params) => {
        setEditingData(params.row);
        setOpen(true);
    };

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

    const handleConfirmDelete = async () => {
        try {
            await deleteExternalData(rowToDelete._Id);
            await loadData();
        } catch (error) {
            console.error('Delete failed:', error);
        } finally {
            setConfirmOpen(false);
            setRowToDelete(null);
        }
    };

    const loadData = async () => {
        try {
            const data = await getExternalData();
            const safeData = Array.isArray(data) ? data : [];
            setRows(safeData);
        } catch (error) {
            console.error('Error loading data:', error);
            handleError(error, 'Failed to load data');
            setRows([]);
        }
    };

    const columns = [
        ...columnsBase,
        {
            field: 'actions',
            headerName: '',
            width: 130,
            renderCell: (params) => (
                <Box display="flex" alignItems="center" justifyContent="flex-end" height="100%" gap={2}>
                    <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>
            )
        }
    ];

    return (
        <SectionContainer sx={{ width: '100%' }}>
            <Typography variant="h4" gutterBottom color='#26201AFF'>Admin</Typography>

            <Dialog open={open} onClose={() => { setOpen(false); setEditingData(null); }} maxWidth="md" fullWidth>
                <DialogTitle>{editingData ? 'Edit Item' : 'Add Item'}</DialogTitle>
                <DialogContent>
                    <AddOrEditAdminForm
                        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?.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}>
                <DataGrid
                    rows={rows}
                    columns={columns}
                    pageSize={5}
                    rowsPerPageOptions={[5]}
                    getRowSpacing={() => ({ top: 4, bottom: 4 })}
                />

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