import React, { createContext, useContext, useState, useEffect } from 'react';
import { toast } from '@/components/ui/use-toast';
import { universignService } from '@/service/signature/universignService';

const SignatureContext = createContext();

export const useSignature = () => {
  const context = useContext(SignatureContext);
  if (!context) {
    throw new Error('useSignature must be used within a SignatureProvider');
  }
  return context;
};

export const SignatureProvider = ({ children }) => {
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState(null);
  const [signatures, setSignatures] = useState([]);
  const [history, setHistory] = useState([]);
  const [refreshTrigger, setRefreshTrigger] = useState(0);

  // Initial load
  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      try {
        const [statsData, sigsData, historyData] = await Promise.all([
          universignService.getStats(),
          universignService.getSignatures(),
          universignService.getConsumptionHistory()
        ]);
        
        setStats(statsData);
        setSignatures(sigsData);
        setHistory(historyData);
      } catch (error) {
        console.error("Error loading signature data:", error);
        toast({
          title: "Erreur",
          description: "Impossible de charger les données de signature.",
          variant: "destructive"
        });
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [refreshTrigger]);

  const refreshData = () => setRefreshTrigger(prev => prev + 1);

  const purchaseCredits = async (amount) => {
    try {
      await universignService.purchaseCredits(amount);
      refreshData();
      return true;
    } catch (error) {
      return false;
    }
  };

  const sendReminder = async (signatureId) => {
    try {
      await universignService.sendReminder(signatureId);
      refreshData();
      return true;
    } catch (error) {
      return false;
    }
  };

  return (
    <SignatureContext.Provider value={{
      loading,
      stats,
      signatures,
      history,
      refreshData,
      purchaseCredits,
      sendReminder
    }}>
      {children}
    </SignatureContext.Provider>
  );
};