import { createContext, useState, useCallback } from 'react';
import type { ReactNode } from 'react';

const BASKET_STORAGE_KEY = 'snp-api-basket';

export interface BasketItem {
  apiId: number;
  serviceId: number;
  apiName: string;
  domain?: string;
}

export interface ApiRequestBasketContextType {
  items: BasketItem[];
  addItem: (item: BasketItem) => void;
  removeItem: (apiId: number) => void;
  clearItems: () => void;
  hasItem: (apiId: number) => boolean;
  isBasketOpen: boolean;
  setBasketOpen: (open: boolean) => void;
}

export const ApiRequestBasketContext = createContext<ApiRequestBasketContextType | null>(null);

const loadFromStorage = (): BasketItem[] => {
  try {
    const raw = localStorage.getItem(BASKET_STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed)) return parsed as BasketItem[];
    return [];
  } catch {
    return [];
  }
};

const saveToStorage = (items: BasketItem[]): void => {
  try {
    localStorage.setItem(BASKET_STORAGE_KEY, JSON.stringify(items));
  } catch {
    // 저장 실패 시 무시
  }
};

interface ApiRequestBasketProviderProps {
  children: ReactNode;
}

const ApiRequestBasketProvider = ({ children }: ApiRequestBasketProviderProps) => {
  const [items, setItems] = useState<BasketItem[]>(loadFromStorage);
  const [isBasketOpen, setIsBasketOpen] = useState(false);

  const addItem = useCallback((item: BasketItem) => {
    setItems((prev) => {
      if (prev.some((i) => i.apiId === item.apiId)) return prev;
      const next = [...prev, item];
      saveToStorage(next);
      return next;
    });
  }, []);

  const removeItem = useCallback((apiId: number) => {
    setItems((prev) => {
      const next = prev.filter((i) => i.apiId !== apiId);
      saveToStorage(next);
      return next;
    });
  }, []);

  const clearItems = useCallback(() => {
    setItems([]);
    saveToStorage([]);
  }, []);

  const hasItem = useCallback(
    (apiId: number) => items.some((i) => i.apiId === apiId),
    [items],
  );

  const setBasketOpen = useCallback((open: boolean) => {
    setIsBasketOpen(open);
  }, []);

  return (
    <ApiRequestBasketContext.Provider value={{ items, addItem, removeItem, clearItems, hasItem, isBasketOpen, setBasketOpen }}>
      {children}
    </ApiRequestBasketContext.Provider>
  );
};

export default ApiRequestBasketProvider;
