'use client'

import React, { createContext, useContext, useReducer, useEffect } from 'react'
import { CuratedItem, UserProfile, SearchFilters, Badge } from '@/types'
import { mockItems, mockBadges } from '@/data/mockItems'

// State Interface
interface AppState {
  // Items & Search
  items: CuratedItem[]
  filteredItems: CuratedItem[]
  searchFilters: SearchFilters
  searchQuery: string
  
  // User & Profile
  user: UserProfile | null
  isAuthenticated: boolean
  
  // UI State
  loading: boolean
  error: string | null
  
  // Features
  wishlist: string[]
  recentlyViewed: string[]
}

// Action Types
type AppAction =
  | { type: 'SET_ITEMS'; payload: CuratedItem[] }
  | { type: 'SET_FILTERED_ITEMS'; payload: CuratedItem[] }
  | { type: 'SET_SEARCH_QUERY'; payload: string }
  | { type: 'SET_SEARCH_FILTERS'; payload: SearchFilters }
  | { type: 'SET_USER'; payload: UserProfile | null }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'TOGGLE_WISHLIST'; payload: string }
  | { type: 'ADD_TO_RECENTLY_VIEWED'; payload: string }
  | { type: 'CLEAR_SEARCH' }

// Initial State
const initialState: AppState = {
  items: [],
  filteredItems: [],
  searchFilters: {},
  searchQuery: '',
  user: null,
  isAuthenticated: false,
  loading: false,
  error: null,
  wishlist: [],
  recentlyViewed: []
}

// Reducer
function appReducer(state: AppState, action: AppAction): AppState {
  switch (action.type) {
    case 'SET_ITEMS':
      return {
        ...state,
        items: action.payload,
        filteredItems: action.payload
      }
    
    case 'SET_FILTERED_ITEMS':
      return {
        ...state,
        filteredItems: action.payload
      }
    
    case 'SET_SEARCH_QUERY':
      return {
        ...state,
        searchQuery: action.payload
      }
    
    case 'SET_SEARCH_FILTERS':
      return {
        ...state,
        searchFilters: action.payload
      }
    
    case 'SET_USER':
      return {
        ...state,
        user: action.payload,
        isAuthenticated: action.payload !== null,
        wishlist: action.payload?.wishlist || []
      }
    
    case 'SET_LOADING':
      return {
        ...state,
        loading: action.payload
      }
    
    case 'SET_ERROR':
      return {
        ...state,
        error: action.payload
      }
    
    case 'TOGGLE_WISHLIST':
      const itemId = action.payload
      const isWishlisted = state.wishlist.includes(itemId)
      const newWishlist = isWishlisted
        ? state.wishlist.filter(id => id !== itemId)
        : [...state.wishlist, itemId]
      
      return {
        ...state,
        wishlist: newWishlist,
        user: state.user ? {
          ...state.user,
          wishlist: newWishlist
        } : null
      }
    
    case 'ADD_TO_RECENTLY_VIEWED':
      const viewedItemId = action.payload
      const newRecentlyViewed = [
        viewedItemId,
        ...state.recentlyViewed.filter(id => id !== viewedItemId)
      ].slice(0, 10) // Keep only last 10
      
      return {
        ...state,
        recentlyViewed: newRecentlyViewed
      }
    
    case 'CLEAR_SEARCH':
      return {
        ...state,
        searchQuery: '',
        searchFilters: {},
        filteredItems: state.items
      }
    
    default:
      return state
  }
}

// Context
const AppContext = createContext<{
  state: AppState
  dispatch: React.Dispatch<AppAction>
  // Helper functions
  searchItems: (query: string, filters?: SearchFilters) => void
  toggleWishlist: (itemId: string) => void
  addToRecentlyViewed: (itemId: string) => void
  getItemById: (id: string) => CuratedItem | undefined
  getFeaturedItems: () => CuratedItem[]
  getItemsByCategory: (category: string) => CuratedItem[]
  checkBadgeProgress: (userId: string) => Badge[]
} | null>(null)

// Provider Component
export function AppProvider({ children }: { children: React.ReactNode }) {
  const [state, dispatch] = useReducer(appReducer, initialState)

  // Initialize data
  useEffect(() => {
    dispatch({ type: 'SET_ITEMS', payload: mockItems })
    
    // Load user from localStorage
    const savedUser = localStorage.getItem('curatedFindsUser')
    if (savedUser) {
      try {
        const user = JSON.parse(savedUser)
        dispatch({ type: 'SET_USER', payload: user })
      } catch (error) {
        console.error('Error loading user from localStorage:', error)
      }
    } else {
      // Create demo user
      const demoUser: UserProfile = {
        id: 'demo-user',
        email: 'demo@curatedfinds.com',
        username: 'CollectorDemo',
        level: 3,
        xp: 250,
        badges: [mockBadges[0], mockBadges[6]], // First Find + Daily Visitor
        collections: [],
        wishlist: ['1', '3'], // Pre-populate with some items
        streak: 5,
        preferences: {
          categories: ['photography', 'books'],
          priceRange: { min: 0, max: 500 },
          notifications: {
            email: true,
            push: false,
            priceAlerts: true,
            newFinds: true,
            weeklyDigest: true
          },
          privacy: {
            showCollections: true,
            showActivity: false
          }
        },
        joinDate: new Date('2024-11-01'),
        lastActive: new Date()
      }
      dispatch({ type: 'SET_USER', payload: demoUser })
    }
  }, [])

  // Save user to localStorage when it changes
  useEffect(() => {
    if (state.user) {
      localStorage.setItem('curatedFindsUser', JSON.stringify(state.user))
    }
  }, [state.user])

  // Helper Functions
  const searchItems = (query: string, filters: SearchFilters = {}) => {
    dispatch({ type: 'SET_SEARCH_QUERY', payload: query })
    dispatch({ type: 'SET_SEARCH_FILTERS', payload: filters })

    let filtered = [...state.items]

    // Text search
    if (query.trim()) {
      const searchTerm = query.toLowerCase()
      filtered = filtered.filter(item =>
        item.title.toLowerCase().includes(searchTerm) ||
        item.expertNotes.toLowerCase().includes(searchTerm) ||
        item.tags.some(tag => tag.toLowerCase().includes(searchTerm))
      )
    }

    // Category filter
    if (filters.category) {
      filtered = filtered.filter(item => item.category === filters.category)
    }

    // Price range filter
    if (filters.priceMin !== undefined) {
      filtered = filtered.filter(item => item.price >= filters.priceMin!)
    }
    if (filters.priceMax !== undefined) {
      filtered = filtered.filter(item => item.price <= filters.priceMax!)
    }

    // Condition filter
    if (filters.condition && filters.condition.length > 0) {
      filtered = filtered.filter(item => filters.condition!.includes(item.condition))
    }

    // Rarity filter
    if (filters.rarity && filters.rarity.length > 0) {
      filtered = filtered.filter(item => filters.rarity!.includes(item.rarity))
    }

    // Featured filter
    if (filters.featured) {
      filtered = filtered.filter(item => item.featured)
    }

    // Sorting
    switch (filters.sortBy) {
      case 'price-low':
        filtered.sort((a, b) => a.price - b.price)
        break
      case 'price-high':
        filtered.sort((a, b) => b.price - a.price)
        break
      case 'rarity':
        filtered.sort((a, b) => b.rarity - a.rarity)
        break
      case 'date':
      default:
        filtered.sort((a, b) => new Date(b.dateAdded).getTime() - new Date(a.dateAdded).getTime())
        break
    }

    dispatch({ type: 'SET_FILTERED_ITEMS', payload: filtered })
  }

  const toggleWishlist = (itemId: string) => {
    dispatch({ type: 'TOGGLE_WISHLIST', payload: itemId })
  }

  const addToRecentlyViewed = (itemId: string) => {
    dispatch({ type: 'ADD_TO_RECENTLY_VIEWED', payload: itemId })
  }

  const getItemById = (id: string) => {
    return state.items.find(item => item.id === id)
  }

  const getFeaturedItems = () => {
    return state.items.filter(item => item.featured)
  }

  const getItemsByCategory = (category: string) => {
    return state.items.filter(item => item.category === category)
  }

  const checkBadgeProgress = (userId: string): Badge[] => {
    if (!state.user) return []

    const earnedBadges: Badge[] = []
    const wishlistCount = state.user.wishlist.length

    // First Find badge
    if (wishlistCount >= 1 && !state.user.badges.find(b => b.id === 'first-find')) {
      earnedBadges.push(mockBadges.find(b => b.id === 'first-find')!)
    }

    // Category-specific badges
    const photoItems = state.user.wishlist.filter(id => {
      const item = getItemById(id)
      return item?.category === 'photography'
    }).length

    if (photoItems >= 10 && !state.user.badges.find(b => b.id === 'camera-collector')) {
      earnedBadges.push(mockBadges.find(b => b.id === 'camera-collector')!)
    }

    return earnedBadges
  }

  const contextValue = {
    state,
    dispatch,
    searchItems,
    toggleWishlist,
    addToRecentlyViewed,
    getItemById,
    getFeaturedItems,
    getItemsByCategory,
    checkBadgeProgress
  }

  return (
    <AppContext.Provider value={contextValue}>
      {children}
    </AppContext.Provider>
  )
}

// Hook to use the context
export function useApp() {
  const context = useContext(AppContext)
  if (!context) {
    throw new Error('useApp must be used within an AppProvider')
  }
  return context
}

export default AppContext