import { create } from 'zustand';
import type { Sale, CreateSaleDto, DebtsSummary } from '../types/sale';
import { salesService } from '../services/sales';

interface SalesState {
  sales: Sale[];
  debts: Sale[];
  debtsSummary: DebtsSummary | null;
  cursor: string | null;
  hasMore: boolean;
  debtsCursor: string | null;
  debtsHasMore: boolean;
  isLoading: boolean;
  isLoadingMore: boolean;
  isSubmitting: boolean;
  error: string | null;
  activeTab: 'sales' | 'debts';

  setActiveTab: (tab: 'sales' | 'debts') => void;
  fetchSales: (refresh?: boolean) => Promise<void>;
  fetchMoreSales: () => Promise<void>;
  fetchDebts: (refresh?: boolean) => Promise<void>;
  fetchMoreDebts: () => Promise<void>;
  fetchDebtsSummary: () => Promise<void>;
  createSale: (dto: CreateSaleDto) => Promise<void>;
  markAsPaid: (id: string) => Promise<void>;
  cancelSale: (id: string) => Promise<void>;
  clearError: () => void;
}

export const useSalesStore = create<SalesState>((set, get) => ({
  sales: [],
  debts: [],
  debtsSummary: null,
  cursor: null,
  hasMore: false,
  debtsCursor: null,
  debtsHasMore: false,
  isLoading: false,
  isLoadingMore: false,
  isSubmitting: false,
  error: null,
  activeTab: 'sales',

  setActiveTab: (tab: 'sales' | 'debts') => {
    set({ activeTab: tab });
    if (tab === 'sales' && get().sales.length === 0) {
      get().fetchSales();
    }
    if (tab === 'debts' && get().debts.length === 0) {
      get().fetchDebts();
      get().fetchDebtsSummary();
    }
  },

  fetchSales: async (refresh = false) => {
    set({ isLoading: true, error: null });
    try {
      const response = await salesService.getSales({ limit: 20 });
      set({
        sales: response.data,
        cursor: response.cursor,
        hasMore: response.hasMore,
        isLoading: false,
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Ошибка загрузки продаж';
      set({ error: message, isLoading: false });
    }
  },

  fetchMoreSales: async () => {
    const { hasMore, isLoadingMore, cursor } = get();
    if (!hasMore || isLoadingMore) return;

    set({ isLoadingMore: true });
    try {
      const response = await salesService.getSales({
        cursor: cursor ?? undefined,
        limit: 20,
      });
      set((state) => ({
        sales: [...state.sales, ...response.data],
        cursor: response.cursor,
        hasMore: response.hasMore,
        isLoadingMore: false,
      }));
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Ошибка загрузки';
      set({ error: message, isLoadingMore: false });
    }
  },

  fetchDebts: async (refresh = false) => {
    set({ isLoading: true, error: null });
    try {
      const response = await salesService.getDebts({ limit: 20 });
      set({
        debts: response.data,
        debtsCursor: response.cursor,
        debtsHasMore: response.hasMore,
        isLoading: false,
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Ошибка загрузки долгов';
      set({ error: message, isLoading: false });
    }
  },

  fetchMoreDebts: async () => {
    const { debtsHasMore, isLoadingMore, debtsCursor } = get();
    if (!debtsHasMore || isLoadingMore) return;

    set({ isLoadingMore: true });
    try {
      const response = await salesService.getDebts({
        cursor: debtsCursor ?? undefined,
        limit: 20,
      });
      set((state) => ({
        debts: [...state.debts, ...response.data],
        debtsCursor: response.cursor,
        debtsHasMore: response.hasMore,
        isLoadingMore: false,
      }));
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Ошибка загрузки';
      set({ error: message, isLoadingMore: false });
    }
  },

  fetchDebtsSummary: async () => {
    try {
      const summary = await salesService.getDebtsSummary();
      set({ debtsSummary: summary });
    } catch {
      // Summary is not critical, ignore errors
    }
  },

  createSale: async (dto: CreateSaleDto) => {
    set({ isSubmitting: true, error: null });
    try {
      await salesService.createSale(dto);
      await get().fetchSales(true);
      set({ isSubmitting: false });
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Ошибка создания продажи';
      set({ error: message, isSubmitting: false });
      throw err;
    }
  },

  markAsPaid: async (id: string) => {
    set({ isSubmitting: true, error: null });
    try {
      await salesService.markAsPaid(id);
      await get().fetchSales(true);
      await get().fetchDebts(true);
      await get().fetchDebtsSummary();
      set({ isSubmitting: false });
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Ошибка оплаты';
      set({ error: message, isSubmitting: false });
      throw err;
    }
  },

  cancelSale: async (id: string) => {
    set({ isSubmitting: true, error: null });
    try {
      await salesService.cancelSale(id);
      await get().fetchSales(true);
      set({ isSubmitting: false });
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Ошибка отмены';
      set({ error: message, isSubmitting: false });
      throw err;
    }
  },

  clearError: () => {
    set({ error: null });
  },
}));
