import AddIcon from "@mui/icons-material/Add";
import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import EditIcon from "@mui/icons-material/Edit";
import VisibilityIcon from "@mui/icons-material/Visibility";
import { Button, TextField, Tooltip } from "@mui/material";
import { DataGrid, GridActionsCellItem, GridColDef } from "@mui/x-data-grid";
import React from "react";
import { useNavigate } from "react-router-dom";
import { Couple, CoupleApi } from "../../../api/genealogy/CoupleApi";
import { dateTimestamp, fmtDate } from "../../../api/genealogy/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 { useFamily } from "../../../widgets/BaseFamilyRoute";
import { CouplePhoto } from "../../../widgets/CouplePhoto";
import { FamilyPageTitle } from "../../../widgets/FamilyPageTitle";
import { MemberPhoto } from "../../../widgets/MemberPhoto";
import { RouterLink } from "../../../widgets/RouterLink";
import { useGenealogy } from "../../../widgets/genealogy/BaseGenealogyRoute";

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

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

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

  const processDeletion = async (c: Couple) => {
    try {
      if (
        !(await confirm(
          `Voulez-vous vraiment supprimer cette fiche de couple ?`
        ))
      )
        return;

      await CoupleApi.Delete(c);
      await genealogy.reloadCouplesList();

      snackbar("La fiche du couple 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="Couples de la famille" />
        <RouterLink to={family.family.URL("couple/create")}>
          <Tooltip title="Créer la fiche d'un nouveau couple">
            <Button startIcon={<AddIcon />}>Nouveau</Button>
          </Tooltip>
        </RouterLink>
      </div>

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

          <CouplesTable
            couples={
              filter === ""
                ? genealogy.couples.fullList
                : genealogy.couples.filter(
                    (m) =>
                      (m.wife &&
                        genealogy.members
                          .get(m.wife)!
                          .fullName.toLocaleLowerCase()
                          .includes(filter.toLocaleLowerCase())) ||
                      (m.husband &&
                        genealogy.members
                          .get(m.husband)!
                          .fullName.toLocaleLowerCase()
                          .includes(filter.toLocaleLowerCase())) === true
                  )
            }
            onDelete={processDeletion}
          />
        </>
      )}
    </>
  );
}

function CouplesTable(p: {
  couples: Couple[];
  onDelete: (m: Couple) => void;
}): React.ReactElement {
  const family = useFamily();
  const genealogy = useGenealogy();

  const n = useNavigate();

  const compareInvertedMembersNames = (
    v1: number | undefined,
    v2: number | undefined
  ) => {
    const n1 =
      ((v1 && genealogy.members.get(v1)?.invertedFullName) ?? "") || "";
    const n2 =
      ((v2 && genealogy.members.get(v2)?.invertedFullName) ?? "") || "";

    return n1?.localeCompare(n2, undefined, {
      ignorePunctuation: true,
      sensitivity: "base",
    });
  };

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

    {
      field: "husband",
      headerName: "Époux",
      flex: 5,
      sortComparator: compareInvertedMembersNames,
      renderCell(params) {
        return <MemberCell id={params.row.husband} />;
      },
    },

    {
      field: "wife",
      headerName: "Épouse",
      flex: 5,
      sortComparator: compareInvertedMembersNames,
      renderCell(params) {
        return <MemberCell id={params.row.wife} />;
      },
    },

    {
      field: "state",
      headerName: "État",
      flex: 3,
      renderCell(params) {
        return ServerApi.Config.couples_states.find(
          (c) => c.code === params.row.state
        )?.fr;
      },
    },
    {
      field: "dateOfWedding",
      headerName: "Date de mariage",
      flex: 3,
      sortComparator(v1, v2) {
        const d1 = dateTimestamp(v1);
        const d2 = dateTimestamp(v2);
        return d1 - d2;
      },
      renderCell(params) {
        return fmtDate(params.row.dateOfWedding);
      },
    },
    {
      field: "dateOfDivorce",
      headerName: "Date de divorce",
      flex: 3,
      sortComparator(v1, v2) {
        const d1 = dateTimestamp(v1);
        const d2 = dateTimestamp(v2);
        return d1 - d2;
      },
      renderCell(params) {
        return fmtDate(params.row.dateOfDivorce);
      },
    },
    {
      field: "actions",
      type: "actions",
      sortable: false,
      width: 120,
      disableColumnMenu: true,
      getActions(params) {
        return [
          <GridActionsCellItem
            icon={<VisibilityIcon />}
            label="Consulter la fiche du couple"
            className="textPrimary"
            onClick={() => n(family.family.coupleURL(params.row))}
            color="inherit"
          />,
          <GridActionsCellItem
            icon={<EditIcon />}
            label="Modifier la fiche du couple"
            className="textPrimary"
            onClick={() => n(family.family.coupleURL(params.row, true))}
            color="inherit"
          />,
          <GridActionsCellItem
            icon={<DeleteIcon />}
            label="Supprimer la fiche du couple"
            onClick={() => p.onDelete(params.row)}
            color="inherit"
          />,
        ];
      },
    },
  ];

  // If couple photos are hidden, remove their column
  if (family.family.disable_couple_photos) columns.splice(0, 1);

  return (
    <DataGrid
      style={{ flex: "1" }}
      rows={p.couples}
      columns={columns}
      autoPageSize
      getRowId={(c) => c.id}
      onCellDoubleClick={(p) => {
        /*let member;
        if (p.field === "wife") member = family.members.get(p.row.wife);
        else if (p.field === "husband")
          member = family.members.get(p.row.husband);

        if (member) {
          n(family.family.memberURL(member));
          return;
        }*/

        n(family.family.coupleURL(p.row));
      }}
    />
  );
}

function MemberCell(p: { id?: number }): React.ReactElement {
  const genealogy = useGenealogy();
  if (!p.id) return <></>;

  const member = genealogy.members.get(p.id!)!;

  return (
    <Tooltip title="Double-cliquez ici pour accéder à la fiche du membre">
      <div style={{ display: "flex", alignItems: "center" }}>
        <MemberPhoto member={member} width={25} /> &nbsp; {member.fullName}
      </div>
    </Tooltip>
  );
}
