import { Button, Typography } from 'antd';
import { Fragment, useMemo, useState } from 'react';

const { Link, Text } = Typography;

export type FolderTreeLeaf = {
  id: string;
  label: string;
  href: string;
};

export type FolderTreeGroup = {
  id: string;
  label: string;
  items: FolderTreeLeaf[];
};

export type FolderTreeNavProps = {
  groups: FolderTreeGroup[];
  title?: string;
  defaultExpandedIds?: string[];
};

export function FolderTreeNav({
  groups,
  title = 'Folders',
  defaultExpandedIds = [],
}: FolderTreeNavProps) {
  const [expandedIds, setExpandedIds] = useState<string[]>(defaultExpandedIds);
  const expandedSet = useMemo(() => new Set(expandedIds), [expandedIds]);

  const toggleGroup = (groupId: string) => {
    setExpandedIds((previous) =>
      previous.includes(groupId)
        ? previous.filter((id) => id !== groupId)
        : [...previous, groupId],
    );
  };

  return (
    <div className="folder-tree-nav">
      <Text strong>{title}</Text>
      <div className="folder-tree-nav__groups">
        {groups.map((group) => {
          const isExpanded = expandedSet.has(group.id);

          return (
            <Fragment key={group.id}>
              <div className="folder-tree-nav__group-row">
                <Button
                  type="text"
                  size="small"
                  className="folder-tree-nav__toggle"
                  onClick={() => {
                    toggleGroup(group.id);
                  }}
                >
                  {isExpanded ? '-' : '+'}
                </Button>
                <Link href={`#${group.id}`}>{group.label}</Link>
              </div>

              {isExpanded ? (
                <div className="folder-tree-nav__children">
                  {group.items.map((item) => (
                    <Link key={item.id} href={item.href} className="folder-tree-nav__child-link">
                      {item.label}
                    </Link>
                  ))}
                </div>
              ) : null}
            </Fragment>
          );
        })}
      </div>
    </div>
  );
}
