import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import {Box, Button, IconButton, Toolbar, useTheme} from "@mui/material";
import AccountType from "../../components/Account";
import {useTranslation} from "react-i18next";
import {DataGrid, GridColDef, GridRowId, GridRowSelectionModel} from "@mui/x-data-grid";
import {useEffect, useState} from "react";
import { useQuery } from "@tanstack/react-query";
import { fetchAccounts } from "../query/Queries";
import { useAccount } from "../AccountProvider";

export default function AccountsInfo() {
    const theme = useTheme();
    const {t} = useTranslation();

    function handleCustomerEdit(account: AccountType) {
        //TODO: implement
        console.log("CustomerEdit", account);
    }
    
/*
    for testing purposes
    for (let i = 0; i < 100; i++) {
        _rows.push(_rows[5]);
    }
* */

    //TODO: get per REST
    const [rows, setRows] = useState<AccountType[]>([]);
    const [selectedRows, setSelectedRows] = useState<Set<GridRowId>>(new Set());

    const {user: loginData} = useAccount();

    const { data } = useQuery({
        queryKey: ["fetchAccounts", loginData],
        queryFn: () => fetchAccounts(loginData? loginData : {email: "", password: "", session: "", customerId: -1}),
        retry: 3,
        retryDelay: 1000,
    });

    useEffect(() => {
        if (data) {
            setRows(data);
        }
    }, [data]);

    const handleSelectionChange = (newSelection: GridRowSelectionModel) => {
        setSelectedRows(newSelection.ids);
    };

    const handleDeleteSelected = async () => {
        selectedRows.forEach((row) => {
            //TODO: send delete command, or send deleteall
            console.log(row);
        })

        setRows(rows.filter((row) => !selectedRows.has(row.id)));
    };

    const columns: GridColDef<(typeof rows)[number]>[] = [
        {field: 'id', headerName: 'ID', width: 60},
        {
            field: 'admin',
            headerName: t('admin'),
            type: "boolean",
            width: 90,
            editable: true
        },
        {
            field: 'email',
            headerName: t('email'),
            width: 150,
            editable: true,
        },
        {
            field: 'langI18n',
            headerName: t('language'),
            width: 150,
            editable: true,
        },
        { //edit billing information button
            field: "customer",
            headerName: t('address'),
            width: 90,
            sortable: false,
            disableReorder: true,
            disableColumnMenu: true,
            renderCell: params => <IconButton onClick={() => handleCustomerEdit(params.row)}> <EditIcon/> </IconButton>,
        }
    ];

    return (
        <Box
            className="page-table"
            sx={{
                backgroundColor: theme.palette.background.paper,
                color: theme.palette.text.secondary
            }}
        >
            <DataGrid
                rows={rows}
                columns={columns}
                initialState={{}}
                checkboxSelection
                disableRowSelectionOnClick
                onRowSelectionModelChange={handleSelectionChange}
                slots={{ toolbar: () => (
                    <Toolbar>
                        <Button
                            variant="contained"
                            color="error"
                            startIcon={<DeleteIcon/>}
                            onClick={handleDeleteSelected}
                            disabled={selectedRows.size === 0}
                            sx={{
                                marginRight: 1
                            }}
                        >
                            {t('deleteAccount')}
                        </Button>
                    </Toolbar>
                    )}}
                showToolbar
                processRowUpdate={(updatedRow) => {
                    setRows(rows.map(row => row.id === updatedRow.id ? updatedRow : row));
                    //TODO: make REST callback
                    return updatedRow;
                }}
            />
        </Box>
    );
}
