import type { ReactNode } from "react";
import type { AdminTone } from "./layouts/admin";
import type {
  ProductHistoryQuery,
  ProductHistoryPagination,
  ProductListQuery,
  ProductTab,
} from "./features/products/components/productTypes";

type KnownMarketSyncPage =
  | "market-sync"
  | "market-sync-home"
  | "market-sync-connections"
  | "market-sync-products"
  | "market-sync-orders"
  | "market-sync-settings";

export type MarketSyncPage = KnownMarketSyncPage | (string & {});

export interface StoredConnectionsPageState {
  query: string;
}

export interface StoredProductsPageState {
  inventoryQuery: ProductHistoryQuery;
  inventoryPagination: ProductHistoryPagination;
  inventorySearch: string;
  linkedQuery: ProductListQuery;
  priceQuery: ProductHistoryQuery;
  pricePagination: ProductHistoryPagination;
  priceSearch: string;
  tab: ProductTab;
  unlinkedQuery: ProductListQuery;
}

export type SettingsTabSlug = "connection";

export interface SettingsTabConfig {
  label: string;
  url: string;
}

export interface MarketSyncAdminUrls {
  home: string;
  settings: string;
  settingsConnection: string;
  connections: string;
  products: string;
  orders: string;
}

export interface ChatSupportConfig {
  appId: string;
  origin: string;
}

/**
 * Served by /admin/chat-support/identity, never inlined into the page. The admin's
 * name and email are only fetched once the user asks to start a chat.
 */
export interface ChatSupportIdentity {
  externalId: string;
  userHash: string;
  email: string;
  name: string;
  customData: Record<string, string>;
}

export interface MarketSyncAdminConfig {
  rootId: string;
  page: MarketSyncPage;
  settingsTab: SettingsTabSlug;
  restBase: string;
  chatSupport: ChatSupportConfig;
  urls: MarketSyncAdminUrls;
  settingsTabs: Record<SettingsTabSlug, SettingsTabConfig>;
}

export interface ConnectionDetails {
  isConnected: boolean;
  status: string;
  label?: string;
  store?: string;
  shopId?: number | string | null;
  lastSyncAt?: string;
  lastError?: string;
  saasBaseUrl?: string;
  currency?: string;
  locale?: string;
  pluginVersion?: string;
  wooVersion?: string;
  connectedAt?: string;
}

export interface HomeStats {
  totalOrders: number;
  failedImports: number;
  totalProducts: number;
  totalMarketplaces: number;
}

export interface ProductStats {
  total: number;
  linked: number;
  unlinked: number;
}

export interface ProductStatsResponse {
  stats: ProductStats;
}

// Home tones arrive from the REST layer but render through the same palette as
// the rest of the admin, so they stay one type rather than a parallel copy.
export type HomeTone = AdminTone;

export interface HomeChannel {
  id: string;
  initials: string;
  logoUrl?: string;
  name: string;
  status: string;
  detail: string;
  products: number;
  tone: HomeTone;
}

export interface HomeOperationMetric {
  value: string;
  helper: string;
  progress: number;
  tone: HomeTone;
}

export interface HomeOperations {
  catalogReady: HomeOperationMetric;
  channelCoverage: HomeOperationMetric;
}

export interface HomeResponse {
  connection: ConnectionDetails;
  stats: HomeStats;
  channels: HomeChannel[];
  operations: HomeOperations;
}

export interface SettingsResponse {
  connection: ConnectionDetails;
}

export interface ActionResponse {
  ok: boolean;
  message: string;
}

export interface PaginationInfo {
  currentPage: number;
  perPage: number;
  totalItems: number;
  totalPages: number;
}

export interface MarketplaceProduct {
  id: number;
  barcode: string | null;
  sku: string | null;
  default_title: string | null;
  image_url: string;
  linked: boolean;
  manual_linked: boolean | 0 | 1;
  requires_components: boolean | 0 | 1;
  platform_variant_id: number | null;
  variant_id: number | null;
  sales_channel?: MarketplaceSalesChannel;
  stock: number;
  product_title: string | null;
  shop_currency?: string | null;
  sc_currency?: string | null;
}

export interface MarketplaceSalesChannel {
  id: number;
  prefix: string | null;
  shop_name: string;
  channel_type: string | null;
  active: boolean | 0 | 1;
  currency: string | null;
  shop_to_marketplace_currency_rate: number | null;
  fields: unknown[];
  tags: unknown[];
  product_tags: unknown[];
  default_metafields: unknown[];
  markup: number | string | null;
  markup_type: string | null;
  rounding: number | string | null;
  display_name: string;
}

export interface MarketplaceOrderProduct {
  id: number;
  image_url: string | null;
  barcode: string | null;
  sku: string | null;
  platform_product_id: number | string | null;
  platform_variant_id: number | string | null;
  has_only_default_variant?: boolean;
}

export interface MarketplaceOrderTracking {
  id: number;
  tracking_company: string;
  tracking_number: string;
  tracking_url: string | null;
  synced: boolean;
}

export interface MarketplaceOrderItem {
  id: number;
  title: string;
  quantity: number;
  commission: string | null;
  latest_delivery_date: string | null;
  product: MarketplaceOrderProduct | null;
  linked: boolean;
  tracking: MarketplaceOrderTracking[];
}

export interface WooProductOption {
  id: number;
  name: string;
  sku: string;
  stock: number;
  type: string;
  variations: Array<{ id: number; name: string; sku: string; stock: number }>;
}

export interface WooProductsResponse {
  products: WooProductOption[];
}

export interface MarketplaceOrderAddress {
  full_name: string;
  company: string;
  address: string;
  address_extra_information: string;
  zip_code: string;
  city: string;
  state: string;
  country: string;
  country_code: string;
  email: string;
  phone: string;
}

/**
 * The order shape `Order_Resource` emits. `MarketSync\Orders\Order` is the
 * source of truth for it, so change the PHP object first and mirror it here.
 */
export interface MarketplaceOrder {
  id: number;
  order_number: string;
  platform_order_number: string;
  marketplace: string;
  type: string;
  order_date: string;
  shipping_name: string;
  imported_in_store: boolean;
  woocommerce_edit_url: string | null;
  tracking_synced: boolean;
  marketplace_commission: string | null;
  latest_delivery_date: string | null;
  order_total: string;
  currency: string;
  charge_subtotal: string;
  charge_tax: string;
  shipping_costs: string | null;
  shipping_tax: string | null;
  sales_channel: MarketplaceSalesChannel | null;
  shipping_address: MarketplaceOrderAddress;
  billing_address: MarketplaceOrderAddress;
  order_placed_date: string;
  items: MarketplaceOrderItem[];
  /** `null` when the payload carried no item list, so linkage is unknown. */
  products_linked: boolean | null;
  shop_name: string;
  archived: boolean;
  import_error: boolean;
  error_status: unknown;
  anonymized: boolean;
  fulfillment_by_marketplace: boolean;
  is_prime: boolean;
  is_business: boolean;
  review_request_sent: boolean | null;
  sales_channel_permalink: string;
  cancelled_at: string | null;
  cancel_reason: string | null;
  location_id: number | string | null;
  has_tracking: boolean;
  status: string;
  discount: string | null;
  sales_channel_extra_order_data: string | null;
  metadata: string | null;
}

export interface OrderStats {
  total: number;
  pending: number;
  imported: number;
  failed: number;
  needsTracking: number;
  archived: number;
}

export interface OrderStatsResponse {
  stats: OrderStats;
}

export interface OrdersResponse {
  data: MarketplaceOrder[];
  meta: {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
  };
}

export type SaleChannelFlow = "amazon-oauth" | "ebay-oauth" | "oauth" | "manual" | (string & {});

export type SaleChannelFieldType =
  | "string"
  | "boolean"
  | "select"
  | "multi_select"
  | "number_decimal"
  | "number_integer"
  | (string & {});

export interface SaleChannelFieldOption {
  label: string;
  value: string;
}

export interface SaleChannelField {
  id?: number | string;
  name: string;
  displayName: string;
  description?: string;
  type: SaleChannelFieldType;
  value?: boolean | string | string[] | number | null;
  options?: SaleChannelFieldOption[];
  hidden?: boolean;
  readOnly?: boolean;
  required?: boolean;
}

export interface SaleChannelType {
  id?: number | string;
  name: string;
  label: string;
  flow: SaleChannelFlow;
  logoUrl?: string;
}

export interface SaleChannelSummary {
  id: number | string;
  name: string;
  prefix?: string;
  active: boolean;
  channelType: Pick<SaleChannelType, "name" | "label" | "logoUrl">;
}

export interface SaleChannelTag {
  tag: string;
}

export interface SaleChannelForm {
  id?: number | string | null;
  action: "add" | "edit" | (string & {});
  active: boolean;
  name: string;
  prefix?: string;
  channelType: SaleChannelType;
  fields: SaleChannelField[];
  tags: SaleChannelTag[];
  productTags: SaleChannelTag[];
  metafields: SaleChannelField[];
  oauth?: {
    requiresMarketplace?: boolean;
    supportsAutoDetect?: boolean;
  };
}

export interface SaleChannelsResponse {
  saleChannels: SaleChannelSummary[];
}

export interface SaleChannelTypesResponse {
  saleChannelTypes: SaleChannelType[];
}

export interface SaleChannelFormResponse {
  form: SaleChannelForm;
}

export type NoticeType = "info" | "success" | "error";

export type Renderable = ReactNode;

export interface ImportOrdersResponse extends ActionResponse {
  imported_ids: number[];
  errors: string[];
}

export interface OrderListQuery {
  page: number;
  saleChannelId: string;
  search: string;
  overview: OrderOverviewFilter;
}

export type OrderOverviewFilter =
  "all" | "pending" | "imported" | "failed" | "needs_tracking" | "archived";
