import {
  Box,
  Button,
  Divider,
  Paper,
  Stack,
  TextField,
  Typography,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} 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, User } from "../components/Account";
import { useAccount } from "../helper/AccountProvider";
import { deleteAccount, editAccount, fetchCustomer } from "../helper/query/Queries";
import "./pages.css";

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

  const [user, setUser] = useState<CustomerType>({
    name: "",
    surname: "",
    address: "",
    country: "",
    zip: "",
    id: userData?.customerId || 0,
  });

  const [userDataState, setUserDataState] = useState<User>(userData || {
    password: "",
    email: "",
    customerId: 0,
    session: "",
    isAdmin: false,
  });

  useEffect(() => {
    if (userData?.customerId) {
      setUser((prev) => ({
        ...prev,
        id: userData.customerId,
      }));
    }
  }, [userData]);

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

  // Neu: Passwort-Dialog-Status und Passwort-Input
  const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
  const [passwordInput, setPasswordInput] = useState("");

  const { data } = useQuery<CustomerType>({
    queryKey: ["fetchCustomer", userData?.customerId],
    queryFn: () => fetchCustomer(userData?.customerId || 0),
    retry: 1,
    retryDelay: 1000,
  });

  const { refetch: deleteRefetch } = useQuery({
    queryKey: ["deleteAccount", userDataState],
    queryFn: () => deleteAccount(userDataState!),
    enabled: false,
  });

  const { refetch: editRefetch } = useQuery({
    queryKey: ["editAccount", form],
    queryFn: () => editAccount(form),
    enabled: false,
  });

  useEffect(() => {
    if (data) {
      setUser(data);
      setForm(data);
    }
  }, [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 = async () => {
    setUser(form);
    setEdit(false);
    await editRefetch();
  };

  // Neu: Passwort-Dialog öffnen
  const handleDeleteClick = () => {
    setPasswordInput("");
    setPasswordDialogOpen(true);
  };

  // Neu: Passwort-Dialog schließen
  const handlePasswordDialogClose = () => {
    setPasswordDialogOpen(false);
  };

  // Neu: Passwort-Eingabe bestätigen
  const handlePasswordConfirm = async () => {
    if (!passwordInput) {
      alert(t("pleaseEnterPassword"));
      return;
    }
    // Passwort in Form aktualisieren (hier z.B. als field "password", anpassen falls anders)
    setUserDataState({ ...userDataState, password: passwordInput });

    // Erst User-Daten mit Passwort aktualisieren
    try {
      await editRefetch(); // Achtung: editRefetch verwendet immer noch alten form, daher call direkt mit updatedForm:
      // Danach Account löschen
      await deleteRefetch();
      logout();
      navigate("/");
    } catch (error) {
      console.error("Fehler beim Löschen des Accounts:", error);
      alert(t("deleteAccountFailed"));
    } finally {
      setPasswordDialogOpen(false);
    }
  };

  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={handleDeleteClick} // Neu: Passwort-Dialog öffnen
                sx={{ marginLeft: "auto" }}
            >
              {t("deleteAccount")}
            </Button>
          </Box>
        </Paper>

        {/* Passwort-Dialog */}
        <Dialog open={passwordDialogOpen} onClose={handlePasswordDialogClose}>
          <DialogTitle>{t("confirmDeleteAccount")}</DialogTitle>
          <DialogContent>
            <Typography>{t("enterPasswordToConfirmDeletion")}</Typography>
            <TextField
                autoFocus
                margin="dense"
                label={t("password")}
                type="password"
                fullWidth
                variant="standard"
                value={passwordInput}
                onChange={(e) => setPasswordInput(e.target.value)}
            />
          </DialogContent>
          <DialogActions>
            <Button onClick={handlePasswordDialogClose}>{t("cancel")}</Button>
            <Button color="error" onClick={handlePasswordConfirm}>
              {t("delete")}
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
  );
}
