import client from './client';
import type { PaginatedResponse } from './types';

export interface PluginEntityInfo {
  name: string;
  display_name: string;
  table_name: string;
}

export interface PluginPermissionInfo {
  code: string;
  name: string;
  description: string;
}

export type PluginStatus = 'uploaded' | 'installed' | 'enabled' | 'running' | 'disabled' | 'uninstalled';

export interface PluginInfo {
  id: string;
  name: string;
  version: string;
  description?: string;
  author?: string;
  status: PluginStatus;
  config: Record<string, unknown>;
  installed_at?: string;
  enabled_at?: string;
  entities: PluginEntityInfo[];
  permissions?: PluginPermissionInfo[];
  record_version: number;
}

export async function listPlugins(page = 1, pageSize = 20, status?: string) {
  const { data } = await client.get<{ success: boolean; data: PaginatedResponse<PluginInfo> }>(
    '/admin/plugins',
    { params: { page, page_size: pageSize, status: status || undefined } },
  );
  return data.data;
}

export async function getPlugin(id: string) {
  const { data } = await client.get<{ success: boolean; data: PluginInfo }>(
    `/admin/plugins/${id}`,
  );
  return data.data;
}

export async function uploadPlugin(wasmFile: File, manifestToml: string) {
  const formData = new FormData();
  formData.append('wasm', wasmFile);
  formData.append('manifest', manifestToml);

  const { data } = await client.post<{ success: boolean; data: PluginInfo }>(
    '/admin/plugins/upload',
    formData,
    { headers: { 'Content-Type': 'multipart/form-data' }, timeout: 60000 },
  );
  return data.data;
}

export async function installPlugin(id: string) {
  const { data } = await client.post<{ success: boolean; data: PluginInfo }>(
    `/admin/plugins/${id}/install`,
  );
  return data.data;
}

export async function enablePlugin(id: string) {
  const { data } = await client.post<{ success: boolean; data: PluginInfo }>(
    `/admin/plugins/${id}/enable`,
  );
  return data.data;
}

export async function disablePlugin(id: string) {
  const { data } = await client.post<{ success: boolean; data: PluginInfo }>(
    `/admin/plugins/${id}/disable`,
  );
  return data.data;
}

export async function uninstallPlugin(id: string) {
  const { data } = await client.post<{ success: boolean; data: PluginInfo }>(
    `/admin/plugins/${id}/uninstall`,
  );
  return data.data;
}

export async function purgePlugin(id: string) {
  await client.delete(`/admin/plugins/${id}`);
}

export async function getPluginHealth(id: string) {
  const { data } = await client.get<{
    success: boolean;
    data: { plugin_id: string; status: string; details: Record<string, unknown> };
  }>(`/admin/plugins/${id}/health`);
  return data.data;
}

export async function updatePluginConfig(id: string, config: Record<string, unknown>, version: number) {
  const { data } = await client.put<{ success: boolean; data: PluginInfo }>(
    `/admin/plugins/${id}/config`,
    { config, version },
  );
  return data.data;
}

export async function getPluginSchema(id: string): Promise<PluginSchemaResponse> {
  const { data } = await client.get<{ success: boolean; data: PluginSchemaResponse }>(
    `/admin/plugins/${id}/schema`,
  );
  return data.data;
}

// ── Schema 类型定义 ──

export interface PluginFieldValidation {
  pattern?: string;
  message?: string;
  min_length?: number;
  max_length?: number;
  min_value?: number;
  max_value?: number;
}

export interface PluginFieldSchema {
  name: string;
  field_type: string;
  required: boolean;
  display_name?: string;
  ui_widget?: string;
  options?: { label: string; value: string }[];
  searchable?: boolean;
  filterable?: boolean;
  sortable?: boolean;
  visible_when?: string;
  unique?: boolean;
  ref_entity?: string;
  ref_label_field?: string;
  ref_search_fields?: string[];
  ref_plugin?: string;
  ref_fallback_label?: string;
  cascade_from?: string;
  cascade_filter?: string;
  validation?: PluginFieldValidation;
}

export interface PluginRelationSchema {
  entity: string;
  foreign_key: string;
  on_delete: 'cascade' | 'nullify' | 'restrict';
  name?: string;
  type?: 'one_to_many' | 'many_to_one' | 'many_to_many';
  display_field?: string;
}

export interface PluginEntitySchema {
  name: string;
  display_name: string;
  fields: PluginFieldSchema[];
  relations?: PluginRelationSchema[];
  data_scope?: boolean;
  is_public?: boolean;
  importable?: boolean;
  exportable?: boolean;
}

export interface PluginSchemaResponse {
  entities: PluginEntitySchema[];
  ui?: PluginUiSchema;
  settings?: PluginSettings;
  numbering?: PluginNumbering[];
  trigger_events?: PluginTriggerEvent[];
}

export interface PluginUiSchema {
  pages: PluginPageSchema[];
}

export type PluginPageSchema =
  | { type: 'crud'; entity: string; label: string; icon?: string; enable_search?: boolean; enable_views?: string[] }
  | { type: 'tree'; entity: string; label: string; icon?: string; id_field: string; parent_field: string; label_field: string }
  | { type: 'detail'; entity: string; label: string; sections: PluginSectionSchema[] }
  | { type: 'tabs'; label: string; icon?: string; tabs: PluginPageSchema[] }
  | { type: 'graph'; entity: string; label: string; relationship_entity: string; source_field: string; target_field: string; edge_label_field: string; node_label_field: string }
  | { type: 'dashboard'; label: string; widgets?: DashboardWidget[] }
  | {
      type: 'kanban';
      entity: string;
      label: string;
      icon?: string;
      lane_field: string;
      lane_order?: string[];
      card_title_field: string;
      card_subtitle_field?: string;
      card_fields?: string[];
      enable_drag?: boolean;
    };

export interface DashboardWidget {
  type: 'stat_card' | 'bar_chart' | 'pie_chart' | 'funnel_chart' | 'line_chart'
    | 'stat_cards' | 'action_list' | 'funnel' | 'card_list';
  entity: string;
  title: string;
  icon?: string;
  color?: string;
  dimension_field?: string;
  dimension_order?: string[];
  metric?: string;
  // stat_cards
  cards?: StatCardDef[];
  // action_list
  max_items?: number;
  queries?: ActionQueryDef[];
  // funnel
  lane_field?: string;
  value_field?: string;
  lane_order?: string[];
  // card_list
  filter?: string;
  title_field?: string;
  subtitle_field?: string;
  tags?: string[];
  label?: string;
  label_field?: string;
  action?: string;
  sort?: string;
}

export interface StatCardDef {
  entity: string;
  aggregate?: string;
  field?: string;
  filter?: string;
  label: string;
  icon?: string;
  color?: string;
}

export interface ActionQueryDef {
  entity: string;
  filter?: string;
  sort?: string;
  label_field: string;
  subtitle_field?: string;
  action: string;
  icon?: string;
}

export type PluginSectionSchema =
  | { type: 'fields'; label: string; fields: string[] }
  | { type: 'crud'; label: string; entity: string; filter_field?: string; enable_views?: string[] };

// ── P2 平台通用服务 — Settings 类型 ──

export type PluginSettingType =
  | 'text' | 'number' | 'boolean' | 'select' | 'multiselect'
  | 'color' | 'date' | 'datetime' | 'json';

export interface PluginSettingField {
  name: string;
  display_name: string;
  field_type: PluginSettingType;
  default_value?: unknown;
  required: boolean;
  description?: string;
  options?: { label: string; value: string }[];
  range?: [number, number];
  group?: string;
}

export interface PluginSettings {
  fields: PluginSettingField[];
}

// ── P2 平台通用服务 — Numbering 类型 ──

export interface PluginNumbering {
  entity: string;
  field: string;
  prefix: string;
  format: string;
  reset_rule: 'never' | 'daily' | 'monthly' | 'yearly';
  seq_length: number;
  separator?: string;
}

// ── P2 平台通用服务 — TriggerEvent 类型 ──

export interface PluginTriggerEvent {
  name: string;
  display_name: string;
  description: string;
  entity: string;
  on: 'create' | 'update' | 'delete' | 'create_or_update';
}

// ── 插件市场 API ──

export interface MarketEntry {
  id: string;
  plugin_id: string;
  name: string;
  version: string;
  description?: string;
  author?: string;
  category?: string;
  tags?: string[];
  icon_url?: string;
  screenshots?: string[];
  min_platform_version?: string;
  status: string;
  download_count: number;
  rating_avg: number;
  rating_count: number;
  changelog?: string;
  created_at?: string;
  updated_at?: string;
}

export interface MarketEntryDetail extends MarketEntry {
  dependency_warnings: string[];
}

export interface MarketReview {
  id: string;
  user_id: string;
  market_entry_id: string;
  rating: number;
  review_text?: string;
  created_at?: string;
}

export async function listMarketEntries(params?: {
  page?: number;
  page_size?: number;
  category?: string;
  search?: string;
}) {
  const { data } = await client.get<{ success: boolean; data: PaginatedResponse<MarketEntry> }>(
    '/market/entries',
    { params },
  );
  return data.data;
}

export async function getMarketEntry(id: string) {
  const { data } = await client.get<{ success: boolean; data: MarketEntryDetail }>(
    `/market/entries/${id}`,
  );
  return data.data;
}

export async function installFromMarket(id: string) {
  const { data } = await client.post<{ success: boolean; data: PluginInfo }>(
    `/market/entries/${id}/install`,
  );
  return data.data;
}

export async function listMarketReviews(id: string) {
  const { data } = await client.get<{ success: boolean; data: MarketReview[] }>(
    `/market/entries/${id}/reviews`,
  );
  return data.data;
}

export async function submitMarketReview(id: string, review: { rating: number; review_text?: string }) {
  const { data } = await client.post<{ success: boolean; data: MarketReview }>(
    `/market/entries/${id}/reviews`,
    review,
  );
  return data.data;
}
