import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { Box, Typography, IconButton } from "@mui/material";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { KPIForm } from "../../components/KPIForm";
import type { Kennzahl } from "../../types/kpi";
import { API_HOST } from "../../util/api";


export const Route = createFileRoute("/ff/config-add")({
    component: ConfigAddPage,
    validateSearch: (search: Record<string, unknown>): { from?: string } => {
        return {
            from: search.from as string | undefined,
        };
    },
});

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

    const handleBack = () => {
        navigate({
            to: "/ff/config",
            search: from ? { from } : undefined,
        });
    };

    const handleSave = async (formData: Partial<Kennzahl>) => {
        try {
            const existingKPIsResponse = await fetch(`${API_HOST}/api/kpi_setting/`);
            const existingKPIs = await existingKPIsResponse.json();
            const maxPosition = existingKPIs.length > 0
                ? Math.max(...existingKPIs.map((kpi: Kennzahl) => kpi.position))
                : 0;

            const kpiData = {
                ...formData,
                position: maxPosition + 1,
                active: formData.active !== false
            };

            const response = await fetch(`${API_HOST}/api/kpi_setting/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(kpiData),
            });


            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            navigate({
                to: "/ff/config",
                search: { success: "true", ...(from ? { from } : {}) },
            });

        } catch (error) {
            console.error('Error creating KPI:', error);
            throw error;
        }
    };


    const handleCancel = () => {
        navigate({
            to: "/ff/config",
            search: from ? { from } : undefined,
        });
    };

    return (
        <Box
            minHeight="100vh"
            width="100vw"
            bgcolor="#f5f5f5"
            display="flex"
            flexDirection="column"
            alignItems="center"
            pt={3}
            pb={4}
        >
            <Box
                width="100%"
                display="flex"
                justifyContent="flex-start"
                alignItems="center"
                px={4}
                mb={4}
            >
                <Box display="flex" alignItems="center">
                    <IconButton onClick={handleBack}>
                        <ArrowBackIcon fontSize="large" sx={{ color: '#383838' }} />
                    </IconButton>
                    <Typography variant="h5" fontWeight="bold" ml={3}>
                        Neue Kennzahl hinzufügen
                    </Typography>
                </Box>
            </Box>

            <KPIForm
                mode="add"
                key={Date.now()}
                onSave={handleSave}
                onCancel={handleCancel}
            />
        </Box>
    );
}
