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

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

function KPIDetailPage() {
    const { kpiId } = Route.useParams();
    const navigate = useNavigate();
    const { from } = Route.useSearch();
    const [kennzahl, setKennzahl] = useState<Kennzahl | null>(null);
    const [isEditing, setIsEditing] = useState(false);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

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

    useEffect(() => {
        const fetchKennzahl = async () => {
            try {
                setLoading(true);
                const response = await fetch(`${API_HOST}/api/kpi_setting/${kpiId}`);
                if (!response.ok) {
                    if (response.status === 404) {
                        setError('KPI not found');
                        return;
                    }
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();
                setKennzahl(data);
                setError(null);
            } catch (err) {
                console.error('Error fetching KPI:', err);
                setError('Error loading KPI');
            } finally {
                setLoading(false);
            }
        };

        fetchKennzahl();
    }, [kpiId]);

    const handleSave = async (formData: Partial<Kennzahl>) => {
        try {
            const response = await fetch(`${API_HOST}/api/kpi_setting/${kpiId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData),
            });

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

            const updatedKennzahl = await response.json();
            setKennzahl(updatedKennzahl);
            setIsEditing(false);
        } catch (error) {
            console.error('Error saving KPI:', error);
            throw error;
        }
    };

    const handleCancel = () => {
        setIsEditing(false);
    };

    if (loading) {
        return (
            <Box
                minHeight="100vh"
                width="100vw"
                bgcolor="#f5f5f5"
                display="flex"
                justifyContent="center"
                alignItems="center"
                flexDirection="column"
            >
                <CircularProgress sx={{ color: '#383838', mb: 2 }} />
                <Typography>Lade KPI Details...</Typography>
            </Box>
        );
    }

    if (error || !kennzahl) {
        return (
            <Box
                minHeight="100vh"
                width="100vw"
                bgcolor="#f5f5f5"
                display="flex"
                justifyContent="center"
                alignItems="center"
                flexDirection="column"
            >
                <Typography variant="h6" mb={2}>
                    {error || 'KPI nicht gefunden'}
                </Typography>
                <Button
                    variant="contained"
                    onClick={() => navigate({ to: "/config" })}
                    sx={{
                        backgroundColor: "#383838",
                        "&:hover": { backgroundColor: "#2e2e2e" },
                    }}
                >
                    Zurück zur Konfiguration
                </Button>
            </Box>
        );
    }

    if (!isEditing) {
        return (
            <Box
                minHeight="100vh"
                width="100vw"
                bgcolor="#f5f5f5"
                display="flex"
                flexDirection="column"
                alignItems="center"
                pt={3}
                pb={4}
            >
                <Box
                    width="100%"
                    display="flex"
                    justifyContent="space-between"
                    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}>
                            Detailansicht
                        </Typography>
                    </Box>
                    <Button
                        variant="contained"
                        sx={{
                            backgroundColor: "#383838",
                            "&:hover": { backgroundColor: "#2e2e2e" },
                        }}
                        onClick={() => setIsEditing(true)}
                    >
                        Bearbeiten
                    </Button>
                </Box>
                <Paper
                    elevation={2}
                    sx={{
                        width: "90%",
                        maxWidth: 800,
                        p: 4,
                        borderRadius: 2,
                        backgroundColor: "white"
                    }}
                >
                    <Box mb={4}>
                        <Typography variant="h6" fontWeight="bold" mb={2}>
                            Kennzahl
                        </Typography>
                        <Typography variant="body1" sx={{ mb: 2, fontSize: 16 }}>
                            {kennzahl.name}
                        </Typography>
                    </Box>

                    <Divider sx={{ my: 3 }} />

                    <Box mb={4}>
                        <Typography variant="h6" fontWeight="bold" mb={2}>
                            Beschreibung
                        </Typography>
                        <Typography variant="body1" color="text.secondary">
                            {kennzahl.description || "Zurzeit ist die Beschreibung der Kennzahl leer. Klicken Sie auf den Bearbeiten-Button, um die Beschreibung zu ergänzen."}
                        </Typography>

                        <Box mt={2}>
                            <Typography variant="body2" color="text.secondary">
                                <strong>Erforderlich:</strong> {kennzahl.mandatory ? 'Ja' : 'Nein'}
                            </Typography>
                        </Box>
                    </Box>

                    <Divider sx={{ my: 3 }} />

                    <Box mb={4}>
                        <Typography variant="h6" fontWeight="bold" mb={2}>
                            Format
                        </Typography>
                        <Typography variant="body1" color="text.secondary">
                            {typeDisplayMapping[kennzahl.type] || kennzahl.type}
                        </Typography>
                    </Box>

                    <Divider sx={{ my: 3 }} />

                    <Box mb={4}>
                        <Typography variant="h6" fontWeight="bold" mb={2}>
                            Synonyme & Übersetzungen
                        </Typography>
                        <Typography variant="body1" color="text.secondary">
                            {kennzahl.translation || "Zurzeit gibt es keine Einträge für Synonyme und Übersetzungen der Kennzahl. Klicken Sie auf den Bearbeiten-Button, um die Liste zu ergänzen."}
                        </Typography>
                    </Box>

                    <Divider sx={{ my: 3 }} />

                    <Box mb={4}>
                        <Typography variant="h6" fontWeight="bold" mb={2}>
                            Beispiele von Kennzahl
                        </Typography>
                        <Typography variant="body1" color="text.secondary">
                            {kennzahl.example || "Zurzeit gibt es keine Beispiele der Kennzahl. Klicken Sie auf den Bearbeiten-Button, um die Liste zu ergänzen."}
                        </Typography>
                    </Box>
                </Paper>
            </Box>
        );
    }

    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}>
                        Kennzahl bearbeiten
                    </Typography>
                </Box>
            </Box>

            <KPIForm
                mode="edit"
                initialData={kennzahl}
                onSave={handleSave}
                onCancel={handleCancel}
            />
        </Box>
    );
}