import React, { createContext, useContext, useReducer } from 'react';

export type QRState = {
  text: string;
  size: number;
  imageUrl: string | null;
  loading: boolean;
  error: string | null;
};

type Action =
  | { type: 'setText'; payload: string }
  | { type: 'setSize'; payload: number }
  | { type: 'setImageUrl'; payload: string | null }
  | { type: 'setLoading'; payload: boolean }
  | { type: 'setError'; payload: string | null };

const initialState: QRState = {
  text: '',
  size: 300,
  imageUrl: null,
  loading: false,
  error: null,
};

function reducer(state: QRState, action: Action): QRState {
  switch (action.type) {
    case 'setText':
      return { ...state, text: action.payload };
    case 'setSize':
      return { ...state, size: action.payload };
    case 'setImageUrl':
      return { ...state, imageUrl: action.payload };
    case 'setLoading':
      return { ...state, loading: action.payload };
    case 'setError':
      return { ...state, error: action.payload };
    default:
      return state;
  }
}

const QrContext = createContext<{ state: QRState; dispatch: React.Dispatch<Action> } | undefined>(
  undefined
);

export const QrProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return <QrContext.Provider value={{ state, dispatch }}>{children}</QrContext.Provider>;
};

export function useQrStore() {
  const ctx = useContext(QrContext);
  if (!ctx) throw new Error('useQrStore must be used within QrProvider');
  return ctx;
}
