import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import RefreshIcon from "@mui/icons-material/Refresh";
import SecurityIcon from "@mui/icons-material/Security";
import SettingsApplicationsIcon from "@mui/icons-material/SettingsApplications";
import StorageIcon from "@mui/icons-material/Storage";
import {
  Alert,
  Avatar,
  Box,
  Button,
  Card,
  CardContent,
  CircularProgress,
  FormControlLabel,
  Grid,
  IconButton,
  InputAdornment,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Paper,
  Stack,
  Switch,
  TextField,
  Typography
} from "@mui/material";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useEffect, useMemo, useRef, useState } from "react";
import { Controller, useForm } from "react-hook-form";

import {
  fetchServerConfig,
  fetchSettings,
  resetIcalSecret,
  triggerMailTest,
  triggerNtfyTest,
  ServerConfig,
  SettingsResponse,
  updateSettings,
  UpdateSettingsPayload
} from "../api/config";
import { request } from "../api/client";
import PageHeader from "../components/PageHeader";
import { useAuth } from "../contexts/AuthContext";
import { useSnackbar } from "../hooks/useSnackbar";
import { useTranslation } from "react-i18next";

interface HealthResponse {
  status: string;
}

type FormValues = {
  paperlessBaseUrl: string;
  paperlessExternalUrl: string;
  paperlessToken: string;
  schedulerIntervalMinutes: number;
  alertDaysBefore: number;
  mailServer: string;
  mailPort: string;
  mailUsername: string;
  mailPassword: string;
  mailUseTls: boolean;
  mailFrom: string;
  mailTo: string;
  ntfyServerUrl: string;
  ntfyTopic: string;
  ntfyToken: string;
  ntfyPriority: string;
  authUsername: string;
  authPassword: string;
};

const defaultValues: FormValues = {
  paperlessBaseUrl: "",
  paperlessExternalUrl: "",
  paperlessToken: "",
  schedulerIntervalMinutes: 60,
  alertDaysBefore: 30,
  mailServer: "",
  mailPort: "",
  mailUsername: "",
  mailPassword: "",
  mailUseTls: true,
  mailFrom: "",
  mailTo: "",
  ntfyServerUrl: "",
  ntfyTopic: "",
  ntfyToken: "",
  ntfyPriority: "default",
  authUsername: "",
  authPassword: ""
};

export default function SettingsPage() {
  const { authEnabled } = useAuth();
  const { showMessage } = useSnackbar();
  const { t } = useTranslation();

  const { data: health } = useQuery({
    queryKey: ["healthz"],
    queryFn: () => request<HealthResponse>("/healthz", { method: "GET" })
  });

  const {
    data: serverConfig,
    refetch: refetchServerConfig
  } = useQuery<ServerConfig>({
    queryKey: ["server-config"],
    queryFn: fetchServerConfig
  });

  const {
    data: settingsData,
    isLoading: loadingSettings,
    refetch: refetchSettings
  } = useQuery<SettingsResponse>({
    queryKey: ["settings"],
    queryFn: fetchSettings
  });

  const initialValuesRef = useRef<FormValues>(defaultValues);
  const [removePaperlessToken, setRemovePaperlessToken] = useState(false);
  const [removeMailPassword, setRemoveMailPassword] = useState(false);
  const [removeNtfyToken, setRemoveNtfyToken] = useState(false);
  const [removeAuthPassword, setRemoveAuthPassword] = useState(false);

  const {
    control,
    register,
    handleSubmit,
    reset,
    setValue,
    formState: { isSubmitting }
  } = useForm<FormValues>({
    defaultValues
  });

  useEffect(() => {
    if (!settingsData) {
      return;
    }
    const values: FormValues = {
      paperlessBaseUrl: settingsData.values.paperlessBaseUrl ?? "",
      paperlessExternalUrl: settingsData.values.paperlessExternalUrl ?? "",
      paperlessToken: "",
      schedulerIntervalMinutes: settingsData.values.schedulerIntervalMinutes,
      alertDaysBefore: settingsData.values.alertDaysBefore,
      mailServer: settingsData.values.mailServer ?? "",
      mailPort: settingsData.values.mailPort ? String(settingsData.values.mailPort) : "",
      mailUsername: settingsData.values.mailUsername ?? "",
      mailPassword: "",
      mailUseTls: settingsData.values.mailUseTls,
      mailFrom: settingsData.values.mailFrom ?? "",
      mailTo: settingsData.values.mailTo ?? "",
      ntfyServerUrl: settingsData.values.ntfyServerUrl ?? "",
      ntfyTopic: settingsData.values.ntfyTopic ?? "",
      ntfyToken: "",
      ntfyPriority: settingsData.values.ntfyPriority ?? "default",
      authUsername: settingsData.values.authUsername ?? "",
      authPassword: ""
    };

    initialValuesRef.current = values;
    setRemovePaperlessToken(false);
    setRemoveMailPassword(false);
    setRemoveNtfyToken(false);
    setRemoveAuthPassword(false);
    reset(values);
  }, [settingsData, reset]);

  const updateMutation = useMutation({
    mutationFn: (payload: UpdateSettingsPayload) => updateSettings(payload),
    onSuccess: async () => {
      showMessage(t("settings.saved"), "success");
      await Promise.all([refetchSettings(), refetchServerConfig()]);
    },
    onError: (error: Error) => {
      showMessage(error.message ?? t("contractForm.saveError"), "error");
    }
  });

  const resetIcalMutation = useMutation({
    mutationFn: () => resetIcalSecret(),
    onSuccess: async () => {
      showMessage(t("settings.icalTokenRenewed"), "success");
      await refetchSettings();
    },
    onError: (error: Error) => showMessage(error.message ?? t("settings.actionFailed"), "error")
  });

  const mailTestMutation = useMutation({
    mutationFn: () => triggerMailTest(),
    onSuccess: () => showMessage(t("settings.mailTestSuccess"), "success"),
    onError: (error: Error) => showMessage(error.message ?? t("settings.mailTestError"), "error")
  });

  const ntfyTestMutation = useMutation({
    mutationFn: () => triggerNtfyTest(),
    onSuccess: () => showMessage(t("settings.ntfyTestSuccess"), "success"),
    onError: (error: Error) => showMessage(error.message ?? t("settings.ntfyTestError"), "error")
  });

  const settings = settingsData;
  const icalSecret = settings?.icalSecret ?? null;
  const icalUrl = useMemo(() => {
    if (!icalSecret) return null;
    if (typeof window === "undefined") return null;
    const origin = window.location.origin;
    return `${origin}/api/calendar/feed.ics?token=${icalSecret}`;
  }, [icalSecret]);

  const onSubmit = (formValues: FormValues) => {
    const initial = initialValuesRef.current;
    if (!initial || !settings) {
      return;
    }

    const payload: UpdateSettingsPayload = {};
    const trimOrNull = (value: string) => {
      const trimmed = value.trim();
      return trimmed.length === 0 ? null : trimmed;
    };

    if (formValues.paperlessBaseUrl !== initial.paperlessBaseUrl) {
      payload.paperlessBaseUrl = trimOrNull(formValues.paperlessBaseUrl);
    }
    if (formValues.paperlessExternalUrl !== initial.paperlessExternalUrl) {
      payload.paperlessExternalUrl = trimOrNull(formValues.paperlessExternalUrl);
    }

    if (removePaperlessToken) {
      payload.paperlessToken = null;
    } else if (formValues.paperlessToken.trim().length > 0) {
      payload.paperlessToken = formValues.paperlessToken.trim();
    }

    if (formValues.schedulerIntervalMinutes !== initial.schedulerIntervalMinutes) {
      payload.schedulerIntervalMinutes = formValues.schedulerIntervalMinutes;
    }
    if (formValues.alertDaysBefore !== initial.alertDaysBefore) {
      payload.alertDaysBefore = formValues.alertDaysBefore;
    }

    if (formValues.mailServer !== initial.mailServer) {
      payload.mailServer = trimOrNull(formValues.mailServer);
    }

    if (formValues.mailPort !== initial.mailPort) {
      payload.mailPort = formValues.mailPort.trim()
        ? Number(formValues.mailPort)
        : null;
    }

    if (formValues.mailUsername !== initial.mailUsername) {
      payload.mailUsername = trimOrNull(formValues.mailUsername);
    }

    if (removeMailPassword) {
      payload.mailPassword = null;
    } else if (formValues.mailPassword.trim().length > 0) {
      payload.mailPassword = formValues.mailPassword.trim();
    }

    if (formValues.mailUseTls !== initial.mailUseTls) {
      payload.mailUseTls = formValues.mailUseTls;
    }

    if (formValues.mailFrom !== initial.mailFrom) {
      payload.mailFrom = trimOrNull(formValues.mailFrom);
    }

    if (formValues.mailTo !== initial.mailTo) {
      payload.mailTo = trimOrNull(formValues.mailTo);
    }

    if (formValues.ntfyServerUrl !== initial.ntfyServerUrl) {
      payload.ntfyServerUrl = trimOrNull(formValues.ntfyServerUrl);
    }

    if (formValues.ntfyTopic !== initial.ntfyTopic) {
      payload.ntfyTopic = trimOrNull(formValues.ntfyTopic);
    }

    if (removeNtfyToken) {
      payload.ntfyToken = null;
    } else if (formValues.ntfyToken.trim().length > 0) {
      payload.ntfyToken = formValues.ntfyToken.trim();
    }

    if (formValues.ntfyPriority !== initial.ntfyPriority) {
      payload.ntfyPriority = formValues.ntfyPriority === "default" ? null : formValues.ntfyPriority;
    }

    if (formValues.authUsername !== initial.authUsername) {
      payload.authUsername = trimOrNull(formValues.authUsername);
    }

    if (removeAuthPassword) {
      payload.authPassword = null;
    } else if (formValues.authPassword.trim().length > 0) {
      payload.authPassword = formValues.authPassword.trim();
    }

    if (Object.keys(payload).length === 0) {
      showMessage(t("settings.noChanges"), "info");
      return;
    }

    updateMutation.mutate(payload);
  };

  const handleCopy = async (text: string) => {
    try {
      if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(text);
        showMessage(t("actions.copy"), "success");
      } else {
        const textarea = document.createElement("textarea");
        textarea.value = text;
        textarea.setAttribute("readonly", "");
        textarea.style.position = "absolute";
        textarea.style.left = "-9999px";
        document.body.appendChild(textarea);
        textarea.select();
        const successful = document.execCommand("copy");
        document.body.removeChild(textarea);
        if (successful) {
          showMessage(t("actions.copy"), "success");
        } else {
          showMessage(t("actions.copyUnsupported"), "warning");
        }
      }
    } catch (error) {
      showMessage((error as Error).message ?? t("actions.copyFailed"), "error");
    }
  };

  const loading = loadingSettings || !settings;
  const paperlessTokenSet = settings?.secrets.paperlessTokenSet ?? false;
  const mailPasswordSet = settings?.secrets.mailPasswordSet ?? false;
  const ntfyTokenSet = settings?.secrets.ntfyTokenSet ?? false;
  const authPasswordSet = settings?.secrets.authPasswordSet ?? false;

  return (
    <>
      <PageHeader
        title={t("settings.title")}
        subtitle={t("settings.subtitle")}
      />

      <Grid container spacing={3} sx={{ mb: 3 }}>
        <Grid item xs={12} md={6}>
          <Paper variant="outlined" sx={{ borderRadius: 3, p: 3 }}>
              <Typography variant="h6" gutterBottom>
              {t("settings.systemStatus")}
              </Typography>
              <List>
                <ListItem>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: "success.main" }}>
                      <StorageIcon />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText
                    primary={t("settings.apiStatus")}
                    secondary={health?.status === "ok" ? t("settings.apiOk") : t("settings.apiError")}
                  />
                </ListItem>
                <ListItem>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: authEnabled ? "primary.main" : "warning.main" }}>
                      <SecurityIcon />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText
                    primary={t("settings.authStatus")}
                    secondary={authEnabled ? t("settings.authActive") : t("settings.authInactive")}
                  />
                </ListItem>
                <ListItem>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: serverConfig?.paperlessConfigured ? "primary.main" : "warning.main" }}>
                      <SettingsApplicationsIcon />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText
                    primary={t("settings.paperlessStatus")}
                    secondary={
                      serverConfig?.paperlessConfigured
                        ? t("settings.paperlessActive", {
                            url: serverConfig.paperlessBaseUrl ?? ""
                          })
                        : t("settings.paperlessInactive")
                    }
                  />
                </ListItem>
                <ListItem>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: serverConfig?.mailConfigured ? "primary.main" : "warning.main" }}>
                      <SettingsApplicationsIcon />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText
                    primary={t("settings.mailStatus")}
                    secondary={serverConfig?.mailConfigured ? t("settings.mailActive") : t("settings.mailInactive")}
                  />
                </ListItem>
                <ListItem>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: serverConfig?.ntfyConfigured ? "primary.main" : "warning.main" }}>
                      <SettingsApplicationsIcon />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText
                    primary={t("settings.ntfyStatus")}
                    secondary={serverConfig?.ntfyConfigured ? t("settings.ntfyActive") : t("settings.ntfyInactive")}
                  />
                </ListItem>
              </List>
          </Paper>
        </Grid>
        <Grid item xs={12} md={6}>
          <Card variant="outlined" sx={{ borderRadius: 3, height: "100%" }}>
            <CardContent>
              <Stack spacing={2}>
                <Box>
                  <Typography variant="h6">{t("settings.ical")}</Typography>
                  <Typography variant="body2" color="text.secondary">
                    {t("settings.icalDescription")}
                  </Typography>
                </Box>
                {icalUrl ? (
                  <TextField
                    label={t("settings.icalFeedUrl")}
                    value={icalUrl}
                    InputProps={{
                      readOnly: true,
                      endAdornment: (
                        <InputAdornment position="end">
                          <IconButton onClick={() => handleCopy(icalUrl)} edge="end">
                            <ContentCopyIcon fontSize="small" />
                          </IconButton>
                        </InputAdornment>
                      )
                    }}
                    fullWidth
                  />
                ) : (
                  <Alert severity="warning">{t("settings.icalTokenMissing")}</Alert>
                )}
                <Stack direction="row" spacing={2}>
                  <Button
                    variant="outlined"
                    startIcon={<RefreshIcon />}
                    onClick={() => resetIcalMutation.mutate()}
                    disabled={resetIcalMutation.isPending}
                  >
                    {t("settings.icalRenew")}
                  </Button>
                  {resetIcalMutation.isPending && <CircularProgress size={24} />}
                </Stack>
              </Stack>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      <Box component="form" onSubmit={handleSubmit(onSubmit)}>
        <Stack spacing={3}>
          <Card variant="outlined" sx={{ borderRadius: 3 }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t("settings.paperless")}
              </Typography>
              {loading ? (
                <CircularProgress size={24} />
              ) : (
                <Stack spacing={2}>
                  <TextField
                    label={t("settings.paperlessApiUrl")}
                    {...register("paperlessBaseUrl")}
                    placeholder={t("settings.paperlessExample")}
                    fullWidth
                  />
                  <TextField
                    label={t("settings.paperlessExternalUrl")}
                    {...register("paperlessExternalUrl")}
                    placeholder={t("settings.paperlessExample")}
                    fullWidth
                  />
                  <Stack direction={{ xs: "column", sm: "row" }} spacing={2} alignItems={{ xs: "stretch", sm: "center" }}>
                    <TextField
                      label={paperlessTokenSet && !removePaperlessToken ? t("settings.paperlessTokenNew") : t("settings.paperlessToken")}
                      {...register("paperlessToken")}
                      type="password"
                      fullWidth
                      placeholder={paperlessTokenSet && !removePaperlessToken ? "" : t("settings.paperlessTokenPlaceholder")}
                    />
                    <Button
                      variant="outlined"
                      color={removePaperlessToken ? "inherit" : "warning"}
                      onClick={() => {
                        if (removePaperlessToken) {
                          setRemovePaperlessToken(false);
                        } else {
                          setRemovePaperlessToken(true);
                          setValue("paperlessToken", "", { shouldDirty: true });
                        }
                      }}
                    >
                      {removePaperlessToken ? t("settings.paperlessTokenKeep") : t("settings.paperlessTokenRemove")}
                    </Button>
                  </Stack>
                  {paperlessTokenSet && !removePaperlessToken && (
                    <Typography variant="caption" color="text.secondary">
                      {t("settings.paperlessTokenInfo")}
                    </Typography>
                  )}
                </Stack>
              )}
            </CardContent>
          </Card>

          <Card variant="outlined" sx={{ borderRadius: 3 }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t("settings.scheduler")}
              </Typography>
              {loading ? (
                <CircularProgress size={24} />
              ) : (
                <Stack spacing={2}>
                  <TextField
                    label={t("settings.interval")}
                    type="number"
                    inputProps={{ min: 5, max: 1440 }}
                    {...register("schedulerIntervalMinutes", { valueAsNumber: true })}
                  />
                  <TextField
                    label={t("settings.alert")}
                    type="number"
                    inputProps={{ min: 1, max: 365 }}
                    {...register("alertDaysBefore", { valueAsNumber: true })}
                  />
                </Stack>
              )}
            </CardContent>
          </Card>

          <Card variant="outlined" sx={{ borderRadius: 3 }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t("settings.auth")}
              </Typography>
              {loading ? (
                <CircularProgress size={24} />
              ) : (
                <Stack spacing={2}>
                  <TextField label={t("settings.authUsername")} {...register("authUsername")} fullWidth />
                  <Stack direction={{ xs: "column", sm: "row" }} spacing={2} alignItems={{ xs: "stretch", sm: "center" }}>
                    <TextField
                      label={t("settings.authPassword")}
                      type="password"
                      {...register("authPassword")}
                      fullWidth
                      placeholder={t("settings.authPasswordPlaceholder")}
                    />
                    <Button
                      variant="outlined"
                      color={removeAuthPassword ? "inherit" : "warning"}
                      onClick={() => {
                        if (removeAuthPassword) {
                          setRemoveAuthPassword(false);
                        } else {
                          setRemoveAuthPassword(true);
                          setValue("authPassword", "", { shouldDirty: true });
                        }
                      }}
                    >
                      {removeAuthPassword ? t("settings.paperlessTokenKeep") : t("settings.authPasswordRemove")}
                    </Button>
                  </Stack>
                  {authPasswordSet && !removeAuthPassword && (
                    <Typography variant="caption" color="text.secondary">
                      {t("settings.authPasswordInfo")}
                    </Typography>
                  )}
                  <Typography variant="caption" color="text.secondary">
                    {t("settings.authHint")}
                  </Typography>
                </Stack>
              )}
            </CardContent>
          </Card>

          <Card variant="outlined" sx={{ borderRadius: 3 }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t("settings.mail")}
              </Typography>
              {loading ? (
                <CircularProgress size={24} />
              ) : (
                <Stack spacing={2}>
                  <TextField label={t("settings.smtpServer")} {...register("mailServer")} fullWidth />
                  <TextField
                    label={t("settings.smtpPort")}
                    type="number"
                    {...register("mailPort")}
                    fullWidth
                  />
                  <TextField label={t("settings.smtpUsername")} {...register("mailUsername")} fullWidth />
                  <Stack direction={{ xs: "column", sm: "row" }} spacing={2} alignItems={{ xs: "stretch", sm: "center" }}>
                    <TextField
                      label={mailPasswordSet && !removeMailPassword ? t("settings.smtpPasswordNew") : t("settings.smtpPassword")}
                      type="password"
                      {...register("mailPassword")}
                      fullWidth
                    />
                    <Button
                      variant="outlined"
                      color={removeMailPassword ? "inherit" : "warning"}
                      onClick={() => {
                        if (removeMailPassword) {
                          setRemoveMailPassword(false);
                        } else {
                          setRemoveMailPassword(true);
                          setValue("mailPassword", "", { shouldDirty: true });
                        }
                      }}
                    >
                      {removeMailPassword ? t("settings.paperlessTokenKeep") : t("settings.smtpPasswordRemove")}
                    </Button>
                  </Stack>
                  {mailPasswordSet && !removeMailPassword && (
                    <Typography variant="caption" color="text.secondary">
                      {t("settings.smtpPasswordInfo")}
                    </Typography>
                  )}
                  <FormControlLabel
                    control={
                      <Controller
                        name="mailUseTls"
                        control={control}
                        render={({ field }) => <Switch {...field} checked={field.value} />}
                      />
                    }
                    label={t("settings.tls")}
                  />
                  <TextField label={t("settings.mailFrom")} {...register("mailFrom")} fullWidth />
                  <TextField label={t("settings.mailTo")} {...register("mailTo")} fullWidth />
                  <Stack direction={{ xs: "column", sm: "row" }} spacing={2}>
                    <Button
                      variant="outlined"
                      onClick={() => mailTestMutation.mutate()}
                      disabled={mailTestMutation.isPending || !serverConfig?.mailConfigured}
                    >
                      {t("settings.mailTest")}
                    </Button>
                    {mailTestMutation.isPending && <CircularProgress size={24} />}
                  </Stack>
                  {mailTestMutation.isError && (
                    <Alert severity="error">{(mailTestMutation.error as Error).message ?? t("settings.mailTestError")}</Alert>
                  )}
                </Stack>
              )}
            </CardContent>
          </Card>

          <Card variant="outlined" sx={{ borderRadius: 3 }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t("settings.ntfy")}
              </Typography>
              {loading ? (
                <CircularProgress size={24} />
              ) : (
                <Stack spacing={2}>
                  <TextField label={t("settings.ntfyServer")} {...register("ntfyServerUrl")} fullWidth />
                  <TextField label={t("settings.ntfyTopic")} {...register("ntfyTopic")} fullWidth />
                  <Stack direction={{ xs: "column", sm: "row" }} spacing={2} alignItems={{ xs: "stretch", sm: "center" }}>
                    <TextField
                      label={ntfyTokenSet && !removeNtfyToken ? t("settings.ntfyTokenNew") : t("settings.ntfyToken")}
                      type="password"
                      {...register("ntfyToken")}
                      fullWidth
                    />
                    <Button
                      variant="outlined"
                      color={removeNtfyToken ? "inherit" : "warning"}
                      onClick={() => {
                        if (removeNtfyToken) {
                          setRemoveNtfyToken(false);
                        } else {
                          setRemoveNtfyToken(true);
                          setValue("ntfyToken", "", { shouldDirty: true });
                        }
                      }}
                    >
                      {removeNtfyToken ? t("settings.paperlessTokenKeep") : t("settings.ntfyTokenRemove")}
                    </Button>
                  </Stack>
                  <TextField
                    label={t("settings.ntfyPriority")}
                    select
                    SelectProps={{ native: true }}
                    {...register("ntfyPriority")}
                  >
                    <option value="default">default</option>
                    <option value="min">min</option>
                    <option value="low">low</option>
                    <option value="high">high</option>
                    <option value="urgent">urgent</option>
                  </TextField>
                  <Stack direction={{ xs: "column", sm: "row" }} spacing={2}>
                    <Button
                      variant="outlined"
                      onClick={() => ntfyTestMutation.mutate()}
                      disabled={ntfyTestMutation.isPending || !serverConfig?.ntfyConfigured}
                    >
                      {t("settings.ntfyTest")}
                    </Button>
                    {ntfyTestMutation.isPending && <CircularProgress size={24} />}
                  </Stack>
                  {ntfyTestMutation.isError && (
                    <Alert severity="error">{(ntfyTestMutation.error as Error).message ?? t("settings.mailTestError")}</Alert>
                  )}
                </Stack>
              )}
            </CardContent>
          </Card>

          <Stack direction="row" spacing={2} justifyContent="flex-end">
            <Button
              type="submit"
              variant="contained"
              disabled={isSubmitting || updateMutation.isPending}
            >
              {updateMutation.isPending ? t("actions.saving") : t("settings.save")}
            </Button>
          </Stack>
        </Stack>
      </Box>
    </>
  );
}
