import { useIntl, useModel } from '@umijs/max';
import { Spin, TreeSelect } from 'antd';
import { useEffect, useState } from 'react';

interface TreeSelectedGroupProps {
  groupIds?: string | string[] | null;
  multiple?: boolean;
  disabled?: boolean;
  isLoading?: boolean;
  onSelected?: (value: string | string[] | null) => void;
  placeholder?: string;
  allowClear?: boolean;
  showSearch?: boolean;
  style?: React.CSSProperties;
}

const TreeSelectedGroup = ({
  groupIds,
  multiple = false,
  disabled = false,
  isLoading = false,
  onSelected,
  placeholder,
  allowClear = true,
  showSearch = true,
  style = { width: '100%' },
}: TreeSelectedGroupProps) => {
  const intl = useIntl();
  const { initialState } = useModel('@@initialState');
  const { currentUserProfile } = initialState || {};
  const [treeData, setTreeData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedValue, setSelectedValue] = useState<string | string[] | null>(
    () => {
      // If disabled is true, don't show any selected values
      if (disabled) {
        return null;
      }
      return groupIds || null;
    },
  );
  const { groups, getGroups } = useModel('master.useGroups');
  useEffect(() => {
    if (!groups) {
      getGroups();
    }
  }, [groups]);
  // Update internal state when prop changes
  useEffect(() => {
    // If disabled is true, clear the selection
    if (disabled) {
      setSelectedValue(null);
    } else {
      setSelectedValue(groupIds || null);
    }
  }, [groupIds, disabled]);

  const transformGroupNodeToTreeData = (
    groups: MasterModel.GroupNode[],
  ): any[] => {
    // console.log('Group tranform: ', groups);

    // Convert groupIds to array for easier checking
    const groupIdsArray = Array.isArray(groupIds)
      ? groupIds
      : groupIds
      ? [groupIds]
      : [];

    return groups.map((group: any) => ({
      title: group.name,
      value: group.id,
      key: group.id,
      disabled: disabled && groupIdsArray.includes(group.id),
      children: group.children
        ? transformGroupNodeToTreeData(group.children)
        : undefined,
      data: group,
    }));
  };

  useEffect(() => {
    const loadTreeData = async () => {
      setLoading(true);
      const transformedData = transformGroupNodeToTreeData(groups || []);
      setTreeData(transformedData);
      setLoading(false);
    };

    loadTreeData();
  }, [currentUserProfile, groups, disabled, groupIds]);

  const handleChange = (value: string | string[] | null) => {
    setSelectedValue(value);
    onSelected?.(value);
  };

  return (
    <Spin spinning={loading}>
      <TreeSelect
        disabled={isLoading}
        value={selectedValue}
        multiple={multiple}
        treeCheckable={multiple}
        showSearch={showSearch}
        style={style}
        styles={{
          popup: {
            root: {
              maxHeight: 400,
              overflow: 'auto',
            },
          },
        }}
        placeholder={
          placeholder ||
          intl.formatMessage({
            id: 'master.groups.treeselect.placeholder',
            defaultMessage: 'Please select group',
          })
        }
        allowClear={allowClear}
        treeDefaultExpandAll
        treeData={treeData}
        onChange={handleChange}
        treeLine
        filterTreeNode={(search, node) => {
          return (
            node.title
              ?.toString()
              .toLowerCase()
              .includes(search.toLowerCase()) ?? false
          );
        }}
      />
    </Spin>
  );
};

export default TreeSelectedGroup;
