import { Box, Button, Divider, Paper, Stack, TextField, Typography } from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { CustomerType } from "../components/Account";
import { useAccount } from "../helper/AccountProvider";
import { deleteAccount, fetchCustomer } from "../helper/query/Queries";
import "./pages.css";

export default function Account() {

    const { t } = useTranslation();
    const navigate = useNavigate();
    const { user: userData, logout } = useAccount();

    // Beispielhafte Userdaten (könnten aus Context/Backend kommen)
    const [user, setUser] = useState<CustomerType>({
        name: "",
        surname: "",
        address: "",
        country: "",
        zip: "",
        id: userData?.customerId || 0, // Initialwert
    });

    // Aktualisiere den `user`-State, wenn sich `userData` ändert
    useEffect(() => {
        if (userData?.customerId) {
            setUser((prev) => ({
                ...prev,
                id: userData.customerId, // Aktualisiere die ID
            }));
        }
    }, [userData]);

    const [edit, setEdit] = useState(false);
    const [form, setForm] = useState(user);

    const { data } = useQuery<CustomerType>({
        queryKey: ['fetchCustomer', userData?.customerId],
        queryFn: () => fetchCustomer(userData?.customerId || 0), // Funktion zum Abrufen der Kundendaten
        retry: 3, // Versucht es 3-mal erneut
        retryDelay: 1000, // Wartezeit zwischen den Versuchen (in ms)
    });

    const { refetch: deleteRefetch } = useQuery({ 
        queryKey: ['deleteAccount', userData?.customerId],
        queryFn: () => deleteAccount(userData?.customerId || 0), // Funktion zum Löschen des Accounts
        enabled: false, // Diese Abfrage wird nicht automatisch ausgeführt
    });

    useEffect(() => {
        if (data) {
            setUser(data); // Aktualisiere den user-State mit den abgerufenen Daten
            setForm(data); // Optional: Aktualisiere auch den form-State
        }
    }, [data]);

    const handleEdit = () => setEdit(true);
    const handleCancel = () => {
        setForm(user);
        setEdit(false);
    };
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setForm({ ...form, [e.target.name]: e.target.value });
    };
    const handleSave = () => {
        setUser(form);
        setEdit(false);
    };
    const handleDelete = () => {
        deleteRefetch();
        navigate("/");
        logout(); // Logout nach dem Löschen
    };

    return (
        <Box className="page-background page-background-center" sx={{ minHeight: "100vh", justifyContent: "flex-start", pt: 4 }}>
            <Paper elevation={3} sx={{ p: 4, maxWidth: 500, width: "100%", mx: "auto" }}>
                <Typography variant="h4" gutterBottom>
                    {t('myAccount')}
                </Typography>
                <Divider sx={{ mb: 3 }} />
                <Stack spacing={2}>
                    <TextField
                        label={t('name')}
                        name="name"
                        value={edit ? form.name : user.name}
                        onChange={handleChange}
                        disabled={!edit}
                        fullWidth
                    />
                    <TextField
                        label={t('surname')}
                        name="surname"
                        value={edit ? form.surname : user.surname}
                        onChange={handleChange}
                        disabled={!edit}
                        fullWidth
                    />
                    <TextField
                        label={t('address')}
                        name="address"
                        value={edit ? form.address : user.address}
                        onChange={handleChange}
                        disabled={!edit}
                        fullWidth
                    />
                    <TextField
                        label={t('country')}
                        name="country"
                        value={edit ? form.country : user.country}
                        onChange={handleChange}
                        disabled={!edit}
                        fullWidth
                    />
                    <TextField
                        label={t('zip')}
                        name="zip"
                        value={edit ? form.zip : user.zip}
                        onChange={handleChange}
                        disabled={!edit}
                        fullWidth
                    />
                </Stack>
                <Box sx={{ display: "flex", gap: 2, mt: 4 }}>
                    {edit ? (
                        <>
                            <Button variant="contained" color="primary" onClick={handleSave}>
                                {t('save')}
                            </Button>
                            <Button variant="outlined" color="secondary" onClick={handleCancel}>
                                {t('cancel')}
                            </Button>
                        </>
                    ) : (
                        <Button variant="contained" color="primary" onClick={handleEdit}>
                            {t('edit')}
                        </Button>
                    )}
                    <Button
                        variant="outlined"
                        color="error"
                        onClick={handleDelete}
                        sx={{ marginLeft: "auto" }}
                    >
                        {t('deleteAccount')}
                    </Button>
                </Box>
            </Paper>
        </Box>
    );
}