import {
  Box,
  Button,
  CardActions,
  CardContent,
  FormControlLabel,
  Switch,
  TextField,
  Typography,
} from "@mui/material";
import React from "react";
import { useNavigate } from "react-router-dom";
import { FamilyApi } from "../../api/FamilyApi";
import { ServerApi } from "../../api/ServerApi";
import { useAlert } from "../../hooks/context_providers/AlertDialogProvider";
import { useConfirm } from "../../hooks/context_providers/ConfirmDialogProvider";
import { useFamily } from "../../widgets/BaseFamilyRoute";
import { FamilyCard } from "../../widgets/FamilyCard";
import { formatDate } from "../../widgets/TimeWidget";

export function FamilySettingsRoute(): React.ReactElement {
  const alert = useAlert();
  const confirm = useConfirm();
  const navigate = useNavigate();

  const family = useFamily();

  const deleteFamily = async () => {
    try {
      if (
        !(await confirm(
          "Voulez-vous vraiment supprimer cette famille, et toute les données qui s'y rattachent ? Cette opération est absolument irréversible !"
        ))
      )
        return;

      await FamilyApi.DeleteFamily(family.family);

      await alert("La famille a été supprimée avec succès !");

      navigate("/");
    } catch (e) {
      console.error(e);
      alert("Echec de la suppression de la famille !");
    }
  };

  return (
    <>
      <FamilySettingsCard />
      <div style={{ textAlign: "center", marginTop: "50px" }}>
        <Button
          size="small"
          color="error"
          onClick={deleteFamily}
          disabled={!family.family.is_admin}
        >
          Supprimer la famille
        </Button>
      </div>
    </>
  );
}

function FamilySettingsCard(): React.ReactElement {
  const alert = useAlert();

  const family = useFamily();

  const [newName, setNewName] = React.useState(family.family.name);
  const [enableGenealogy, setEnableGenealogy] = React.useState(
    family.family.enable_genealogy
  );
  const [enableAccommodations, setEnableAccommodations] = React.useState(
    family.family.enable_accommodations
  );

  const canEdit = family.family.is_admin;

  const [error, setError] = React.useState<string>();
  const [success, setSuccess] = React.useState<string>();

  const updateFamily = async () => {
    try {
      setError(undefined);
      setSuccess(undefined);

      await FamilyApi.UpdateFamily({
        id: family.family.family_id,
        name: newName,
        enable_genealogy: enableGenealogy,
        enable_accommodations: enableAccommodations,
      });

      family.reloadFamilyInfo();

      alert("Les paramètres de la famille ont été mis à jour avec succès !");
    } catch (e) {
      console.error(e);
      setError("Echec de la mise à jour des paramètres de la famille !");
    }
  };

  return (
    <FamilyCard error={error} success={success}>
      <CardContent>
        <Typography gutterBottom variant="h5" component="div">
          Paramètres de la famille
        </Typography>

        <Box
          component="form"
          sx={{
            "& .MuiTextField-root": { my: 1 },
          }}
          noValidate
          autoComplete="off"
        >
          <TextField
            disabled
            fullWidth
            label="Identifiant"
            value={family.family.family_id}
          />
          <TextField
            disabled
            fullWidth
            label="Création de la famille"
            value={formatDate(family.family.time_create)}
          />
          <TextField
            fullWidth
            label="Nom de la famille"
            value={newName}
            disabled={!canEdit}
            onChange={(e) => setNewName(e.target.value)}
            inputProps={{
              maxLength: ServerApi.Config.constraints.family_name_len.max,
            }}
          />
          <FormControlLabel
            disabled={!canEdit}
            control={
              <Switch
                checked={enableGenealogy}
                onChange={(_e, c) => setEnableGenealogy(c)}
              />
            }
            label="Activer le module de généalogie"
          />
          <FormControlLabel
            disabled={!canEdit}
            control={
              <Switch
                checked={enableAccommodations}
                onChange={(_e, c) => setEnableAccommodations(c)}
              />
            }
            label="Activer le module de réservation de logements"
          />
        </Box>
      </CardContent>
      <CardActions>
        <Button
          onClick={updateFamily}
          disabled={!canEdit}
          style={{ marginLeft: "auto" }}
        >
          Enregistrer
        </Button>
      </CardActions>
    </FamilyCard>
  );
}
