import React, { useRef } from "react";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { User, UserApi } from "../api/UserApi";
import {
  Alert,
  Box,
  Button,
  Card,
  CardActions,
  CardContent,
  Checkbox,
  FormControlLabel,
  TextField,
  Typography,
} from "@mui/material";
import { TimeWidget, formatDate } from "../widgets/TimeWidget";
import { ServerApi } from "../api/ServerApi";

export function ProfileRoute(): React.ReactElement {
  const [user, setUser] = React.useState<null | User>(null);
  const [newName, setNewName] = React.useState("");

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

  const load = async () => {
    const u = await UserApi.GetUserInfo();
    setUser(u);
    setNewName(u.name);
  };

  const counter = useRef(0);

  const updateProfile = async () => {
    try {
      setSuccess(null);
      setError(null);

      await UserApi.UpdateProfile(newName);

      counter.current += 1;
      setSuccess("Informations du profil mises à jour avec succès !");
    } catch (e) {
      console.error(e);
      setError("Echec de la mise à jour du profil !");
    }
  };

  return (
    <AsyncWidget
      loadKey={counter.current}
      load={load}
      errMsg="Echec du chargement des informations du compte utilisateur !"
      build={() => (
        <div style={{ maxWidth: "500px", margin: "auto" }}>
          <Typography variant="h3">Profil</Typography>

          {error && <Alert severity="error">{error}</Alert>}
          {success && <Alert severity="success">{success}</Alert>}

          <Card style={{ marginTop: "10px" }}>
            <CardContent>
              <Typography gutterBottom variant="h5" component="div">
                Paramètres du compte
              </Typography>

              <Box
                component="form"
                sx={{
                  "& .MuiTextField-root": { m: 1 },
                }}
                noValidate
                autoComplete="off"
              >
                <TextField
                  disabled
                  fullWidth
                  label="Identifiant"
                  value={user?.id}
                />

                <TextField
                  disabled
                  fullWidth
                  label="Création du compte"
                  value={formatDate(user!.time_create)}
                />

                <TextField
                  disabled
                  fullWidth
                  label="Activation du compte"
                  value={formatDate(user!.time_activate)}
                />

                <TextField
                  disabled
                  fullWidth
                  label="Adresse mail"
                  value={user?.email}
                />

                <TextField
                  fullWidth
                  label="Nom d'utilisateur"
                  value={newName}
                  onChange={(e) => setNewName(e.target.value)}
                  inputProps={{
                    maxLength: ServerApi.Config.constraints.user_name_len.max,
                  }}
                />

                <FormControlLabel
                  disabled
                  control={<Checkbox checked={user!.admin} />}
                  label="Compte administrateur"
                />
              </Box>
            </CardContent>
            <CardActions>
              <Button onClick={updateProfile} style={{ marginLeft: "auto" }}>
                Enregistrer
              </Button>
            </CardActions>
          </Card>
        </div>
      )}
    />
  );
}
