import AddIcon from "@mui/icons-material/Add";
import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import EditIcon from "@mui/icons-material/Edit";
import FemaleIcon from "@mui/icons-material/Female";
import MaleIcon from "@mui/icons-material/Male";
import VisibilityIcon from "@mui/icons-material/Visibility";
import { Button, TextField, Tooltip, Typography } from "@mui/material";
import { DataGrid, GridActionsCellItem, GridColDef } from "@mui/x-data-grid";
import React from "react";
import { useNavigate } from "react-router-dom";
import {
  Member,
  MemberApi,
  dateTimestamp,
  fmtDate,
} from "../../../api/genealogy/MemberApi";
import { useAlert } from "../../../hooks/context_providers/AlertDialogProvider";
import { useConfirm } from "../../../hooks/context_providers/ConfirmDialogProvider";
import { useSnackbar } from "../../../hooks/context_providers/SnackbarProvider";
import { useFamily } from "../../../widgets/BaseFamilyRoute";
import { FamilyPageTitle } from "../../../widgets/FamilyPageTitle";
import { MemberPhoto } from "../../../widgets/MemberPhoto";
import { RouterLink } from "../../../widgets/RouterLink";
import { useGenealogy } from "../../../widgets/genealogy/BaseGenealogyRoute";

export function FamilyMembersListRoute(): React.ReactElement {
  const alert = useAlert();
  const confirm = useConfirm();
  const snackbar = useSnackbar();

  const genealogy = useGenealogy();
  const family = useFamily();

  const [filter, setFilter] = React.useState("");

  const processDeletion = async (m: Member) => {
    try {
      if (
        !(await confirm(
          `Voulez-vous vraiment supprimer la fiche de ${m.fullName} ?`
        ))
      )
        return;

      await MemberApi.Delete(m);
      await genealogy.reloadMembersList();

      snackbar("La fiche du membre a été supprimée avec succès !");
    } catch (e) {
      console.error(e);
      alert("Echec de la suppression de la fiche ! ");
    }
  };

  return (
    <>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <FamilyPageTitle title="Membres de la famille" />
        <RouterLink to={family.family.URL("genealogy/member/create")}>
          <Tooltip title="Créer la fiche d'un nouveau membre">
            <Button startIcon={<AddIcon />}>Nouveau</Button>
          </Tooltip>
        </RouterLink>
      </div>

      {genealogy.members.isEmpty ? (
        <p>
          Votre famille n'a aucun membre pour le moment ! Utilisez le bouton
          situé en haut à droite pour créer le premier !
        </p>
      ) : (
        <>
          <TextField
            label={"Rechercher un membre..."}
            variant="standard"
            value={filter}
            onChange={(e) => setFilter(e.target.value)}
            style={{ maxWidth: "500px", margin: "10px" }}
          />

          <MembersTable
            members={
              filter === ""
                ? genealogy.members.fullList
                : genealogy.members.filter((m) =>
                    m.fullName.toLowerCase().includes(filter.toLowerCase())
                  )
            }
            onDelete={processDeletion}
          />
        </>
      )}
    </>
  );
}

function MembersTable(p: {
  members: Member[];
  onDelete: (m: Member) => void;
}): React.ReactElement {
  const genealogy = useGenealogy();
  const family = useFamily();
  const n = useNavigate();

  const columns: GridColDef<Member>[] = [
    {
      field: "signed_photo_id",
      headerName: "",
      disableColumnMenu: true,
      sortable: false,
      width: 60,
      renderCell(params) {
        return (
          <div
            style={{ display: "flex", alignItems: "center", height: "100%" }}
          >
            <MemberPhoto member={params.row} />
          </div>
        );
      },
    },

    {
      field: "last_name",
      headerName: "Nom",
      flex: 3,
    },
    {
      field: "first_name",
      headerName: "Prénom",
      flex: 3,
    },

    {
      field: "sex",
      headerName: "",
      disableColumnMenu: true,
      width: 20,
      renderCell(params) {
        if (params.row.sex === "F")
          return <FemaleIcon fontSize="small" htmlColor="pink" />;
        else return <MaleIcon fontSize="small" htmlColor="lightBlue" />;
      },
    },
    {
      field: "dateOfBirth",
      headerName: "Date de naissance",
      flex: 3,
      sortComparator(v1, v2) {
        const d1 = dateTimestamp(v1);
        const d2 = dateTimestamp(v2);
        return d1 - d2;
      },
      renderCell(params) {
        return fmtDate(params.row.dateOfBirth);
      },
    },
    {
      field: "dateOfDeath",
      headerName: "Date de décès",
      flex: 3,
      sortComparator(v1, v2) {
        const d1 = dateTimestamp(v1);
        const d2 = dateTimestamp(v2);
        return d1 - d2;
      },
      renderCell(params) {
        return fmtDate(params.row.dateOfDeath);
      },
    },
    {
      field: "father",
      headerName: "Père",
      flex: 5,
      renderCell(params) {
        if (!params.row.father)
          return (
            <Typography color="red" component="span" variant="body2">
              Non renseigné
            </Typography>
          );
        return genealogy.members.get(params.row.father)!.fullName;
      },
    },
    {
      field: "mother",
      headerName: "Mère",
      flex: 5,
      renderCell(params) {
        if (!params.row.mother)
          return (
            <Typography color="red" component="span" variant="body2">
              Non renseignée
            </Typography>
          );
        return genealogy.members.get(params.row.mother)!.fullName;
      },
    },
    {
      field: "actions",
      type: "actions",
      sortable: false,
      width: 120,
      disableColumnMenu: true,
      getActions(params) {
        return [
          <GridActionsCellItem
            icon={<VisibilityIcon />}
            label="Consulter le membre"
            className="textPrimary"
            onClick={() => n(family.family.memberURL(params.row))}
            color="inherit"
          />,
          <GridActionsCellItem
            icon={<EditIcon />}
            label="Modifier le membre"
            className="textPrimary"
            onClick={() => n(family.family.memberURL(params.row, true))}
            color="inherit"
          />,
          <GridActionsCellItem
            icon={<DeleteIcon />}
            label="Supprimer le membre"
            onClick={() => p.onDelete(params.row)}
            color="inherit"
          />,
        ];
      },
    },
  ];

  return (
    <DataGrid
      style={{ flex: "1" }}
      rows={p.members}
      columns={columns}
      autoPageSize
      getRowId={(c) => c.id}
      onRowDoubleClick={(p) => n(family.family.memberURL(p.row))}
    />
  );
}
