import ClearIcon from "@mui/icons-material/Clear";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import SaveIcon from "@mui/icons-material/Save";
import { Button, Grid, Stack } from "@mui/material";
import React from "react";
import FileDownloadIcon from "@mui/icons-material/FileDownload";
import { useNavigate, useParams } from "react-router-dom";
import { Member, MemberApi } from "../../api/MemberApi";
import { ServerApi } from "../../api/ServerApi";
import { useAlert } from "../../hooks/context_providers/AlertDialogProvider";
import { useConfirm } from "../../hooks/context_providers/ConfirmDialogProvider";
import { useSnackbar } from "../../hooks/context_providers/SnackbarProvider";
import { AsyncWidget } from "../../widgets/AsyncWidget";
import { useFamily } from "../../widgets/BaseFamilyRoute";
import { ConfirmLeaveWithoutSaveDialog } from "../../widgets/ConfirmLeaveWithoutSaveDialog";
import { FamilyPageTitle } from "../../widgets/FamilyPageTitle";
import { PropertiesBox } from "../../widgets/PropertiesBox";
import { DateInput } from "../../widgets/forms/DateInput";
import { PropCheckbox } from "../../widgets/forms/PropCheckbox";
import { PropEdit } from "../../widgets/forms/PropEdit";
import { SexSelection } from "../../widgets/forms/SexSelection";
import { UploadPhotoButton } from "../../widgets/forms/UploadPhotoButton";
import { MemberPhoto } from "../../widgets/MemberPhoto";
import { RouterLink } from "../../widgets/RouterLink";

/**
 * Create a new member route
 */
export function FamilyCreateMemberRoute(): React.ReactElement {
  const alert = useAlert();
  const snackbar = useSnackbar();

  const [shouldQuit, setShouldQuit] = React.useState(false);
  const n = useNavigate();
  const family = useFamily();

  const create = async (m: Member) => {
    try {
      const r = await MemberApi.Create(m);

      await family.reloadMembersList();

      setShouldQuit(true);
      n(family.family.URL(`member/${r.id}`));
      snackbar(`La fiche pour ${r.fullName} a été créée avec succès !`);
    } catch (e) {
      console.error(e);
      alert("Echec de la création de la personne !");
    }
  };

  const cancel = () => {
    setShouldQuit(true);
    n(family.family.URL("members"));
  };

  return (
    <MemberPage
      member={Member.New(family.family.family_id)}
      creating={true}
      editing={true}
      onCancel={cancel}
      onSave={create}
      shouldAllowLeaving={shouldQuit}
    />
  );
}

/**
 * Get existing member route
 */
export function FamilyMemberRoute(): React.ReactElement {
  const count = React.useRef(1);

  const n = useNavigate();
  const alert = useAlert();
  const confirm = useConfirm();
  const snackbar = useSnackbar();

  const family = useFamily();
  const { memberId } = useParams();

  const [member, setMember] = React.useState<Member>();
  const load = async () => {
    setMember(await MemberApi.GetSingle(family.familyId, Number(memberId)));
  };

  const forceReload = async () => {
    count.current += 1;
    setMember(undefined);

    await family.reloadMembersList();
  };

  const deleteMember = async () => {
    try {
      if (
        !(await confirm(
          "Voulez-vous vraiment supprimer cette fiche membre ? L'opération n'est pas réversible !"
        ))
      )
        return;

      await MemberApi.Delete(member!);

      snackbar("La fiche de membre a été supprimée avec succès !");
      n(family.family.URL("members"));

      await family.reloadMembersList();
    } catch (e) {
      console.error(e);
      alert("Échec de la suppression du membre !");
    }
  };

  return (
    <AsyncWidget
      loadKey={`${memberId}-${count.current}`}
      load={load}
      ready={member !== undefined}
      errMsg="Echec du chargement des informations du membre"
      build={() => (
        <MemberPage
          member={member!}
          creating={false}
          editing={false}
          onRequestDelete={deleteMember}
          onRequestEdit={() =>
            n(family.family.URL(`member/${member!.id}/edit`))
          }
          onForceReload={forceReload}
        />
      )}
    />
  );
}

/**
 * Edit existing member route
 */
export function FamilyEditMemberRoute(): React.ReactElement {
  const n = useNavigate();
  const alert = useAlert();
  const snackbar = useSnackbar();

  const [shouldQuit, setShouldQuit] = React.useState(false);

  const family = useFamily();
  const { memberId } = useParams();

  const [member, setMember] = React.useState<Member>();
  const load = async () => {
    setMember(await MemberApi.GetSingle(family.familyId, Number(memberId)));
  };

  const cancel = () => {
    setShouldQuit(true);
    n(family.family.URL(`member/${member!.id}`));
  };

  const save = async (m: Member) => {
    try {
      await MemberApi.Update(m);

      snackbar("Les informations du membre ont été mises à jour avec succès !");

      await family.reloadMembersList();

      setShouldQuit(true);
      n(family.family.URL(`member/${member!.id}`));
    } catch (e) {
      console.error(e);
      alert("Échec de la mise à jour des informations du membre !");
    }
  };

  return (
    <AsyncWidget
      loadKey={memberId}
      load={load}
      errMsg="Échec du chargement des informations du membre"
      build={() => (
        <MemberPage
          member={member!}
          creating={false}
          editing={true}
          onCancel={cancel}
          onSave={save}
          shouldAllowLeaving={shouldQuit}
        />
      )}
    />
  );
}

export function MemberPage(p: {
  member: Member;
  editing: boolean;
  creating: boolean;
  shouldAllowLeaving?: boolean;
  onCancel?: () => void;
  onSave?: (m: Member) => void;
  onRequestEdit?: () => void;
  onRequestDelete?: () => void;
  onForceReload?: () => void;
}): React.ReactElement {
  const confirm = useConfirm();
  const snackbar = useSnackbar();

  const [changed, setChanged] = React.useState(false);
  const [member, setMember] = React.useState(
    new Member(structuredClone(p.member))
  );

  const updatedMember = () => {
    setChanged(true);
    setMember(new Member(structuredClone(member)));
  };

  const save = () => {
    p.onSave!(member);
  };

  const cancel = async () => {
    if (
      changed &&
      !(await confirm(
        "Voulez-vous vraiment retirer les modifications apportées ? Celles-ci seront perdues !"
      ))
    )
      return;

    p.onCancel!();
  };

  const uploadNewPhoto = async (b: Blob) => {
    await MemberApi.SetMemberPhoto(member, b);
    snackbar("La photo du membre a été mise à jour avec succès !");
    p.onForceReload?.();
  };

  const deletePhoto = async () => {
    try {
      if (!(await confirm("Voulez-vous supprimer cette photo ?"))) return;

      await MemberApi.RemoveMemberPhoto(member);

      snackbar("La photo du membre a été supprimée avec succès !");
      p.onForceReload?.();
    } catch (e) {
      console.error(e);
      alert("Échec de la suppresion de la photo !");
    }
  };

  return (
    <div style={{ maxWidth: "2000px", margin: "auto" }}>
      <ConfirmLeaveWithoutSaveDialog
        shouldBlock={changed && p.shouldAllowLeaving !== true}
      />
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <FamilyPageTitle
          title={
            (p.editing
              ? p.creating
                ? "Création"
                : "Édition"
              : "Visualisation") + " d'une fiche de membre"
          }
        />
        <Stack direction="row" spacing={1}>
          {/* Edit button */}
          {p.onRequestEdit && (
            <Button
              variant="outlined"
              startIcon={<EditIcon />}
              onClick={p.onRequestEdit}
              size="large"
            >
              Editer
            </Button>
          )}

          {/* Delete button */}
          {p.onRequestDelete && (
            <Button
              variant="outlined"
              startIcon={<DeleteIcon />}
              onClick={p.onRequestDelete}
              size="large"
              color="error"
            >
              Supprimer
            </Button>
          )}

          {/* Save button */}
          {p.editing && changed && (
            <Button
              variant={"contained"}
              startIcon={<SaveIcon />}
              onClick={save}
              size="large"
            >
              Enregistrer
            </Button>
          )}

          {/* Cancel button */}
          {p.editing && (
            <Button
              variant="outlined"
              startIcon={<ClearIcon />}
              onClick={cancel}
              size="small"
            >
              Annuler les modifications
            </Button>
          )}
        </Stack>
      </div>

      <Grid container spacing={2}>
        {/* General info */}
        <Grid item sm={12} md={6}>
          <PropertiesBox title="Informations générales">
            {/* Sex */}
            <SexSelection
              readonly={!p.editing}
              current={member.sex}
              onChange={(v) => {
                member.sex = v;
                updatedMember();
              }}
            />

            {/* First name */}
            <PropEdit
              label="Prénom"
              editable={p.editing}
              value={member.first_name}
              onValueChange={(v) => {
                member.first_name = v;
                updatedMember();
              }}
              size={ServerApi.Config.constraints.member_first_name}
            />

            {/* Last name */}
            <PropEdit
              label="Nom"
              editable={p.editing}
              value={member.last_name}
              onValueChange={(v) => {
                member.last_name = v;
                updatedMember();
              }}
              size={ServerApi.Config.constraints.member_last_name}
            />

            {/* Birth last name */}
            <PropEdit
              label="Nom de naissance"
              editable={p.editing}
              value={member.birth_last_name}
              onValueChange={(v) => {
                member.birth_last_name = v;
                updatedMember();
              }}
              size={ServerApi.Config.constraints.member_birth_last_name}
            />

            {/* Birth day */}
            <DateInput
              label="Date de naissance"
              editable={p.editing}
              id="dob"
              value={{
                year: member.birth_year,
                month: member.birth_month,
                day: member.birth_day,
              }}
              onValueChange={(d) => {
                member.birth_year = d.year;
                member.birth_month = d.month;
                member.birth_day = d.day;
                updatedMember();
              }}
            />

            {/* Is dead */}
            <PropCheckbox
              checked={member.dead}
              editable={p.editing}
              label="Décédé"
              onValueChange={(v) => {
                member.dead = v;
                updatedMember();
              }}
            />

            {/* Death day */}
            <DateInput
              label="Date de décès"
              editable={p.editing}
              id="dod"
              value={{
                year: member.death_year,
                month: member.death_month,
                day: member.death_day,
              }}
              onValueChange={(d) => {
                member.death_year = d.year;
                member.death_month = d.month;
                member.death_day = d.day;
                updatedMember();
              }}
            />
          </PropertiesBox>
        </Grid>

        {/* Photo */}
        <Grid item sm={12} md={6}>
          <PropertiesBox title="Photo">
            <div style={{ textAlign: "center" }}>
              <MemberPhoto member={member} width={150} />
              <br />
              {p.editing ? (
                <p>
                  Veuillez enregistrer / annuler les modifications apportées à
                  la fiche avant de changer la photo du membre.
                </p>
              ) : (
                <>
                  <UploadPhotoButton
                    label={member.hasPhoto ? "Remplacer" : "Ajouter"}
                    onPhotoSelected={uploadNewPhoto}
                  />{" "}
                  {member.hasPhoto && (
                    <RouterLink to={member.photoURL} target="_blank">
                      <Button
                        variant="outlined"
                        startIcon={<FileDownloadIcon />}
                      >
                        Télécharger
                      </Button>
                    </RouterLink>
                  )}{" "}
                  {member.hasPhoto && (
                    <Button
                      variant="outlined"
                      startIcon={<DeleteIcon />}
                      color="error"
                      onClick={deletePhoto}
                    >
                      Supprimer
                    </Button>
                  )}
                </>
              )}{" "}
            </div>
          </PropertiesBox>
        </Grid>

        {/* Contact */}
        <Grid item sm={12} md={6}>
          <PropertiesBox title="Contact">TODO</PropertiesBox>
        </Grid>

        {/* Bio */}
        <Grid item sm={12} md={6}>
          <PropertiesBox title="Biographie">TODO</PropertiesBox>
        </Grid>

        {/* Spouse */}
        <Grid item sm={12} md={6}>
          <PropertiesBox title={member.sex === "F" ? "Époux" : "Épouse"}>
            TODO
          </PropertiesBox>
        </Grid>

        {/* Children */}
        <Grid item sm={12} md={6}>
          <PropertiesBox title="Enfants">TODO</PropertiesBox>
        </Grid>
      </Grid>
    </div>
  );
}
