import { DataGrid, GridColDef } from "@mui/x-data-grid";
import React from "react";
import { FamilyApi, FamilyUser } from "../../api/FamilyApi";
import { useAlert } from "../../context_providers/AlertDialogProvider";
import { AsyncWidget } from "../../widgets/AsyncWidget";
import { useUser } from "../../widgets/BaseAuthenticatedPage";
import { useFamily } from "../../widgets/BaseFamilyRoute";
import { FamilyPageTitle } from "../../widgets/FamilyPageTitle";

export function FamilyUsersListRoute(): React.ReactElement {
  const family = useFamily();

  const [users, setUsers] = React.useState<FamilyUser[] | null>(null);

  const key = React.useRef(1);

  const load = async () => {
    setUsers(await FamilyApi.GetUsersList(family.family.family_id));
  };

  return (
    <AsyncWidget
      loadKey={`${family.family.family_id}-${key.current}`}
      errMsg="Echec du chargement de la liste des utilisateurs de la famille !"
      load={load}
      ready={users !== null}
      build={() => (
        <>
          <FamilyPageTitle title="Utilisateurs de la famille" />
          <UsersTable users={users!} />
        </>
      )}
    />
  );
}

function UsersTable(p: { users: FamilyUser[] }): React.ReactElement {
  const alert = useAlert();
  const user = useUser();
  const family = useFamily();

  const columns: GridColDef[] = [
    { field: "user_id", headerName: "#", flex: 1 },
    { field: "user_mail", headerName: "Adresse mail", flex: 5 },
    { field: "user_name", headerName: "Nom d'utilisateur", flex: 5 },
    {
      field: "is_admin",
      headerName: "Admin",
      flex: 2,
      type: "boolean",
      editable: family.family.is_admin,
    },
  ];

  return (
    <DataGrid
      style={{ flex: "1" }}
      rows={p.users}
      columns={columns}
      autoPageSize
      editMode="cell"
      getRowId={(c) => c.user_id}
      isCellEditable={(params) => params.row.user_id !== user.user.id}
      processRowUpdate={async (n: FamilyUser) => {
        await FamilyApi.UpdateUser(n);
        return n;
      }}
      onProcessRowUpdateError={(e) => {
        console.error(e);
        alert.alert("Échec de la mise à jour des informations utilisateurs !");
      }}
    />
  );
}
