import { useIntl } from '@umijs/max';
import { Checkbox, Input, Tabs } from 'antd';
import { useMemo, useState } from 'react';
import { TabContent } from './components/TabContent';
import { usePermTree } from './hooks/usePermTree';

export interface PermTreeProps {
  mode: 'view' | 'edit';
  allPerms: API.PermItem[];
  checkedPermIds?: number[];
  onChange?: (ids: number[]) => void;
}

const TAB_KEYS = ['api', 'data'] as const;

export const PermTree = ({ mode, allPerms, checkedPermIds = [], onChange }: PermTreeProps) => {
  const intl = useIntl();
  const {
    keyword,
    setKeyword,
    checkedIds,
    grouped: allGroups,
    filteredGroups,
    toggle,
    selectAll,
    invert,
    isAllSelected,
    isIndeterminate,
  } = usePermTree({ allPerms, initialCheckedIds: checkedPermIds, onChange });

  const [activeTab, setActiveTab] = useState<'api' | 'data'>('api');

  const tabItems = useMemo(
    () =>
      TAB_KEYS.map((key) => ({
        key,
        label: intl.formatMessage({ id: `admin.permTree.${key}Tab` }),
        children: (
          <TabContent
            tab={key}
            filteredGroups={filteredGroups}
            allGroups={allGroups}
            checkedIds={checkedIds}
            mode={mode}
            onToggle={toggle}
          />
        ),
      })),
    [intl, filteredGroups, allGroups, checkedIds, mode, toggle],
  );

  return (
    <div className="flex flex-col gap-2">
      {mode === 'edit' && (
        <div className="flex items-center gap-2">
          <Input.Search
            placeholder={intl.formatMessage({ id: 'admin.permTree.search' })}
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
            allowClear
            className="flex-1"
          />
          <Checkbox
            checked={isAllSelected(activeTab)}
            indeterminate={isIndeterminate(activeTab)}
            onChange={() => selectAll(activeTab)}
          >
            {intl.formatMessage({ id: 'admin.permTree.selectAll' })}
          </Checkbox>
          <a onClick={() => invert(activeTab)} className="text-sm whitespace-nowrap">
            {intl.formatMessage({ id: 'admin.permTree.invert' })}
          </a>
        </div>
      )}
      <Tabs
        activeKey={activeTab}
        onChange={(k) => setActiveTab(k as 'api' | 'data')}
        items={tabItems}
      />
    </div>
  );
};
