"use client";

import React, { createContext, useContext, useState, useEffect } from "react";

interface UserProfile {
  name: string;
  level: number;
  xp: number;
  xpToNextLevel: number;
  streak: number;
  stepsToday: number;
  stepGoal: number;
  lytBalance: number;
}

interface Voucher {
  id: string;
  brand: string;
  logo: string;
  discount: string;
  lytCost: number;
  code: string;
  claimedAt: string;
}

interface UserContextType {
  profile: UserProfile;
  vouchers: Voucher[];
  addLyts: (amount: number) => void;
  spendLyts: (amount: number) => boolean;
  incrementSteps: (amount: number) => void;
  claimVoucher: (brand: string, discount: string, cost: number) => { success: boolean; code?: string };
}

const UserContext = createContext<UserContextType | undefined>(undefined);

export function UserProvider({ children }: { children: React.ReactNode }) {
  const [profile, setProfile] = useState<UserProfile>({
    name: "Alex Stark",
    level: 4,
    xp: 680,
    xpToNextLevel: 1000,
    streak: 5,
    stepsToday: 6420,
    stepGoal: 10000,
    lytBalance: 450,
  });

  const [vouchers, setVouchers] = useState<Voucher[]>([]);

  // Function to add LYTs and award XP
  const addLyts = (amount: number) => {
    setProfile((prev) => {
      const newBalance = prev.lytBalance + amount;
      const addedXp = amount * 2;
      let newXp = prev.xp + addedXp;
      let newLevel = prev.level;
      let newXpToNext = prev.xpToNextLevel;

      if (newXp >= newXpToNext) {
        newLevel += 1;
        newXp = newXp - newXpToNext;
        newXpToNext = Math.round(newXpToNext * 1.5);
      }

      return {
        ...prev,
        lytBalance: newBalance,
        xp: newXp,
        level: newLevel,
        xpToNextLevel: newXpToNext,
      };
    });
  };

  // Function to spend LYTs
  const spendLyts = (amount: number): boolean => {
    let success = false;
    setProfile((prev) => {
      if (prev.lytBalance >= amount) {
        success = true;
        return {
          ...prev,
          lytBalance: prev.lytBalance - amount,
        };
      }
      return prev;
    });
    return success;
  };

  // Function to update steps
  const incrementSteps = (amount: number) => {
    setProfile((prev) => {
      const newSteps = Math.min(25000, prev.stepsToday + amount);
      // Earn 1 LYT for every 500 steps taken
      const stepDiff = newSteps - prev.stepsToday;
      const lytReward = Math.floor(stepDiff / 500);

      return {
        ...prev,
        stepsToday: newSteps,
        lytBalance: prev.lytBalance + (lytReward > 0 ? lytReward : 0),
      };
    });
  };

  // Function to claim brand vouchers
  const claimVoucher = (brand: string, discount: string, cost: number) => {
    if (profile.lytBalance < cost) {
      return { success: false };
    }

    const claimSuccess = spendLyts(cost);
    if (!claimSuccess) return { success: false };

    // Generate a random alphanumeric code
    const generatedCode = Math.random().toString(36).substring(2, 8).toUpperCase() + "-" + cost;

    const newVoucher: Voucher = {
      id: Math.random().toString(36).substring(2, 9),
      brand,
      logo: `/images/logo-${brand.toLowerCase().replace(/\s+/g, "")}.png`,
      discount,
      lytCost: cost,
      code: generatedCode,
      claimedAt: new Date().toLocaleDateString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
      }),
    };

    setVouchers((prev) => [newVoucher, ...prev]);
    return { success: true, code: generatedCode };
  };

  return (
    <UserContext.Provider
      value={{
        profile,
        vouchers,
        addLyts,
        spendLyts,
        incrementSteps,
        claimVoucher,
      }}
    >
      {children}
    </UserContext.Provider>
  );
}

export function useUser() {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error("useUser must be used within a UserProvider");
  }
  return context;
}
