import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import {Box, Button, IconButton, Toolbar, useTheme} from "@mui/material";
import Item from "../../components/Item";
import {useTranslation} from "react-i18next";
import {DataGrid, GridColDef, GridRowId, GridRowSelectionModel} from "@mui/x-data-grid";
import {useEffect, useState} from "react";
import {Gauge, gaugeClasses} from "@mui/x-charts";
import {useAccount} from "../AccountProvider.tsx";
import {useQuery} from "@tanstack/react-query";
import {fetchItems} from "../query/Queries.tsx";
import { mapValueToColor } from "../../util/ColorUtil.tsx";

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

    function handleIconEdit(item: Item) {
        //TODO: implement
        console.log("IconEdit", item);
    }

    const [rows, setRows] = useState<Item[]>([]);
    const [selectedRows, setSelectedRows] = useState<Set<GridRowId>>(new Set());

    const {user: loginData} = useAccount();

    const { data } = useQuery({
        queryKey: ["fetchItems", loginData],
        queryFn: () => fetchItems(),
        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: 'uuid',
            headerName: t('uuid'),
            type: "string",
            width: 120,
            editable: true
        },
        {
            field: 'name',
            headerName: t('name'),
            width: 200,
            editable: true,
        },
        {
            field: 'category',
            headerName: t('category'),
            width: 150,
            editable: true,
            valueFormatter: (val) => t(val),
        },
        {
            field: 'description',
            headerName: t('description'),
            width: 150,
            editable: true,
        },
        {
            field: 'price100',
            headerName: t('price100€'),
            width: 100,
            editable: true,
            type: 'number',
            valueFormatter: (val) => (val / 100).toFixed(2),
        },
        {
            field: 'discount100',
            headerName: t('discount100'),
            width: 120,
            editable: true,
            type: 'number'
        },
        {
            field: 'stock',
            headerName: t('stock'),
            width: 100,
            editable: true,
            type: 'number',
            renderCell: params => <Gauge value={Math.min(params.row.stock, params.row.stockExpected)} valueMin={0} valueMax={params.row.stockExpected} startAngle={-90} endAngle={90} sx={{
                [`& .${gaugeClasses.valueArc}`]: {
                    fill: () => {return mapValueToColor(0, params.row.stockExpected, params.row.stock)},
                },
            }} text={() => `${params.row.stock}`} />
        },
        {
            field: 'rating',
            headerName: t('rating'),
            width: 100,
            editable: false, //the rating is averaged from ratings
            type: 'number',
            renderCell: params => <Gauge value={Math.min(params.row.rating, 10)} valueMin={0} valueMax={10} startAngle={-90} endAngle={90} sx={{
                [`& .${gaugeClasses.valueArc}`]: {
                    fill: () => {return mapValueToColor(0, 10, params.row.rating)},
                },
            }} text={() => `${params.row.rating}`} />
        },
        { //edit billing information button
            field: "actualPrice",
            headerName: t('actualPrice'),
            width: 90,
            editable: false,
            valueGetter: (_, row) => (row.price100 / 100 * ((100-row.discount100)/100)).toFixed(2)
        },
        {
            field: 'images',
            headerName: t('images'),
            width: 90,
            editable: false,
            renderCell: params => <IconButton onClick={() => handleIconEdit(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('deleteProduct')}
                            </Button>
                        </Toolbar>
                    )}}
                showToolbar
                processRowUpdate={(updatedRow) => {
                    setRows(rows.map(row => row.id === updatedRow.id ? updatedRow : row));
                    //TODO: make REST callback
                    return updatedRow;
                }}
            />
        </Box>
    );
}
