import { useEffect, useState } from 'react';

import { useAppDispatch, useAppSelector } from '../store';
import { selectSharedGroups } from '../store/hostsSlice/selectors';
import { fetchSharedGroups } from '../store/hostsSlice/thunks';

interface Props {
  hostkey: string;
}

const COLLAPSE_THRESHOLD = 20;

export const GroupsSection = ({ hostkey }: Props) => {
  const dispatch = useAppDispatch();
  const data = useAppSelector(state => selectSharedGroups(state, hostkey));
  const [showAll, setShowAll] = useState(false);

  useEffect(() => {
    setShowAll(false);
    if (hostkey) dispatch(fetchSharedGroups(hostkey));
  }, [dispatch, hostkey]);

  const renderBody = () => {
    if (!data) return '…';
    if (data.accessDenied) {
      return "You don't have access to view shared host groups. Contact your administrator to gain access.";
    }
    const groups = data.groups ?? [];
    if (groups.length === 0) {
      return 'No groups found.';
    }

    const visible = showAll ? groups : groups.slice(0, COLLAPSE_THRESHOLD);
    const hidden = groups.length > COLLAPSE_THRESHOLD;

    return (
      <span>
        Shared groups:{' '}
        {visible.map((g, i) => (
          <span key={g.id}>
            <a className="btn-blue-link" style={{ verticalAlign: 'baseline' }} href={`/groups/shared/${g.id}`}>
              {g.name}
            </a>
            {i < visible.length - 1 ? ', ' : ''}
          </span>
        ))}
        {hidden && (
          <>
            {showAll ? '. ' : ' '}
            <button className="btn btn-link btn-moreless" onClick={() => setShowAll(!showAll)}>
              {showAll ? 'Show less' : 'Show more...'}
            </button>
          </>
        )}
      </span>
    );
  };

  return (
    <div className="relative" style={{ minHeight: 80 }}>
      <div className="margin-top">
        <h4 title="Ordered by priority, data from the more specific groups at the end of the list is preferred when merging.">
          Groups
        </h4>
        <div>{renderBody()}</div>
      </div>
    </div>
  );
};
