import { createFileRoute } from "@tanstack/react-router";
import { Box, Button, IconButton, Typography } from "@mui/material";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { useNavigate } from "@tanstack/react-router";
import { ConfigTable } from "../components/ConfigTable";

export const Route = createFileRoute("/config")({
    component: ConfigPage,
    validateSearch: (search: Record<string, unknown>): { from?: string } => {
        const from = typeof search.from === "string" ? search.from : undefined;
        return { from };
    }
});

function ConfigPage() {
    const navigate = useNavigate();
    const { from } = Route.useSearch();

    const handleAddNewKPI = () => {
        navigate({
            to: "/config-add",
            search: from ? { from } : undefined
        });
    };

    const handleBack = () => {
        if (from === "pitchbooks") {
            navigate({ to: "/pitchbooks" });
        } else {
            navigate({ to: "/" });
        }
    };

    return (
        <Box
            minHeight="100vh"
            width="100vw"
            bgcolor="white"
            display="flex"
            flexDirection="column"
            alignItems="center"
            pt={3}
            pb={4}
        >
            <Box
                width="100%"
                display="flex"
                justifyContent="space-between"
                alignItems="center"
                px={4}
            >
                <Box display="flex" alignItems="center">
                    <IconButton onClick={handleBack}>
                        <ArrowBackIcon fontSize="large" sx={{ color: '#383838' }}/>
                    </IconButton>
                    <Typography variant="h5" fontWeight="bold" ml={3}>
                        Konfiguration der Kennzahlen
                    </Typography>
                </Box>
                <Button
                    variant="contained"
                    onClick={handleAddNewKPI}
                    sx={{
                        backgroundColor: "#383838",
                        "&:hover": { backgroundColor: "#2e2e2e" },
                    }}
                >
                    Neue Kennzahl hinzufügen
                </Button>
            </Box>
            <Box sx={{ width: "100%", mt: 4, display: "flex", justifyContent: "center" }}>
                <ConfigTable from={from} />
            </Box>
        </Box>
    );
}