import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
import { Pill } from "../..";
import { Grid } from "@mui/material";
import { EntityTagsProps, SubEntityTagsRef } from "./types";

const SubEntityTags = forwardRef<SubEntityTagsRef, EntityTagsProps>(({
  subEntityTagsList,
  selectedSubEntity,
  setSelectedSubEntity,
  defaultSelectedSubEntityId,
  onSubEntityChange
}: EntityTagsProps, ref) => {

  const calculateGridSize = () => {
    const itemCount = subEntityTagsList?.length;
    if (itemCount == 0) return 12;
    return 12 / itemCount;
  };

  const lastAppliedDefaultIdRef = useRef<number | string | undefined>(undefined);

  useEffect(() => {
    if (defaultSelectedSubEntityId == null) return;
    if (lastAppliedDefaultIdRef.current === defaultSelectedSubEntityId) return;
    const found = subEntityTagsList?.find((s) => s?.id === defaultSelectedSubEntityId);
    if (found && setSelectedSubEntity) {
      setSelectedSubEntity(found);
      lastAppliedDefaultIdRef.current = defaultSelectedSubEntityId;
      onSubEntityChange?.(found);
    }
  }, [defaultSelectedSubEntityId, subEntityTagsList, setSelectedSubEntity, onSubEntityChange]);

  useImperativeHandle(ref, () => ({
    selectSubEntityById: (id: number | string) => {
      if (selectedSubEntity?.id === id) return;
      const found = subEntityTagsList?.find((s) => s?.id === id);
      if (found && setSelectedSubEntity) {
        setSelectedSubEntity(found);
        onSubEntityChange?.(found);
      }
    }
  }));

  return (
    <Grid container spacing={1}>
      {subEntityTagsList?.length > 0 && subEntityTagsList?.map((subEntity, index) => {
        const isSelected = selectedSubEntity?.id === subEntity?.id;
        return (
          <Grid item xs={calculateGridSize()} key={index}>
            <Pill
              item={{ ...subEntity, color: isSelected ? "#005bf8" : "gray" }}
              variant={isSelected ? "filled" : "outlined"}
              size="full"
              onClick={() => {
                if (selectedSubEntity?.id !== subEntity?.id) {
                  setSelectedSubEntity?.(subEntity);
                  onSubEntityChange?.(subEntity);
                }
              }}
            />
          </Grid>
        );
      })}
    </Grid>
  );
});

export default SubEntityTags;
