"use client"

import { useEffect, useMemo, useRef, useState } from 'react'
import ProtectedRoute from '@/components/ProtectedRoute'
import { useAuth } from '@/contexts/AuthContext'
import { authFetch } from '@/lib/fetchAuth'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Database, ArrowLeft, Download, RefreshCw, Clock, Users, Ban, Activity, Settings, Coins } from 'lucide-react'
import Notification from '@/components/Notification'

interface BackupItem {
  id: string
  filename: string
  createdAt: string
  sizeBytes: number
}

export default function SqlAutoSavePage() {
  const { user, loading: authLoading } = useAuth()
  const router = useRouter()
  const [isAdmin, setIsAdmin] = useState<boolean>(false)
  const [loading, setLoading] = useState<boolean>(true)
  const [notification, setNotification] = useState<any>(null)
  const [backups, setBackups] = useState<BackupItem[]>([])
  const [lastGeneratedAt, setLastGeneratedAt] = useState<Date>(new Date())
  const secondTickerRef = useRef<NodeJS.Timeout | null>(null)
  const [now, setNow] = useState<number>(Date.now())
  const isRunningRef = useRef<boolean>(false)
  const PERIOD_MS = 5 * 60 * 1000 // 5 minutes

  useEffect(() => {
    if (authLoading) return
    if (!user) {
      router.push('/login')
      return
    }
    checkAdmin(user.id)
  }, [authLoading, user])

  useEffect(() => {
    if (!isAdmin) return

    const STORAGE_KEY = 'sqlAutoBackups'
    const loadData = () => {
      try {
        const raw = localStorage.getItem(STORAGE_KEY)
        if (!raw) return { ok: false, items: [], lastAt: null as Date | null }
        const parsed = JSON.parse(raw)
        const items: BackupItem[] = Array.isArray(parsed.backups) ? parsed.backups : []
        const lastAt = parsed.lastGeneratedAt ? new Date(parsed.lastGeneratedAt) : null
        return { ok: true, items, lastAt }
      } catch {
        return { ok: false, items: [], lastAt: null as Date | null }
      }
    }

    const save = (items: BackupItem[], lastAt: Date) => {
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify({ backups: items, lastGeneratedAt: lastAt.toISOString() }))
      } catch {}
    }
    ;(window as any).__saveSqlBackups = save

    const { ok, items, lastAt } = loadData()
    if (ok) {
      setBackups(items)
      if (lastAt) setLastGeneratedAt(lastAt)
    } else {
      // No previous state, create an initial backup immediately
      createBackup()
    }
  }, [isAdmin])

  // independent 1-second ticker: updates countdown and triggers backup when period elapsed
  useEffect(() => {
    if (!isAdmin) return
    if (secondTickerRef.current) clearInterval(secondTickerRef.current)
    secondTickerRef.current = setInterval(() => {
      const current = Date.now()
      setNow(current)
      // Fire with a small safety threshold so it doesn't hover at 00:00
      if (!isRunningRef.current && current - lastGeneratedAt.getTime() >= (PERIOD_MS - 500)) {
        isRunningRef.current = true
        createBackup().finally(() => {
          isRunningRef.current = false
        })
      }
    }, 1000)
    return () => { if (secondTickerRef.current) clearInterval(secondTickerRef.current) }
  }, [isAdmin, lastGeneratedAt])

  const checkAdmin = async (userId: number) => {
    try {
      const res = await authFetch(`/api/admin/is-admin`)
      const data = await res.json()
      setIsAdmin(!!data?.isAdmin)
    } finally {
      setLoading(false)
    }
  }

  const formatBytes = (bytes: number) => {
    if (!bytes || bytes <= 0) return '-'
    const mb = bytes / (1024 * 1024)
    return `${mb.toFixed(2)} MB`
  }

  const createBackup = async () => {
    try {
      const started = new Date()
      // Ask server to (re)build cached dump now and return meta
      const res = await authFetch('/api/admin/export-database?meta=1&rebuild=1', { method: 'GET', headers: { 'Cache-Control': 'no-cache' } })
      if (!res.ok) throw new Error(`Export failed: ${res.status}`)
      const meta = await res.json()
      const sizeBytes = Number(meta.sizeBytes) || 0
      const stamp = new Date()
      const yyyy = stamp.getFullYear()
      const mm = String(stamp.getMonth() + 1).padStart(2, '0')
      const dd = String(stamp.getDate()).padStart(2, '0')
      const HH = String(stamp.getHours()).padStart(2, '0')
      const MM = String(stamp.getMinutes()).padStart(2, '0')
      const SS = String(stamp.getSeconds()).padStart(2, '0')
      const filename = `owl_gaming_auto_backup_${yyyy}-${mm}-${dd}_${HH}-${MM}-${SS}.sql`
      const item: BackupItem = { id: `${stamp.getTime()}`, filename, createdAt: stamp.toISOString(), sizeBytes }
      setBackups(prev => {
        const next = [item, ...prev].slice(0, 6)
        try { (window as any).__saveSqlBackups?.(next, stamp) } catch {}
        return next
      })
      // Reset timer to when the backup finished saving
      setLastGeneratedAt(stamp)
      setNow(Date.now())
      setNotification({ type: 'success', title: 'New backup created', message: `${formatBytes(sizeBytes)} • ${filename}`, isVisible: true })
    } catch (e) {
      setNotification({ type: 'error', title: 'Auto backup failed', message: 'Could not create backup.', isVisible: true })
    }
  }

  const timeUntilNext = useMemo(() => {
    const next = lastGeneratedAt.getTime() + PERIOD_MS
    const diff = Math.max(0, next - now)
    const mins = Math.floor(diff / 60000)
    const secs = Math.floor((diff % 60000) / 1000)
    const m = String(mins).padStart(2, '0')
    const s = String(secs).padStart(2, '0')
    return `${m}:${s}`
  }, [lastGeneratedAt, now])

  const downloadBackup = async (item: BackupItem) => {
    try {
      // Download cached dump quickly
      const res = await authFetch('/api/admin/export-database', { method: 'GET', headers: { 'Cache-Control': 'no-cache' } })
      if (!res.ok) throw new Error('download-failed')
      const blob = await res.blob()
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = item.filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } catch (e) {
      setNotification({ type: 'error', title: 'Download failed', message: 'Could not download backup.', isVisible: true })
    }
  }

  // removed manual save function

  if (loading) return null
  if (!isAdmin) return (
    <ProtectedRoute>
      <main className="min-h-screen bg-gradient-to-b from-black via-gray-900 to-black p-6">
        <div className="max-w-6xl mx-auto text-center text-gray-300">You do not have admin permissions.</div>
      </main>
    </ProtectedRoute>
  )

  return (
    <ProtectedRoute>
      <div className="min-h-screen bg-gradient-to-b from-black via-gray-900 to-black flex">
        {/* Left Sidebar */}
        <div className="w-64 bg-black/80 border-r border-gray-800/50 p-6 space-y-4">
          <div className="flex items-center space-x-3 mb-8">
            <div className="w-10 h-10 bg-green-600 rounded-xl flex items-center justify-center">
              <Database className="w-5 h-5 text-white" />
            </div>
            <div>
              <h2 className="text-lg font-bold text-white">Admin Panel</h2>
              <p className="text-xs text-gray-400">OwlGaming</p>
            </div>
          </div>

          {/* Navigation Buttons */}
          <div className="space-y-2">
            <Button 
              variant="ghost" 
              onClick={() => router.push('/admin')}
              className="w-full justify-start bg-gray-800/60 text-gray-300 border border-gray-700/50 hover:bg-gray-700/60"
            >
              <Users className="w-4 h-4 mr-3" />
              Dashboard
            </Button>

            <Button 
              variant="ghost" 
              onClick={() => router.push('/admin/bans')}
              className="w-full justify-start bg-gray-800/60 text-gray-300 border border-gray-700/50 hover:bg-gray-700/60"
            >
              <Ban className="w-4 h-4 mr-3" />
              Bans Management
            </Button>

            <Button 
              variant="ghost" 
              className="w-full justify-start bg-gray-800/60 text-gray-300 border border-gray-700/50 hover:bg-gray-700/60"
            >
              <Activity className="w-4 h-4 mr-3" />
              Server Stats
            </Button>

            <Button 
              variant="ghost" 
              className="w-full justify-start bg-gray-800/60 text-gray-300 border border-gray-700/50 hover:bg-gray-700/60"
            >
              <Database className="w-4 h-4 mr-3" />
              Database Tools
            </Button>

            <Button 
              variant="ghost" 
              className="w-full justify-start bg-green-600/20 text-green-400 border border-green-600/30 hover:bg-green-600/30"
            >
              <Database className="w-4 h-4 mr-3" />
              Database Backup
            </Button>

            <Button 
              variant="ghost" 
              onClick={() => router.push('/admin/points')}
              className="w-full justify-start bg-gray-800/60 text-gray-300 border border-gray-700/50 hover:bg-gray-700/60"
            >
              <Coins className="w-4 h-4 mr-3" />
              Coins Manager
            </Button>

            <Button 
              variant="ghost" 
              className="w-full justify-start bg-gray-800/60 text-gray-300 border border-gray-700/50 hover:bg-gray-700/60"
            >
              <Settings className="w-4 h-4 mr-3" />
              Settings
            </Button>
          </div>
        </div>

        {/* Main Content */}
        <div className="flex-1 p-6">
          <div className="max-w-6xl mx-auto space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
              <div>
                <h1 className="text-3xl font-bold text-white">Database Backup</h1>
                <p className="text-gray-400 text-sm">Automatic export every 5 minutes. Only the last 6 are kept.</p>
              </div>
              
              <Button 
                onClick={() => router.push('/admin')}
                variant="outline"
                className="border-gray-600 text-gray-300 hover:bg-gray-800 hover:text-white"
              >
                <ArrowLeft className="w-4 h-4 mr-2" />
                Back to Admin
              </Button>
            </div>

            {/* Stats */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="bg-black/60 rounded-2xl p-4 border border-gray-700/50">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-gray-400 text-sm">Last Backup Size</p>
                    <p className="text-2xl font-bold text-white">{formatBytes(backups[0]?.sizeBytes || 0)}</p>
                  </div>
                  <div className="w-12 h-12 bg-blue-600/20 rounded-xl flex items-center justify-center">
                    <Database className="w-6 h-6 text-blue-400" />
                  </div>
                </div>
              </div>

              <div className="bg-black/60 rounded-2xl p-4 border border-gray-700/50">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-gray-400 text-sm">Next Backup</p>
                    <div className="flex items-center text-green-400 font-semibold">
                      <Clock className="w-4 h-4 mr-2" /> In {timeUntilNext}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Current backup */}
            <div className="bg-black/60 rounded-2xl p-4 border border-gray-700/50">
              <h3 className="text-lg font-semibold text-white mb-2">Backups (last 30 minutes)</h3>
              <p className="text-sm text-gray-400 mb-4">One backup every 5 minutes. Only the last 6 are kept.</p>
              <div className="overflow-x-auto">
                <table className="w-full text-left">
                  <thead>
                    <tr className="text-gray-400 text-xs">
                      <th className="py-2 px-2">Filename</th>
                      <th className="py-2 px-2">Created</th>
                      <th className="py-2 px-2">Size</th>
                      <th className="py-2 px-2">Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    {backups.map((b) => (
                      <tr key={b.id} className="text-gray-200 text-sm border-t border-gray-800/60 hover:bg-gray-800/20">
                        <td className="py-2 px-2 font-mono text-xs">{b.filename}</td>
                        <td className="py-2 px-2">{new Date(b.createdAt).toLocaleString()}</td>
                        <td className="py-2 px-2">{formatBytes(b.sizeBytes)}</td>
                        <td className="py-2 px-2">
                          <Button onClick={() => downloadBackup(b)} className="bg-blue-600/20 text-blue-400 border border-blue-600/30 hover:bg-blue-600/30 rounded-full px-3 py-1 text-xs">
                            <Download className="w-4 h-4 mr-1" /> Download
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        {notification && (
          <Notification
            type={notification.type}
            title={notification.title}
            message={notification.message}
            duration={3500}
            isVisible={notification.isVisible}
            onClose={() => setNotification(null)}
          />
        )}
      </div>
    </ProtectedRoute>
  )
}


