import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import {
  PARLAY_MIN_LEGS,
  PARLAY_MAX_LEGS,
  canSelectForParlay,
  type ParlayRejectReason,
} from '@thebet365/shared';

export interface SlipItem {
  selectionId: string;
  oddsVersion: string;
  matchId: string;
  matchName: string;
  selectionName: string;
  odds: number;
  marketType: string;
  lineValue?: number | null;
  allowParlay?: boolean;
}

export const useBetSlipStore = defineStore('betSlip', () => {
  const items = ref<SlipItem[]>([]);
  const stake = ref<number>(10);
  const mode = ref<'single' | 'parlay'>('single');
  const lastParlayError = ref<ParlayRejectReason | 'MAX_LEGS' | null>(null);

  const count = computed(() => items.value.length);
  const isParlay = computed(() => mode.value === 'parlay' && items.value.length >= PARLAY_MIN_LEGS);

  function parseLineValue(v: number | string | null | undefined): number | null {
    if (v == null || v === '') return null;
    const n = typeof v === 'number' ? v : parseFloat(String(v));
    return Number.isFinite(n) ? n : null;
  }

  /** 球赛/详情页：同场可多选，分笔单关；再点同一项可取消 */
  function addItem(item: SlipItem) {
    if (mode.value === 'parlay') items.value = [];
    mode.value = 'single';
    lastParlayError.value = null;

    const existing = items.value.findIndex(
      (i) => i.selectionId === item.selectionId,
    );
    if (existing >= 0) {
      items.value.splice(existing, 1);
      return;
    }
    items.value.push(item);
  }

  /** 串关页：同场/跨场均可多选，合成一张串关单 */
  function addParlayLeg(item: SlipItem): ParlayRejectReason | 'MAX_LEGS' | null {
    if (mode.value === 'single') items.value = [];
    mode.value = 'parlay';

    const samePick = items.value.findIndex((i) => i.selectionId === item.selectionId);
    if (samePick >= 0) {
      items.value.splice(samePick, 1);
      lastParlayError.value = null;
      return null;
    }

    const check = canSelectForParlay({
      marketType: item.marketType,
      lineValue: parseLineValue(item.lineValue),
      allowParlay: item.allowParlay,
    });
    if (!check.ok) {
      lastParlayError.value = check.reason;
      return check.reason;
    }

    if (items.value.length >= PARLAY_MAX_LEGS) {
      lastParlayError.value = 'MAX_LEGS';
      return 'MAX_LEGS';
    }

    items.value.push(item);
    lastParlayError.value = null;
    return null;
  }

  function removeItem(selectionId: string) {
    items.value = items.value.filter((i) => i.selectionId !== selectionId);
    if (!items.value.length) mode.value = 'single';
    lastParlayError.value = null;
  }

  function clear() {
    items.value = [];
    mode.value = 'single';
    lastParlayError.value = null;
  }

  const totalOdds = computed(() =>
    items.value.reduce((acc, i) => acc * i.odds, 1),
  );

  const potentialReturn = computed(() => {
    if (!items.value.length) return 0;
    if (mode.value === 'parlay' && canPlaceParlay.value) {
      return stake.value * totalOdds.value;
    }
    return items.value.reduce((acc, i) => acc + stake.value * i.odds, 0);
  });

  const hasSameMatch = computed(() => {
    const matchIds = items.value.map((i) => i.matchId);
    return new Set(matchIds).size !== matchIds.length;
  });

  const canPlaceParlay = computed(
    () =>
      mode.value === 'parlay' &&
      items.value.length >= PARLAY_MIN_LEGS &&
      items.value.length <= PARLAY_MAX_LEGS,
  );

  /** 详情页等同场多笔单关（串关模式不走此路径） */
  const canPlaceBatchSingles = computed(
    () => mode.value === 'single' && items.value.length >= 1,
  );

  const canSubmit = computed(
    () => canPlaceParlay.value || canPlaceBatchSingles.value,
  );

  const drawerOpen = ref(false);

  function openDrawer() {
    drawerOpen.value = true;
  }

  function closeDrawer() {
    drawerOpen.value = false;
  }

  return {
    items,
    stake,
    mode,
    count,
    isParlay,
    totalOdds,
    potentialReturn,
    hasSameMatch,
    canPlaceParlay,
    canPlaceBatchSingles,
    canSubmit,
    lastParlayError,
    drawerOpen,
    addItem,
    addParlayLeg,
    removeItem,
    clear,
    openDrawer,
    closeDrawer,
  };
});
