import ClearIcon from "@mui/icons-material/Clear";
import { Autocomplete, IconButton, TextField, Typography } from "@mui/material";
import React from "react";
import { useNavigate } from "react-router-dom";
import { Member } from "../../api/genealogy/MemberApi";
import { useFamily } from "../BaseFamilyRoute";
import { MemberItem } from "../MemberItem";
import { useGenealogy } from "../genealogy/BaseGenealogyRoute";

export function MemberInput(p: {
  editable: boolean;
  current?: number;
  onValueChange: (n?: number) => void;
  label: string;
  filter: (m: Member) => boolean;
}): React.ReactElement {
  const n = useNavigate();
  const family = useFamily();
  const genealogy = useGenealogy();

  const choices = genealogy.members.filter(p.filter);

  const [inputValue, setInputValue] = React.useState("");

  if (p.current) {
    const member = genealogy.members.get(p.current)!;
    return (
      <div style={{ display: "flex", alignItems: "center" }}>
        <Typography variant="body2">{p.label}</Typography>
        <MemberItem
          member={member}
          onClick={
            !p.editable
              ? () => {
                  n(family.family.memberURL(member));
                }
              : undefined
          }
          secondary={
            p.editable ? (
              <>
                <IconButton
                  edge="end"
                  onClick={() => p.onValueChange(undefined)}
                >
                  <ClearIcon />
                </IconButton>
              </>
            ) : undefined
          }
        />
      </div>
    );
  }

  if (!p.editable) return <></>;

  return (
    <Autocomplete
      value={p.current ? genealogy.members.get(p.current) : undefined}
      onChange={(_event: any, newValue: Member | null | undefined) => {
        p.onValueChange(newValue?.id);
      }}
      inputValue={inputValue}
      onInputChange={(_event, newInputValue) => {
        setInputValue(newInputValue);
      }}
      options={choices}
      sx={{ width: "100%" }}
      filterOptions={(options, state) => {
        const res = options.filter((m) =>
          m?.fullName.toLowerCase().includes(state.inputValue)
        );
        res.length = Math.min(20, res.length);
        return res;
      }}
      getOptionLabel={(o) => o?.fullName ?? ""}
      renderInput={(params) => <TextField {...params} label={p.label} />}
      renderOption={(_props, option, _state) => (
        <MemberItem
          member={option}
          onClick={() => p.onValueChange(option?.id)}
        />
      )}
    />
  );
}
