import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'
import type { AddRecord } from '../types'
import { loadRecords, saveRecords, generateId } from '../utils/storage'

interface RecordsContextValue {
  records: AddRecord[]
  addRecord: (record: Omit<AddRecord, 'id' | 'timestamp'>) => void
  deleteRecord: (id: string) => void
  clearRecords: () => void
  getRecordsByDateRange: (startDate: Date, endDate: Date) => AddRecord[]
  getStats: () => {
    totalRecords: number
    totalAdded: number
    totalSuccess: number
    totalFailed: number
    todayAdded: number
    weekAdded: number
  }
}

const RecordsContext = createContext<RecordsContextValue | null>(null)

export function RecordsProvider({ children }: { children: ReactNode }) {
  const [records, setRecords] = useState<AddRecord[]>([])

  // Load records from localStorage on mount
  useEffect(() => {
    const savedRecords = loadRecords()
    setRecords(savedRecords)
  }, [])

  const addRecord = useCallback((record: Omit<AddRecord, 'id' | 'timestamp'>) => {
    const newRecord: AddRecord = {
      ...record,
      id: generateId(),
      timestamp: new Date().toISOString(),
    }

    setRecords((prev) => {
      const updated = [newRecord, ...prev]
      saveRecords(updated)
      return updated
    })
  }, [])

  const deleteRecord = useCallback((id: string) => {
    setRecords((prev) => {
      const updated = prev.filter((r) => r.id !== id)
      saveRecords(updated)
      return updated
    })
  }, [])

  const clearRecords = useCallback(() => {
    setRecords([])
    saveRecords([])
  }, [])

  const getRecordsByDateRange = useCallback(
    (startDate: Date, endDate: Date): AddRecord[] => {
      return records.filter((record) => {
        const recordDate = new Date(record.timestamp)
        return recordDate >= startDate && recordDate <= endDate
      })
    },
    [records]
  )

  const getStats = useCallback(() => {
    const now = new Date()
    const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const weekStart = new Date(todayStart)
    weekStart.setDate(weekStart.getDate() - 7)

    const todayRecords = records.filter((r) => new Date(r.timestamp) >= todayStart)
    const weekRecords = records.filter((r) => new Date(r.timestamp) >= weekStart)

    return {
      totalRecords: records.length,
      totalAdded: records.reduce((sum, r) => sum + r.total, 0),
      totalSuccess: records.reduce((sum, r) => sum + r.success, 0),
      totalFailed: records.reduce((sum, r) => sum + r.failed, 0),
      todayAdded: todayRecords.reduce((sum, r) => sum + r.success, 0),
      weekAdded: weekRecords.reduce((sum, r) => sum + r.success, 0),
    }
  }, [records])

  return (
    <RecordsContext.Provider
      value={{
        records,
        addRecord,
        deleteRecord,
        clearRecords,
        getRecordsByDateRange,
        getStats,
      }}
    >
      {children}
    </RecordsContext.Provider>
  )
}

export function useRecordsContext(): RecordsContextValue {
  const context = useContext(RecordsContext)
  if (!context) {
    throw new Error('useRecordsContext must be used within a RecordsProvider')
  }
  return context
}
