import { useState } from 'react';
import { Ban, CheckCircle2, Trash2 } from 'lucide-react';
import type { IdentityBatchAction } from '@easyai-ai-gateway/contracts';
import { Button, ConfirmDialog } from '../../components/ui';

export function IdentityBatchToolbar(props: {
  entityLabel: string;
  loading: boolean;
  selectedCount: number;
  onAction: (action: IdentityBatchAction) => Promise<void>;
}) {
  const [pendingAction, setPendingAction] = useState<IdentityBatchAction | null>(null);
  const disabled = props.loading || props.selectedCount === 0;
  const copy = pendingAction ? identityBatchActionCopy(pendingAction, props.entityLabel, props.selectedCount) : null;

  async function confirm() {
    if (!pendingAction) return;
    await props.onAction(pendingAction);
    setPendingAction(null);
  }

  return (
    <>
      <div className="identityBatchToolbar" aria-label={`${props.entityLabel}批量操作`}>
        <span>已选 <strong>{props.selectedCount}</strong> 项</span>
        <div>
          <Button type="button" size="sm" variant="outline" disabled={disabled} onClick={() => setPendingAction('enable')}>
            <CheckCircle2 size={14} />批量启用
          </Button>
          <Button type="button" size="sm" variant="outline" disabled={disabled} onClick={() => setPendingAction('disable')}>
            <Ban size={14} />批量禁用
          </Button>
          <Button type="button" size="sm" variant="destructive" disabled={disabled} onClick={() => setPendingAction('delete')}>
            <Trash2 size={14} />批量删除
          </Button>
        </div>
      </div>
      <ConfirmDialog
        confirmLabel={copy?.confirmLabel}
        confirmVariant={pendingAction === 'delete' ? 'destructive' : 'default'}
        description={copy?.description}
        loading={props.loading}
        open={Boolean(pendingAction)}
        title={copy?.title ?? ''}
        onCancel={() => setPendingAction(null)}
        onConfirm={confirm}
      />
    </>
  );
}

export function identityBatchActionCopy(action: IdentityBatchAction, entityLabel: string, count: number) {
  if (action === 'enable') {
    return {
      confirmLabel: '确认启用',
      description: `选中的 ${count} 个${entityLabel}将恢复为 active 状态。`,
      title: `批量启用${entityLabel}？`,
    };
  }
  if (action === 'disable') {
    return {
      confirmLabel: '确认禁用',
      description: `选中的 ${count} 个${entityLabel}将被设为 disabled。`,
      title: `批量禁用${entityLabel}？`,
    };
  }
  return {
    confirmLabel: '确认批量删除',
    description: `将删除选中的 ${count} 个${entityLabel}，该操作不能从当前页面撤销。`,
    title: `批量删除${entityLabel}？`,
  };
}
