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";

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

    //TODO: add colors to gauges for rating adn stock
    function mapValueToColor(minVal: number, maxVal: number, actualVal: number): string {
        const clamped = Math.min(Math.max(actualVal, minVal), maxVal);

        // Calculate interpolation ratio (0-1)
        const ratio = maxVal !== minVal
            ? (clamped - minVal) / (maxVal - minVal)
            : 0;
        return hsvDegToHex(120 * ratio);//120° is green, 0° is red
    }

    function hsvDegToHex(h: number): string {
        h = Math.max(0, Math.min(360, h));
    
        const c = 1;
        const x = (1 - Math.abs(((h / 60) % 2) - 1));
      
        let r = 0, g = 0, b = 0;
        if (h < 60) {
          r = c; g = x; b = 0;
        } else if (h < 120) {
          r = x; g = c; b = 0;
        } else if (h < 180) {
          r = 0; g = c; b = x;
        } else if (h < 240) {
          r = 0; g = x; b = c;
        } else if (h < 300) {
          r = x; g = 0; b = c;
        } else {
          r = c; g = 0; b = x;
        }
      
        // scale to 0-255
        const rHex = Math.round(r * 255).toString(16).padStart(2, '0');
        const gHex = Math.round(g * 255).toString(16).padStart(2, '0');
        const bHex = Math.round(b * 255).toString(16).padStart(2, '0');
      
        return `#${rHex}${gHex}${bHex}`;
    }

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

    const _rows: Item[] = [
        {
            id: "1",
            uuid: "uuid123",
            name: "Item",
            description: "Super duper geil <b>wichtiger text </b>",
            price100: 1000,
            stock: 100,
            stockExpected: 1200,
            category: "garden",
            rating: 7,
            discount100: 21,
        },
        {
            id: "2",
            uuid: "uuid12312412",
            name: "Schlauch",
            description: "Schlauchiger Schlauch für Schlauchige Angelegenheiten",
            price100: 10,
            stock: 50,
            stockExpected: 100,
            category: "technicalComponents",
            rating: 10,
            discount100: 21,
        },
    ]

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

    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: "UUID",
            type: "string",
            width: 120,
            editable: true
        },
        {
            field: 'name',
            headerName: t('name'),
            width: 150,
            editable: true,
        },
        {
            field: 'category',
            headerName: t('category'),
            width: 150,
            editable: true,
        },
        {
            field: 'description',
            headerName: t('description'),
            width: 150,
            editable: true,
        },
        {
            field: 'price100',
            headerName: t('price100'),
            width: 100,
            editable: true,
            type: 'number'
        },
        {
            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={params.row.stock} valueMin={0} valueMax={params.row.stockExpected} startAngle={-90} endAngle={90} sx={{
                [`& .${gaugeClasses.valueArc}`]: {
                    fill: () => {return mapValueToColor(0, params.row.stockExpected, params.row.stock)},
                },
            }}/>
        },
        {
            field: 'rating',
            headerName: t('rating'),
            width: 100,
            editable: true,
            type: 'number',
            renderCell: params => <Gauge value={params.row.rating} valueMin={0} valueMax={10} startAngle={-90} endAngle={90} sx={{
                [`& .${gaugeClasses.valueArc}`]: {
                    fill: () => {return mapValueToColor(0, 10, 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>
    );
}
