import { Box, Text } from "ink";
import { Popup } from "../ui/Popup.js";
import { useFreeSize } from "../../hooks/size.js";
import { useDataResidentsByAbodeId } from "../../../react/hooks/data/residents.js";
import { AbodeName } from "../ui/AbodeName.js";
import { SearchPanel } from "../ui/SearchPanel.js";
import type { Resident } from "../../../db/types/Resident.js";
import { UserName } from "../ui/UserName.js";
import { ButtonList } from "../ui/Button.js";

function AbodeResidentComponent({
  item,
  selected,
}: {
  item: Resident;
  selected: boolean;
}) {
  return (
    <Box height={1} flexDirection="row" justifyContent="space-between">
      <Text underline={selected}>
        <UserName uid={item.uid} />
      </Text>
      {selected && (
        <ButtonList
          isFocused
          buttons={[
            {
              children: "Delete",
              onClick: () => {},
            },
            {
              children: "Delete",
              onClick: () => {},
            },
            {
              children: "Delete",
              onClick: () => {},
            },
          ]}
        />
      )}
    </Box>
  );
}

export function AbodeResidentsPopup({
  aid,
  onClose,
}: {
  aid: string;
  onClose: () => void;
}) {
  const { width, height } = useFreeSize();
  const { residents, status, refresh } = useDataResidentsByAbodeId(aid);

  return (
    <Popup onClose={onClose}>
      <Box flexDirection="column" minWidth={width / 3}>
        <Box justifyContent="center" flexDirection="row">
          <Text>
            Residents of{" "}
            <Text color="yellow" bold>
              <AbodeName aid={aid} />
            </Text>
          </Text>
          <Box height={1} />
        </Box>
        <SearchPanel
          sub
          status={status}
          items={residents}
          refresh={refresh}
          height={Math.min(height, Math.max(Math.floor(height / 2), 20))}
          ItemComponent={AbodeResidentComponent}
        />
      </Box>
    </Popup>
  );
}
