import { useEffect, useState } from 'react';
import { ShieldCheck } from 'lucide-react';
import type {
  BaseModelCatalogItem,
  GatewayAccessRule,
  GatewayAccessRuleBatchRequest,
  IntegrationPlatform,
  PlatformModel,
  UserGroup,
} from '@easyai-ai-gateway/contracts';
import { Badge, Card, CardContent, CardHeader, CardTitle, Label, Select } from '../../components/ui';
import type { LoadState } from '../../types';
import { AccessPermissionEditor } from './AccessPermissionEditor';

export function AccessRulesPanel(props: {
  accessRules: GatewayAccessRule[];
  baseModels: BaseModelCatalogItem[];
  message: string;
  platformModels: PlatformModel[];
  platforms: IntegrationPlatform[];
  state: LoadState;
  userGroups: UserGroup[];
  onBatchAccessRules: (input: GatewayAccessRuleBatchRequest) => Promise<void>;
}) {
  const [selectedGroupId, setSelectedGroupId] = useState(props.userGroups[0]?.id ?? '');

  useEffect(() => {
    if (!selectedGroupId && props.userGroups[0]?.id) {
      setSelectedGroupId(props.userGroups[0].id);
    }
  }, [props.userGroups, selectedGroupId]);

  return (
    <div className="pageStack">
      <Card>
        <CardHeader>
          <div>
            <CardTitle>用户组访问权限</CardTitle>
            <p className="mutedText">数据仍写入统一权限规则表；这里按用户组维护专属使用和不允许使用的平台/模型。</p>
          </div>
          <Badge variant="secondary">{props.accessRules.length} 条规则</Badge>
        </CardHeader>
        <CardContent>
          {props.message && <p className="formMessage">{props.message}</p>}
          <div className="accessGroupToolbar">
            <Label>
              用户组
              <Select size="sm" value={selectedGroupId} onChange={(event) => setSelectedGroupId(event.target.value)}>
                {props.userGroups.map((group) => <option value={group.id} key={group.id}>{group.name}</option>)}
              </Select>
            </Label>
            <div className="accessGroupHint">
              <ShieldCheck size={15} />
              <span>未配置规则时默认放行；拒绝规则优先于专属规则。</span>
            </div>
          </div>
        </CardContent>
      </Card>

      {selectedGroupId ? (
        <AccessPermissionEditor
          accessRules={props.accessRules}
          metadataMode="user_group_permission_tree"
          platformModels={props.platformModels}
          platforms={props.platforms}
          state={props.state}
          subjectId={selectedGroupId}
          subjectType="user_group"
          onBatchAccessRules={props.onBatchAccessRules}
        />
      ) : (
        <div className="emptyState">
          <strong>暂无用户组</strong>
          <span>请先创建用户组，再维护平台和模型权限。</span>
        </div>
      )}
    </div>
  );
}
