"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 { useLocale, useTranslations } from 'next-intl'
import Header from '@/components/Header'
import { Button } from '@/components/ui/button'
import { Database, ArrowLeft, Download, Clock, RefreshCw } 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 locale = useLocale()
  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
  const t = useTranslations('backup')

  useEffect(() => {
    if (authLoading) return
    if (!user) {
      router.push(`/${locale}/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)
      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 {
      // 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() as { filename?: string; sizeBytes?: number; createdAt?: string }
      const sizeBytes = Number(meta.sizeBytes) || 0
      const createdAt = meta.createdAt ? new Date(meta.createdAt) : new Date()
      const filename = meta.filename || `urbangamers_samp_backup_${createdAt.getTime()}.sql`
      const item: BackupItem = { id: `${createdAt.getTime()}`, filename, createdAt: createdAt.toISOString(), sizeBytes }
      setBackups(prev => {
        const next = [item, ...prev].slice(0, 6)
        try { (window as any).__saveSqlBackups?.(next, createdAt) } catch {}
        return next
      })
      setLastGeneratedAt(createdAt)
      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 {
      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 })
    }
  }

  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>
      <>
        <Header />
        <main className="min-h-screen pt-16 bg-gradient-to-b from-[#1E1E2E] via-[#002647] to-[#1E1E2E]">
          <section className="container mx-auto px-6 py-8">
            {/* Header + Actions (match Admin page) */}
            <div className="flex items-center justify-between mb-8">
              <div>
                <h1 className="text-4xl font-bold text-white mb-2">{t('title')}</h1>
                <p className="text-gray-400 text-lg">{t('subtitle')}</p>
              </div>
              <div className="flex items-center gap-3">
                <Button 
                  onClick={() => backups[0] && downloadBackup(backups[0])}
                  className="bg-[#0087FF]/20 hover:bg-[#0087FF]/30 text-[#8ab4ff] border border-[#0087FF]/30"
                >
                  <Download className="w-4 h-4 mr-2" />
                  {t('actions.downloadLatest')}
                </Button>
                <Button 
                  onClick={() => router.push(`/${locale}/admin`)}
                  variant="outline"
                  className="border-[#0087FF]/30 text-[#8ab4ff] hover:bg-[#0087FF]/10"
                >
                  <ArrowLeft className="w-4 h-4 mr-2" />
                  {t('actions.backToAdmin')}
                </Button>
              </div>
            </div>

            {/* Stat Cards (match Admin styles) */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
              <div className="bg-gradient-to-br from-[#0f1620] to-[#0c1320] rounded-2xl p-6 border border-[#0087FF]/20 shadow-lg">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-gray-400 text-sm mb-1">{t('cards.lastSize')}</p>
                    <p className="text-3xl 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-gradient-to-br from-[#0f1620] to-[#0c1320] rounded-2xl p-6 border border-[#0087FF]/20 shadow-lg">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-gray-400 text-sm mb-1">{t('cards.nextBackup')}</p>
                    <div className="flex items-center text-emerald-400 font-semibold">
                      <Clock className="w-4 h-4 mr-2" /> In {timeUntilNext}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Table (match Admin container styles) */}
              <div className="bg-gradient-to-br from-[#0f1620] to-[#0c1320] rounded-2xl p-6 border border-[#0087FF]/20 shadow-lg">
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h2 className="text-2xl font-bold text-white mb-1">{t('table.title')}</h2>
                  <p className="text-gray-400">{t('table.subtitle')}</p>
                </div>
              </div>
              <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">{t('table.filename')}</th>
                      <th className="py-2 px-2">{t('table.created')}</th>
                      <th className="py-2 px-2">{t('table.size')}</th>
                      <th className="py-2 px-2">{t('table.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-[#0c1320]/40">
                        <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-[#0087FF]/20 text-[#8ab4ff] border border-[#0087FF]/30 hover:bg-[#0087FF]/30 rounded-full px-3 py-1 text-xs">
                            <Download className="w-4 h-4 mr-1" /> {t('table.download')}
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </section>
        </main>

        {notification && (
          <Notification
            type={notification.type}
            title={notification.title}
            message={notification.message}
            duration={3500}
            isVisible={notification.isVisible}
            onClose={() => setNotification(null)}
          />
        )}
      </>
    </ProtectedRoute>
  )
}


