'use client'

import { useState, useEffect, useCallback } from 'react'
import { api } from '@/lib/api'
import {
  RefreshCw,
  Globe,
  CheckCircle2,
  AlertTriangle,
  XCircle,
  Loader2,
  Play,
  Clock,
  Database,
  TrendingUp,
} from 'lucide-react'
import clsx from 'clsx'

interface ZoneStatus {
  tld: string
  last_sync: string | null
  domain_count: number
  drops_today: number
  total_drops: number
  status: 'healthy' | 'stale' | 'never'
}

interface ZoneSyncStatus {
  zones: ZoneStatus[]
  summary: {
    total_zones: number
    healthy: number
    stale: number
    never_synced: number
    total_drops_today: number
    total_drops_all: number
  }
}

export function ZonesTab() {
  const [status, setStatus] = useState<ZoneSyncStatus | null>(null)
  const [loading, setLoading] = useState(true)
  const [syncingSwitch, setSyncingSwitch] = useState(false)
  const [syncingCzds, setSyncingCzds] = useState(false)
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)

  const fetchStatus = useCallback(async () => {
    try {
      const data = await api.request<ZoneSyncStatus>('/admin/zone-sync/status')
      setStatus(data)
    } catch (e) {
      console.error('Failed to fetch zone status:', e)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchStatus()
    // Auto-refresh every 30 seconds
    const interval = setInterval(fetchStatus, 30000)
    return () => clearInterval(interval)
  }, [fetchStatus])

  const triggerSwitchSync = async () => {
    if (syncingSwitch) return
    setSyncingSwitch(true)
    setMessage(null)
    try {
      await api.request('/admin/zone-sync/switch', { method: 'POST' })
      setMessage({ type: 'success', text: 'Switch.ch sync started! Check logs for progress.' })
      // Refresh status after a delay
      setTimeout(fetchStatus, 5000)
    } catch (e) {
      setMessage({ type: 'error', text: e instanceof Error ? e.message : 'Sync failed' })
    } finally {
      setSyncingSwitch(false)
    }
  }

  const triggerCzdsSync = async () => {
    if (syncingCzds) return
    setSyncingCzds(true)
    setMessage(null)
    try {
      await api.request('/admin/zone-sync/czds', { method: 'POST' })
      setMessage({ type: 'success', text: 'ICANN CZDS sync started (parallel mode)! Check logs for progress.' })
      // Refresh status after a delay
      setTimeout(fetchStatus, 5000)
    } catch (e) {
      setMessage({ type: 'error', text: e instanceof Error ? e.message : 'Sync failed' })
    } finally {
      setSyncingCzds(false)
    }
  }

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return 'Never'
    const date = new Date(dateStr)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const hours = Math.floor(diff / (1000 * 60 * 60))
    
    if (hours < 1) return 'Just now'
    if (hours < 24) return `${hours}h ago`
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
  }

  const getStatusIcon = (s: string) => {
    switch (s) {
      case 'healthy': return <CheckCircle2 className="w-4 h-4 text-accent" />
      case 'stale': return <AlertTriangle className="w-4 h-4 text-amber-400" />
      default: return <XCircle className="w-4 h-4 text-rose-400" />
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-8 h-8 text-accent animate-spin" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Summary Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white/[0.02] border border-white/[0.08] p-4">
          <div className="flex items-center gap-2 text-white/40 text-xs font-mono uppercase mb-2">
            <Globe className="w-4 h-4" />
            Zones
          </div>
          <div className="text-2xl font-bold text-white">{status?.summary.total_zones || 0}</div>
          <div className="text-xs text-white/30">
            {status?.summary.healthy || 0} healthy
          </div>
        </div>
        
        <div className="bg-white/[0.02] border border-white/[0.08] p-4">
          <div className="flex items-center gap-2 text-white/40 text-xs font-mono uppercase mb-2">
            <TrendingUp className="w-4 h-4" />
            Today
          </div>
          <div className="text-2xl font-bold text-accent">{status?.summary.total_drops_today?.toLocaleString() || 0}</div>
          <div className="text-xs text-white/30">drops detected</div>
        </div>
        
        <div className="bg-white/[0.02] border border-white/[0.08] p-4">
          <div className="flex items-center gap-2 text-white/40 text-xs font-mono uppercase mb-2">
            <Database className="w-4 h-4" />
            Total
          </div>
          <div className="text-2xl font-bold text-white">{status?.summary.total_drops_all?.toLocaleString() || 0}</div>
          <div className="text-xs text-white/30">drops in database</div>
        </div>
        
        <div className="bg-white/[0.02] border border-white/[0.08] p-4">
          <div className="flex items-center gap-2 text-white/40 text-xs font-mono uppercase mb-2">
            <Clock className="w-4 h-4" />
            Status
          </div>
          <div className="flex items-center gap-2">
            {status?.summary.stale || status?.summary.never_synced ? (
              <>
                <AlertTriangle className="w-5 h-5 text-amber-400" />
                <span className="text-amber-400 font-bold">Needs Attention</span>
              </>
            ) : (
              <>
                <CheckCircle2 className="w-5 h-5 text-accent" />
                <span className="text-accent font-bold">All Healthy</span>
              </>
            )}
          </div>
        </div>
      </div>

      {/* Action Buttons */}
      <div className="flex flex-wrap gap-4">
        <button
          onClick={triggerSwitchSync}
          disabled={syncingSwitch}
          className="flex items-center gap-2 px-4 py-3 bg-white/[0.05] border border-white/[0.08] text-white hover:bg-white/[0.08] transition-colors disabled:opacity-50"
        >
          {syncingSwitch ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
          Sync Switch.ch (.ch, .li)
        </button>
        
        <button
          onClick={triggerCzdsSync}
          disabled={syncingCzds}
          className="flex items-center gap-2 px-4 py-3 bg-accent/10 border border-accent/30 text-accent hover:bg-accent/20 transition-colors disabled:opacity-50"
        >
          {syncingCzds ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
          Sync ICANN CZDS (gTLDs)
        </button>
        
        <button
          onClick={fetchStatus}
          className="flex items-center gap-2 px-4 py-3 border border-white/[0.08] text-white/60 hover:text-white hover:bg-white/[0.05] transition-colors"
        >
          <RefreshCw className="w-4 h-4" />
          Refresh Status
        </button>
      </div>

      {/* Message */}
      {message && (
        <div className={clsx(
          "p-4 border",
          message.type === 'success' ? "bg-accent/10 border-accent/30 text-accent" : "bg-rose-500/10 border-rose-500/30 text-rose-400"
        )}>
          {message.text}
        </div>
      )}

      {/* Zone Table */}
      <div className="border border-white/[0.08] overflow-hidden">
        <div className="grid grid-cols-[80px_1fr_120px_120px_120px_100px] gap-4 px-4 py-3 bg-white/[0.02] text-xs font-mono text-white/40 uppercase tracking-wider border-b border-white/[0.08]">
          <div>TLD</div>
          <div>Last Sync</div>
          <div className="text-right">Domains</div>
          <div className="text-right">Today</div>
          <div className="text-right">Total Drops</div>
          <div className="text-center">Status</div>
        </div>
        
        <div className="divide-y divide-white/[0.04]">
          {status?.zones.map((zone) => (
            <div
              key={zone.tld}
              className="grid grid-cols-[80px_1fr_120px_120px_120px_100px] gap-4 px-4 py-3 items-center hover:bg-white/[0.02] transition-colors"
            >
              <div className="font-mono font-bold text-white">.{zone.tld}</div>
              <div className="text-sm text-white/60">{formatDate(zone.last_sync)}</div>
              <div className="text-right font-mono text-white/60">{zone.domain_count?.toLocaleString() || '-'}</div>
              <div className="text-right font-mono text-accent font-bold">{zone.drops_today?.toLocaleString() || '0'}</div>
              <div className="text-right font-mono text-white/40">{zone.total_drops?.toLocaleString() || '0'}</div>
              <div className="flex items-center justify-center gap-2">
                {getStatusIcon(zone.status)}
                <span className={clsx(
                  "text-xs font-mono uppercase",
                  zone.status === 'healthy' ? "text-accent" : zone.status === 'stale' ? "text-amber-400" : "text-rose-400"
                )}>
                  {zone.status}
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Schedule Info */}
      <div className="bg-white/[0.02] border border-white/[0.08] p-4">
        <h3 className="text-sm font-bold text-white mb-3">Automatic Sync Schedule</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
          <div className="flex items-start gap-3">
            <Clock className="w-4 h-4 text-white/40 mt-0.5" />
            <div>
              <div className="text-white font-medium">Switch.ch (.ch, .li)</div>
              <div className="text-white/40">Daily at 05:00 UTC (06:00 CH)</div>
            </div>
          </div>
          <div className="flex items-start gap-3">
            <Clock className="w-4 h-4 text-white/40 mt-0.5" />
            <div>
              <div className="text-white font-medium">ICANN CZDS (gTLDs)</div>
              <div className="text-white/40">Daily at 06:00 UTC (07:00 CH)</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
