import type { ReactNode } from 'react';
import type { GatewayApiKey, PlatformModel } from '@easyai-ai-gateway/contracts';
import { Bot, Image as ImageIcon, Video } from 'lucide-react';
import { Select } from '../components/ui';
import type { PlaygroundMode } from '../types';
import type { PlaygroundVideoCreateMode } from './playground-upload';

export type VideoCreateMode = PlaygroundVideoCreateMode;

export interface ModelOption {
  count: number;
  label: string;
  models: PlatformModel[];
  provider: string;
  value: string;
}

export const modeOptions: Array<{ description: string; icon: ReactNode; label: string; value: PlaygroundMode }> = [
  { value: 'chat', label: '大模型对话', description: '对话、推理、结构化输出', icon: <Bot size={16} /> },
  { value: 'image', label: '图像生成', description: '文生图、图像编辑参数预览', icon: <ImageIcon size={16} /> },
  { value: 'video', label: '视频生成', description: '图生视频、文生视频任务测试', icon: <Video size={16} /> },
];

export const videoModeOptions: Array<{ label: string; value: VideoCreateMode }> = [
  { value: 'text_to_video', label: '文生视频' },
  { value: 'first_last_frame', label: '首尾帧' },
  { value: 'omni_reference', label: '全能参考' },
];

export const placeholderByMode: Record<PlaygroundMode, string> = {
  chat: '输入问题、角色设定或测试提示词，支持 OpenAI 兼容格式验证...',
  image: '描述你想生成的画面，例如：未来城市中的玻璃温室，晨光，电影级构图...',
  video: '描述视频镜头、主体运动和风格，例如：低角度跟拍，一辆复古跑车穿过雨夜街道...',
};

export const quickPrompts: Record<PlaygroundMode, string[]> = {
  chat: ['写一个产品发布摘要', '生成接口调用示例', '分析失败重试策略'],
  image: ['产品海报', '角色设定图', '电商主图'],
  video: ['5 秒运镜', '首帧转视频', '宣传短片'],
};

export function resolveSelectedApiKeyId(apiKeys: GatewayApiKey[], secretsById: Record<string, string>, selectedApiKeyId: string) {
  if (selectedApiKeyId && secretsById[selectedApiKeyId]) return selectedApiKeyId;
  const firstUsable = apiKeys.find((item) => Boolean(secretsById[item.id]));
  return firstUsable?.id ?? '';
}

export function apiKeyNoticeText(apiKeys: GatewayApiKey[], secretsById: Record<string, string>) {
  if (!apiKeys.length) return '当前账号还没有可用 API Key，请先创建一个 Key。';
  if (!apiKeys.some((item) => Boolean(secretsById[item.id]))) {
    return '当前没有可用于在线测试的完整 API Key，请重新加载或创建一个 Key。';
  }
  return '';
}

export function modelOptionLabel(option: ModelOption) {
  const count = option.count > 1 ? ` · ${option.count} 个客户端` : '';
  const provider = option.provider ? ` · ${option.provider}` : '';
  return `${option.label}${provider}${count}`;
}

export function ApiKeySelect(props: {
  apiKeySecretsById: Record<string, string>;
  apiKeys: GatewayApiKey[];
  selectedApiKeyId: string;
  onApiKeyChange: (apiKeyId: string) => void;
}) {
  const activeApiKeyId = resolveSelectedApiKeyId(props.apiKeys, props.apiKeySecretsById, props.selectedApiKeyId);
  return (
    <Select
      className="playgroundApiKeySelect"
      value={activeApiKeyId}
      disabled={!props.apiKeys.length}
      onChange={(event) => props.onApiKeyChange(event.target.value)}
    >
      {!activeApiKeyId && <option value="">{props.apiKeys.length ? '选择 API Key' : '暂无 API Key'}</option>}
      {props.apiKeys.map((item) => {
        const usable = Boolean(props.apiKeySecretsById[item.id]);
        return (
          <option value={item.id} key={item.id} disabled={!usable}>
            {item.name} · {item.keyPrefix}
          </option>
        );
      })}
    </Select>
  );
}

export function ModeSwitch(props: {
  activeMode: PlaygroundMode;
  onModeChange: (mode: PlaygroundMode) => void;
}) {
  return (
    <div className="playgroundModeSwitch">
      {modeOptions.map((item) => (
        <button
          type="button"
          key={item.value}
          data-active={props.activeMode === item.value}
          onClick={() => props.onModeChange(item.value)}
        >
          {item.icon}
          <span>{item.label}</span>
        </button>
      ))}
    </div>
  );
}

export function PlaygroundGreeting(props: {
  activeMode: { description: string; label: string };
}) {
  return (
    <div className="playgroundGreeting">
      <span>你好，想测试什么？</span>
      <strong>{props.activeMode.label}</strong>
      <small>{props.activeMode.description}</small>
    </div>
  );
}
