import React, { useRef } from 'react'
import { Box, Grid, Icon, Typography } from '@mui/material';
import { UNASSIGNED_DRIVER, useTags } from '../useTags';
import { EntityType } from '../types';
import { Icons } from '../../Icons';
import { Checkbox } from '../../Checkbox';
import { Tooltip } from '../..';
import { useLocale } from '../../../hooks/useLocale';

const List = ({ 
  entity,
  value,
  disableUntaggedSelection,
  disableTagSelection,
  multiple,
  onChange,
  tags,
  units,
  drivers,
  landmarks,
  geofences,
  forms,
  subusers,
  hideTagsWithoutEntities,
  messages,
  height,
  includeUnassignedDrivers,
  onlyTags = false,
  showCount = false,
  inheritance = false,
  enableSelectAll = false,
  showOnlyEntity = false,
  onlyCheckEntities = false,
  assets,
  searchText = ''
 }: any) => {

  const {
    expanded,
    getParentsTags,
    onExpand,
    defineMarginLeft,
    handleCheckboxChange,
    isItemDisabled,
    isItemChecked,
    isItemIndeterminate,
    isAllSelected,
    handleSelectAllChange,
    getEntities,
    getEntityList
  } = useTags({
    entity,
    value,
    disableUntaggedSelection,
    disableTagSelection,
    multiple,
    onChange,
    tags,
    units,
    drivers,
    landmarks,
    geofences,
    forms,
    subusers,
    assets,
    hideTagsWithoutEntities,
    onlyTags,
    inheritance,
    enableSelectAll
  });
  
  const instanceIdRef = useRef<string>(`list-${Math.random().toString(36).substr(2, 9)}-${Date.now()}`);
  const entities = getEntities();

  const renderTagItem = (item: any, depth: number = 0) => {
    let hasChildren = false
    if (item.hasChildren) {
      hasChildren = true
    }
    if (item.entitiesCount > 0 && onlyTags === false) {
      hasChildren = true
    }
    const isTag = item.name === EntityType.Tag;
    const marginLeft = defineMarginLeft(depth, isTag, hasChildren);
    const disabled = isItemDisabled(item);
    const isChecked = isItemChecked(item);
    const isIndeterminate = isItemIndeterminate(item);


    return (
      <Box key={item.id}>
        <Box
          display="flex"
          alignItems="center"
          mt={1}
          style={{ marginLeft }}
        >
          {hasChildren && isTag && (
            <Icons
              name={expanded[item.id as keyof typeof expanded] ? "arrow_drop_down" : "arrow_right"}
              onClick={() => onExpand(item.id as number, item.disabled)}
              style={{ fontSize: 30, margin: "0px", cursor: "pointer" }}
            />
          )}
          <Grid item>
            {
              (!onlyCheckEntities || (onlyCheckEntities && !isTag)) && (
                <Checkbox
                  checked={isChecked}
                  value={isChecked ? 'true' : 'false'}
                  isDisabled={disabled}
                  id={`${instanceIdRef.current}-${item.id}`}
                  onChange={() => handleCheckboxChange(item)}
                  isIndeterminate={isIndeterminate}
                />
              )
            }
          </Grid>
          {isTag && (
            <Grid item style={{ display: "flex" }}>
              <Icon
                style={{
                  fontSize: 18,
                  color: `#${item?.color}`,
                  marginRight: 6,
                }}
              >
                local_offer
              </Icon>
            </Grid>
          )}
          <Grid item xs zeroMinWidth>
            <Tooltip
              placement="bottom"
              title={item?.id == -1 ? messages[item.label] : item.label}
            >
              <Typography noWrap>
                {item?.id == -1 ? messages[item.label] : item.label}
              </Typography>
            </Tooltip>
          </Grid>
          {showCount && item?.entitiesCount > 0 && (
            <Grid item>
              <Typography variant="body2" color="text.secondary">
                {item.entitiesCount}
              </Typography>
            </Grid>
          )}
        </Box>

        {expanded[item.id]?.length > 0 &&
          expanded[item.id].map((childItem) => 
            <React.Fragment key={childItem.id}>
              {renderTagItem(childItem, depth + 1)}
            </React.Fragment>
          )}
      </Box>
    );
  };

  const renderEntitiesItem = (item: any, isSearching: boolean = false) => {
    const disabled = isItemDisabled(item);
    const isChecked = isItemChecked(item);
    const isIndeterminate = isItemIndeterminate(item);

    return (
      <Box key={item.id}>
        <Box display="flex" alignItems="center" mt={1}>
          <Grid item>
            <Checkbox
              checked={isChecked}
              value={isChecked ? "true" : "false"}
              isDisabled={disabled}
              id={`${instanceIdRef.current}-${item.id}`}
              onChange={() => handleCheckboxChange(item, isSearching)}
              isIndeterminate={isIndeterminate}
            />
          </Grid>
          <Grid item xs zeroMinWidth>
            <Tooltip
              placement="bottom"
              title={item?.id == -1 ? messages[item.label] : item.label}
            >
              <Typography noWrap>
                {item?.id == -1 ? messages[item.label] : item.label}
              </Typography>
            </Tooltip>
          </Grid>
          {showCount && item?.entitiesCount > 0 && (
            <Grid item>
              <Typography variant="body2" color="text.secondary">
                {item.entitiesCount}
              </Typography>
            </Grid>
          )}
        </Box>
      </Box>
    );
  };

  if (searchText?.trim() !== '') {
    return (
      <Box style={{ height: height, maxHeight: height || 300, overflow: "hidden auto" }}>
        {getEntityList(searchText)?.map((item: any) => renderEntitiesItem(item, true))}
      </Box>
    );
  }

  return (
    <Box style={{ height: height, maxHeight: height || 300, overflow: "hidden auto" }}>
      {
        entity === 'Driver' && includeUnassignedDrivers &&
        <Box ml='30px'>
            <Checkbox
                id={`${instanceIdRef.current}-unassigned-driver`}
                label={useLocale("include_inactive_drivers")}
                checked={value?.find((x: any) => x.id == UNASSIGNED_DRIVER.id && x.name == UNASSIGNED_DRIVER.name) ? true : false}
                value={value?.find((x: any) => x.id == UNASSIGNED_DRIVER.id && x.name == UNASSIGNED_DRIVER.name) ? 'true' : 'false'}
                onChange={() => handleCheckboxChange(UNASSIGNED_DRIVER)}
            />
        </Box>
      }
      {enableSelectAll && (
        <Box ml="30px" mb={1}>
          <Checkbox
            id={`${instanceIdRef.current}-select-all`}
            checked={isAllSelected()}
            value={isAllSelected() ? "true" : "false"}
            label={messages["selectAllTags"] || "Seleccionar todos los tags"}
            onChange={handleSelectAllChange}
          />
        </Box>
      )}
      {
      
        showOnlyEntity ? 
          entities?.map((entity) => renderEntitiesItem(entity)) : 
          getParentsTags().map((tag) => renderTagItem(tag, 0))
      }
    </Box>
  );
}

export default List