import ClearIcon from "@mui/icons-material/Clear";
import SaveIcon from "@mui/icons-material/Save";
import { Button, Grid, Stack } from "@mui/material";
import React from "react";
import { useNavigate } from "react-router-dom";
import { Member, MemberApi } from "../../api/MemberApi";
import { ServerApi } from "../../api/ServerApi";
import { useAlert } from "../../context_providers/AlertDialogProvider";
import { useConfirm } from "../../context_providers/ConfirmDialogProvider";
import { useFamily } from "../../widgets/BaseFamilyRoute";
import { FamilyPageTitle } from "../../widgets/FamilyPageTitle";
import { PropEdit } from "../../widgets/PropEdit";
import { PropertiesBox } from "../../widgets/PropertiesBox";
import { SexSelection } from "../../widgets/SexSelection";

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

  const n = useNavigate();
  const family = useFamily();

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

      // TODO : trigger update

      n(family.family.URL(`member/${r.id}`));
    } catch (e) {
      console.error(e);
      alert("Echec de la création de la personne !");
    }
  };

  return (
    <MemberPage
      member={Member.New(family.family.family_id)}
      creating={true}
      editing={true}
      onCancel={() => n(family.family.URL("members"))}
      onSave={create}
    />
  );
}

/**
 * Edit existing member route
 */
export function FamilyMemberRoute(): React.ReactElement {
  return <p>TODO</p>;
}

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

  // TODO : add confirmation when leaving page https://dev.to/bangash1996/detecting-user-leaving-page-with-react-router-dom-v602-33ni
  const [changed, setChanged] = React.useState(false);
  const [member, setMember] = React.useState(structuredClone(p.member));

  const updatedMember = () => {
    // TODO : add confirmation
    setChanged(true);
    setMember(structuredClone(member));
  };

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

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

    p.onCancel();
  };

  return (
    <div style={{ maxWidth: "2000px", margin: "auto" }}>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <FamilyPageTitle
          title={
            (p.creating ? "Création" : "Édition") + " d'une fiche de membre"
          }
        />
        <Stack direction="row" spacing={1}>
          {/* Save button */}
          {p.editing && (
            <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}>
        <Grid item sm={12} md={6}>
          <PropertiesBox title="Informations générales">
            {/* Sex */}
            <SexSelection
              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}
            />
            <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}
            />
          </PropertiesBox>
        </Grid>
        <Grid item sm={12} md={6}>
          <PropertiesBox title="Contact"></PropertiesBox>
        </Grid>
        <Grid item sm={12} md={6}>
          <PropertiesBox title="Photo"></PropertiesBox>
        </Grid>
        <Grid item sm={12} md={6}>
          <PropertiesBox title="Biographie"></PropertiesBox>
        </Grid>
        <Grid item sm={12} md={6}>
          <PropertiesBox title="Époux / Épouse">TODO</PropertiesBox>
        </Grid>
        <Grid item sm={12} md={6}>
          <PropertiesBox title="Enfants">TODO</PropertiesBox>
        </Grid>
      </Grid>
    </div>
  );
}
