/**
 * Client-side storage utilities for signup data
 * Will be replaced with database storage later
 */

export interface SignupData {
  email: string;
  fullName: string;
  password?: string; // Not stored in production
  googleId?: string;
  plan?: string;
  createdAt: string;
}

export interface CompanyInfo {
  companyName: string;
  industry: string;
  companySize: string;
  gccCountry: string;
  phoneNumber: string;
  agentCount: string;
  agentUseCase: string;
  companyDescription: string;
  services: string[]; // Multi-select services offered by the company
}

export type PaymentStatus = 'not_initiated' | 'in_progress' | 'succeeded' | 'failed';

export interface PlanData {
  tierId: string;
  stripePriceId: string;
  billingPeriod: 'monthly' | 'yearly';
  currency: string;
}

export interface GoogleSignupData {
  email: string;
  name: string;
  googleId?: string;
}

export interface FullSignupData extends SignupData {
  companyInfo?: CompanyInfo;
  verified: boolean;
  verificationCode?: string;
  userId?: string; // User ID from registration
  plan?: PlanData; // Complete plan data (tier, price, billing period, currency)
  goals?: string[]; // Selected business goals
  paymentStatus?: PaymentStatus; // Payment lifecycle status
  paymentInitiatedAt?: string; // Timestamp when payment started
  paymentError?: string; // Last payment error message
  onboardingStep?: number; // Track which step user was on (1-7)
  isGoogleSignup?: boolean; // Flag indicating Google OAuth signup
  googleData?: GoogleSignupData; // Google user data for OTP verification
}

const STORAGE_KEY = 'mawidi_signup_data';
const STORAGE_EXPIRY_HOURS = 24;

export const signupStorage = {
  /**
   * Save signup data to localStorage
   */
  save(data: Partial<FullSignupData>): void {
    if (typeof window === 'undefined') return;

    try {
      const existing = this.get() || {};
      const updated = {
        ...existing,
        ...data,
        updatedAt: new Date().toISOString(),
      };

      localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
    } catch (error) {
      console.error('Error saving signup data:', error);
    }
  },

  /**
   * Get signup data from localStorage
   */
  get(): FullSignupData | null {
    if (typeof window === 'undefined') return null;

    try {
      const data = localStorage.getItem(STORAGE_KEY);
      if (!data) return null;

      const parsed = JSON.parse(data) as FullSignupData & { updatedAt?: string };

      // Check if data has expired
      if (parsed.updatedAt) {
        const expiryTime = new Date(parsed.updatedAt);
        expiryTime.setHours(expiryTime.getHours() + STORAGE_EXPIRY_HOURS);

        if (new Date() > expiryTime) {
          this.clear();
          return null;
        }
      }

      return parsed;
    } catch (error) {
      console.error('Error getting signup data:', error);
      return null;
    }
  },

  /**
   * Clear signup data from localStorage
   */
  clear(): void {
    if (typeof window === 'undefined') return;

    try {
      localStorage.removeItem(STORAGE_KEY);
    } catch (error) {
      console.error('Error clearing signup data:', error);
    }
  },

  /**
   * Update company info
   */
  saveCompanyInfo(companyInfo: CompanyInfo): void {
    const existing = this.get();
    if (existing) {
      this.save({ ...existing, companyInfo });
    }
  },

  /**
   * Mark email as verified
   */
  markVerified(): void {
    const existing = this.get();
    if (existing) {
      this.save({ ...existing, verified: true });
    }
  },

  /**
   * Track plan selection
   */
  savePlan(plan: PlanData): void {
    const existing = this.get();
    if (existing) {
      this.save({ ...existing, plan });
    }
  },

  /**
   * Track selected goals
   */
  saveGoals(goals: string[]): void {
    const existing = this.get();
    if (existing) {
      this.save({ ...existing, goals });
    }
  },

  /**
   * Set payment status and track when it started
   */
  setPaymentStatus(status: PaymentStatus, error?: string): void {
    const existing = this.get();
    if (existing) {
      const update: Partial<FullSignupData> = {
        paymentStatus: status,
      };

      // Track when payment initiated
      if (status === 'in_progress' && !existing.paymentInitiatedAt) {
        update.paymentInitiatedAt = new Date().toISOString();
      }

      // Clear error on successful payment
      if (status === 'succeeded') {
        update.paymentError = undefined;
      } else if (status === 'failed' && error) {
        update.paymentError = error;
      }

      this.save({ ...existing, ...update });
    }
  },

  /**
   * Get current payment status
   */
  getPaymentStatus(): PaymentStatus | null {
    const data = this.get();
    return data?.paymentStatus ?? null;
  },

  /**
   * Track current onboarding step (1-7)
   */
  setOnboardingStep(step: number): void {
    const existing = this.get();
    if (existing) {
      this.save({ ...existing, onboardingStep: step });
    }
  },

  /**
   * Get last completed onboarding step
   */
  getOnboardingStep(): number {
    const data = this.get();
    return data?.onboardingStep ?? 1; // Default to step 1
  },

  /**
   * Resume from last step if payment failed
   * Returns true if resumable (has payment error), false otherwise
   */
  canResume(): boolean {
    const data = this.get();
    return !!(data && data.paymentStatus === 'failed' && data.onboardingStep);
  },

  /**
   * Clear payment-related data after successful payment
   * Keeps signup data for dashboard/account setup but removes payment tracking
   */
  clearPaymentData(): void {
    const existing = this.get();
    if (existing) {
      // Keep: email, fullName, userId, verified, companyInfo, plan, goals
      // Clear: password, paymentStatus, paymentInitiatedAt, paymentError, onboardingStep
      const cleaned: Partial<FullSignupData> = {
        ...existing,
        password: undefined, // Never keep password in storage
        paymentStatus: undefined,
        paymentInitiatedAt: undefined,
        paymentError: undefined,
        onboardingStep: undefined,
        verificationCode: undefined, // Also clear OTP code
      };

      this.save(cleaned);
    }
  },

  /**
   * Get payment retry information after failure
   */
  getPaymentRetryInfo(): {
    lastError?: string;
    initiatedAt?: string;
    step: number;
  } | null {
    const data = this.get();
    if (!data || data.paymentStatus !== 'failed') return null;

    return {
      lastError: data.paymentError,
      initiatedAt: data.paymentInitiatedAt,
      step: data.onboardingStep ?? 5, // Return to goals selection step by default
    };
  },
};

