import { mockQuotes, mockOrders, mockInvoices } from '@/data/mockData';

// Mock data store for signatures
let mockSignatures = [
  ...mockQuotes.filter(q => q.status !== 'Brouillon').map(q => ({
    id: `SIG-Q-${q.id}`,
    documentId: q.id,
    documentType: 'quote',
    documentNumber: q.number,
    clientName: q.client,
    signerEmail: q.signerEmail || 'client@email.com',
    status: q.signatureStatus === 'signed' ? 'signed' : q.signatureStatus === 'viewed' ? 'viewed' : 'sent',
    sentAt: q.date,
    viewedAt: q.signatureStatus !== 'pending' ? new Date(new Date(q.date).getTime() + 3600000).toISOString() : null,
    signedAt: q.signedDate,
    creditsConsumed: q.signatureStatus === 'signed',
    remindersSent: 0
  })),
  // Add some dummy orders/invoices for variety
  {
    id: 'SIG-O-1',
    documentId: 1,
    documentType: 'order',
    documentNumber: 'CM000126',
    clientName: 'TechStart SAS',
    signerEmail: 'jean@techstart.com',
    status: 'pending',
    sentAt: new Date(Date.now() - 86400000 * 2).toISOString(),
    creditsConsumed: false,
    remindersSent: 1
  }
];

let creditBalance = 45;
let totalPurchased = 100;

export const universignService = {
  // Get dashboard statistics
  getStats: async () => {
    // Simulate API delay
    await new Promise(resolve => setTimeout(resolve, 800));

    const total = mockSignatures.length;
    const signed = mockSignatures.filter(s => s.status === 'signed').length;
    const pending = mockSignatures.filter(s => ['sent', 'viewed', 'pending'].includes(s.status)).length;
    const refused = mockSignatures.filter(s => ['refused', 'expired'].includes(s.status)).length;
    const remindable = mockSignatures.filter(s => ['sent', 'viewed'].includes(s.status)).length;

    return {
      credits: {
        total: totalPurchased,
        consumed: totalPurchased - creditBalance,
        remaining: creditBalance,
        projectionDays: Math.floor(creditBalance / 2) // Assuming 2 signatures per day
      },
      signatures: {
        total,
        signed,
        pending,
        refused,
        remindable,
        conversionRate: total > 0 ? Math.round((signed / total) * 100) : 0
      }
    };
  },

  // Get consumption history for chart
  getConsumptionHistory: async (period = '30days') => {
    await new Promise(resolve => setTimeout(resolve, 600));
    
    // Generate mock history data
    const days = 30;
    const history = [];
    let cumulative = 0;
    
    for (let i = days; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const daily = Math.floor(Math.random() * 5);
      cumulative += daily;
      
      history.push({
        date: date.toISOString().split('T')[0],
        daily,
        cumulative
      });
    }
    
    return history;
  },

  // List all signatures
  getSignatures: async (filters = {}) => {
    await new Promise(resolve => setTimeout(resolve, 600));
    return [...mockSignatures].sort((a, b) => new Date(b.sentAt) - new Date(a.sentAt));
  },

  // Purchase credits
  purchaseCredits: async (amount) => {
    await new Promise(resolve => setTimeout(resolve, 1500));
    creditBalance += amount;
    totalPurchased += amount;
    return { success: true, newBalance: creditBalance };
  },

  // Send reminder
  sendReminder: async (signatureId) => {
    await new Promise(resolve => setTimeout(resolve, 1000));
    const sig = mockSignatures.find(s => s.id === signatureId);
    if (sig) {
      sig.remindersSent += 1;
      return { success: true, remindersSent: sig.remindersSent };
    }
    return { success: false };
  },

  // Update settings
  updateSettings: async (settings) => {
    await new Promise(resolve => setTimeout(resolve, 1000));
    return { success: true };
  }
};