"use client"

import { useState, useEffect, useRef, useCallback } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import {
  ArrowLeft,
  Loader2,
  Coins,
  Trophy,
  Smartphone,
  Download,
  Play,
  Wallet,
  Clock,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { useToast } from "@/hooks/use-toast"
import { SPIN_SEGMENTS } from "@/lib/spin-segments"
import { waitForInterstitialCompletion } from "@/lib/interstitial"

const PLAY_STORE_URL = "https://play.google.com/store/apps/details?id=ng.affil.cweb"

const SEGMENT_ANGLE = 360 / SPIN_SEGMENTS.length

interface SpinStatus {
  authenticated: boolean
  enabled: boolean
  spinPoints: number
  unlocked: boolean
  canSpinFree: boolean
  bonusUnlocked: boolean
  canClaimBonusAd: boolean
  bonusPoints: number
  convertThreshold: number
  canConvert: boolean
  lastSpinAt: string | null
  nextSpinAt: string | null
  nextBonusAt: string | null
}

export default function SpinPage() {
  const { toast } = useToast()
  const router = useRouter()

  const [status, setStatus] = useState<SpinStatus | null>(null)
  const [loading, setLoading] = useState(true)
  const [isWebView, setIsWebView] = useState(true)
  const [rotation, setRotation] = useState(0)
  const rotationRef = useRef(0)
  const [result, setResult] = useState<{ points: number; label: string } | null>(null)
  const [spinning, setSpinning] = useState(false)
  const [waitingForAd, setWaitingForAd] = useState(false)
  const [gatewayAdPlaying, setGatewayAdPlaying] = useState(false)
  const [watchingBonusAd, setWatchingBonusAd] = useState(false)
  const [converting, setConverting] = useState(false)
  const [timeUntilReset, setTimeUntilReset] = useState("")
  const adAutoTriggeredRef = useRef(false)
  const rafRef = useRef<number | null>(null)

  const loadStatus = useCallback(async () => {
    try {
      const res = await fetch("/api/spin/status", { cache: "no-store" })
      if (res.status === 401) {
        setStatus(null)
        return
      }
      const data = await res.json()
      setStatus(data)
    } catch (e) {
      console.error("Spin status error:", e)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    const inWebView = typeof window !== "undefined" && (window as any).Android !== undefined
    setIsWebView(inWebView)
    loadStatus()
  }, [loadStatus])

  const triggerInterstitial = useCallback((): Promise<void> | null => {
    const w = window as any
    if (w.Android && typeof w.Android.showInterstitial === "function") {
      const done = waitForInterstitialCompletion()
      w.Android.showInterstitial()
      return done
    }
    return null
  }, [])

  const unlockAfterAd = useCallback(
    async (type: "gateway" | "bonus", done: Promise<void>) => {
      setWaitingForAd(true)
      if (type === "gateway") setGatewayAdPlaying(true)
      try {
        // Wait for the native interstitial to complete (with a fallback timeout).
        await done
        const res = await fetch("/api/spin/unlock", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ type }),
        })
        if (res.ok) {
          await loadStatus()
        } else {
          const data = await res.json().catch(() => ({}))
          toast({ title: "Error", description: data.error || "Failed to unlock", variant: "destructive" })
        }
      } catch {
        toast({ title: "Error", description: "Failed to unlock your spin. Please try again.", variant: "destructive" })
      } finally {
        setWaitingForAd(false)
        setGatewayAdPlaying(false)
      }
    },
    [loadStatus, toast],
  )

  const handleUnlock = useCallback(async () => {
    const done = triggerInterstitial()
    if (!done) {
      toast({
        title: "Mobile App Only",
        description: "Interstitial ads are only available in the Affiliate+ mobile app.",
        variant: "destructive",
      })
      return
    }
    await unlockAfterAd("gateway", done)
  }, [unlockAfterAd, toast, triggerInterstitial])

  const handleBonusUnlock = async () => {
    const w = window as any
    if (!w.Android || typeof w.Android.showSpinBonusRewarded !== "function") {
      toast({
        title: "Mobile App Only",
        description: "Rewarded ads are only available in the Affiliate+ mobile app.",
        variant: "destructive",
      })
      return
    }
    setWatchingBonusAd(true)
    w.Android.showSpinBonusRewarded()
  }

  const segmentIndexForPoints = useCallback((points: number) => {
    let idx = SPIN_SEGMENTS.findIndex((s) => s.points === points)
    if (idx >= 0) return idx
    let best = 0
    let bestDiff = Infinity
    SPIN_SEGMENTS.forEach((s, i) => {
      const d = Math.abs(s.points - points)
      if (d < bestDiff) {
        bestDiff = d
        best = i
      }
    })
    return best
  }, [])

  const animateSpin = useCallback((segmentIndex: number, onDone: () => void) => {
    if (rafRef.current) cancelAnimationFrame(rafRef.current)
    const targetMod = (360 - (segmentIndex * SEGMENT_ANGLE + SEGMENT_ANGLE / 2)) % 360
    const currentMod = ((rotationRef.current % 360) + 360) % 360
    let delta = targetMod - currentMod
    if (delta < 0) delta += 360
    const start = rotationRef.current
    const end = start + 360 * 6 + delta
    const duration = 5000
    const startTime = performance.now()
    // Ease-out: starts fast, decelerates gradually into the target segment.
    const easeOut = (t: number) => 1 - Math.pow(1 - t, 4)
    const step = (now: number) => {
      const t = Math.min(1, (now - startTime) / duration)
      const value = start + (end - start) * easeOut(t)
      rotationRef.current = value
      setRotation(value)
      if (t < 1) {
        rafRef.current = requestAnimationFrame(step)
      } else {
        rafRef.current = null
        onDone()
      }
    }
    rafRef.current = requestAnimationFrame(step)
  }, [])

  const finishSpin = (points: number, label: string) => {
    setResult({ points, label })
    setSpinning(false)
    loadStatus()
  }

  const doBaseSpin = async () => {
    if (!status?.canSpinFree || spinning) return
    setSpinning(true)
    setResult(null)
    try {
      const res = await fetch("/api/spin/play", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ type: "base" }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)

      const points = data.points || 0
      const idx = segmentIndexForPoints(points)
      animateSpin(idx, () => finishSpin(points, `${points.toLocaleString()} pts`))
    } catch (e: any) {
      setSpinning(false)
      toast({ title: "Error", description: e.message, variant: "destructive" })
      loadStatus()
    }
  }

  const doBonusSpin = async () => {
    if (!status?.bonusUnlocked || spinning) return
    setSpinning(true)
    setResult(null)
    try {
      const res = await fetch("/api/spin/play", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ type: "bonus" }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)

      const points = data.points || 0
      const idx = segmentIndexForPoints(points)
      animateSpin(idx, () => finishSpin(points, `${points.toLocaleString()} pts`))
    } catch (e: any) {
      setSpinning(false)
      toast({ title: "Error", description: e.message, variant: "destructive" })
      loadStatus()
    }
  }

  // Always play the gateway interstitial when the user opens the Spin Room,
  // before the page becomes accessible, regardless of spin/cooldown state.
  useEffect(() => {
    if (loading || !isWebView || !status) return
    if (!status.enabled) return
    if (adAutoTriggeredRef.current) return
    adAutoTriggeredRef.current = true
    handleUnlock()
  }, [loading, isWebView, status, handleUnlock])

  // Live countdown until the user's next daily spin becomes available.
  useEffect(() => {
    if (!status?.nextSpinAt) {
      setTimeUntilReset("")
      return
    }
    const tick = () => {
      const diff = new Date(status.nextSpinAt!).getTime() - Date.now()
      if (diff <= 0) {
        setTimeUntilReset("")
        loadStatus()
        return
      }
      const h = Math.floor(diff / 3600000)
      const m = Math.floor((diff % 3600000) / 60000)
      const s = Math.floor((diff % 60000) / 1000)
      setTimeUntilReset(`${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`)
    }
    tick()
    const id = setInterval(tick, 1000)
    return () => clearInterval(id)
  }, [status?.nextSpinAt, loadStatus])

  // Cancel any in-flight wheel animation on unmount.
  useEffect(() => {
    return () => {
      if (rafRef.current) cancelAnimationFrame(rafRef.current)
    }
  }, [])

  // Listen for the native rewarded-ad result for the bonus spin.
  useEffect(() => {
    const handleRewardEvent = (event: Event) => {
      const detail = (event as CustomEvent<any>).detail || {}
      if (detail.rewardType !== "spin_bonus") return
      const status = detail.status || ""
      switch (status) {
        case "reward-success":
          setWatchingBonusAd(false)
          loadStatus()
          toast({ title: "Bonus Unlocked", description: detail.message || "Your bonus spin is ready!" })
          break
        case "reward-processing":
          toast({ title: "Ad Complete", description: detail.message || "Processing your bonus spin..." })
          break
        case "dismissed":
        case "unavailable":
        case "reward-error":
          setWatchingBonusAd(false)
          toast({ title: "Ad not completed", description: detail.message || "Watch the full ad to unlock your bonus spin.", variant: "destructive" })
          break
      }
    }
    window.addEventListener("affiliateplus-reward-event", handleRewardEvent as EventListener)
    return () => window.removeEventListener("affiliateplus-reward-event", handleRewardEvent as EventListener)
  }, [loadStatus, toast])

  const handleConvert = async () => {
    setConverting(true)
    try {
      const res = await fetch("/api/spin/convert", { method: "POST" })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      toast({ title: "💸 Converted!", description: data.message })
      loadStatus()
    } catch (e: any) {
      toast({ title: "Failed", description: e.message, variant: "destructive" })
    } finally {
      setConverting(false)
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-purple-50 via-white to-amber-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600"></div>
      </div>
    )
  }

  if (!status) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-purple-50 via-white to-amber-50 flex flex-col items-center justify-center px-4 text-center">
        <div className="text-5xl mb-4">🎡</div>
        <h1 className="text-xl font-extrabold text-gray-900 mb-2">Sign in to Spin</h1>
        <p className="text-gray-500 text-sm mb-6">Login to unlock your daily spin and win points.</p>
        <Button onClick={() => router.push(`/login?next=${encodeURIComponent("/spin")}`)} className="bg-purple-600 hover:bg-purple-700">
          Login
        </Button>
      </div>
    )
  }

  if (!isWebView) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-purple-50 via-white to-amber-50 flex flex-col items-center justify-center px-4 text-center">
        <div className="max-w-md">
          <div className="mx-auto w-24 h-24 bg-gradient-to-br from-purple-400 to-amber-400 rounded-3xl flex items-center justify-center mb-6 shadow-xl">
            <Smartphone className="h-12 w-12 text-white" />
          </div>
          <h1 className="text-2xl font-extrabold text-gray-900 mb-3">Mobile Only 🎡</h1>
          <p className="text-gray-500 mb-2">Spin &amp; Win is available exclusively on the Affiliate+ mobile app.</p>
          <p className="text-xs text-gray-400 mb-8">Watch a short ad to unlock your daily spin and win points!</p>
          <a href={PLAY_STORE_URL} target="_blank" rel="noopener noreferrer" className="inline-block">
            <Button className="bg-green-600 hover:bg-green-700 text-white h-14 px-8 rounded-2xl font-bold text-lg shadow-lg shadow-green-200 gap-2">
              <Download className="h-5 w-5" /> Get on Play Store
            </Button>
          </a>
        </div>
      </div>
    )
  }

  if (!status.enabled) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-purple-50 via-white to-amber-50 flex flex-col items-center justify-center px-4 text-center">
        <div className="text-5xl mb-4">🚧</div>
        <h1 className="text-xl font-extrabold text-gray-900 mb-2">Spin &amp; Win is temporarily unavailable</h1>
        <p className="text-gray-500 text-sm">Please check back later.</p>
      </div>
    )
  }

  const spinPoints = status.spinPoints || 0
  // Bonus spin is a "try again" offer shown only after the user completes
  // their first spin of the day (daily cooldown is now active).
  const hasSpunToday = !!status.nextSpinAt && new Date(status.nextSpinAt).getTime() > Date.now()
  const convertThreshold = status.convertThreshold ?? 10000
  const wheelBackground = `conic-gradient(${SPIN_SEGMENTS.map(
    (s, i) => `${s.color} ${i * SEGMENT_ANGLE}deg ${(i + 1) * SEGMENT_ANGLE}deg`,
  ).join(", ")})`

  return (
    <div className="min-h-screen bg-gradient-to-b from-purple-50 via-white to-amber-50 flex flex-col">
      {/* Header */}
      <div className="bg-white/80 backdrop-blur-md border-b sticky top-0 z-30">
        <div className="max-w-2xl mx-auto px-4 h-14 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Link href="/">
              <Button variant="ghost" size="icon" className="h-9 w-9">
                <ArrowLeft className="h-5 w-5" />
              </Button>
            </Link>
            <h1 className="font-bold text-gray-900 flex items-center gap-2">
              <Trophy className="h-5 w-5 text-purple-600" />Spin &amp; Win
            </h1>
          </div>
          <div className="flex items-center gap-2 bg-amber-50 rounded-full px-3 py-1.5 border border-amber-200">
            <Coins className="h-4 w-4 text-amber-500" />
            <span className="text-sm font-bold text-amber-700">{spinPoints.toLocaleString()} pts</span>
          </div>
        </div>
      </div>

      <div className="flex-1 max-w-2xl mx-auto w-full px-4 py-6 space-y-5 overflow-y-auto">
        {/* Wheel */}
        <div className="relative mx-auto w-72 h-72 md:w-80 md:h-80">
          {/* Pointer */}
          <div className="absolute -top-1 left-1/2 -translate-x-1/2 z-20 w-0 h-0 border-l-[14px] border-r-[14px] border-t-[22px] border-l-transparent border-r-transparent border-t-red-500 drop-shadow" />
          {/* Wheel */}
          <div
            className="absolute inset-0 rounded-full border-8 border-white shadow-xl"
            style={{ background: wheelBackground, transform: `rotate(${rotation}deg)` }}
          >
            {SPIN_SEGMENTS.map((s, i) => {
              const angle = i * SEGMENT_ANGLE + SEGMENT_ANGLE / 2
              return (
                <div
                  key={i}
                  className="absolute inset-0 flex items-start justify-center"
                  style={{ transform: `rotate(${angle}deg)` }}
                >
                  <span className="mt-4 text-white font-bold text-[11px] drop-shadow">{s.label}</span>
                </div>
              )
            })}
          </div>
          {/* Center hub */}
          <div className="absolute inset-0 m-auto w-24 h-24 rounded-full bg-white shadow-inner flex items-center justify-center z-10">
            <span className="text-center font-extrabold text-purple-700 text-sm leading-tight px-1">
              {result ? result.label : spinning ? "..." : "SPIN"}
            </span>
          </div>
        </div>

        {/* Status text */}
        <div className="text-center space-y-2">
          {result && (
            <p className={`text-lg font-extrabold ${result.points > 0 ? "text-emerald-600" : "text-gray-500"}`}>
              {result.points > 0 ? `You won ${result.label}! 🎉` : "Better luck next time!"}
            </p>
          )}

          {status.canSpinFree && (
            <div className="inline-flex items-center gap-2 bg-green-50 border border-green-200 rounded-full px-4 py-1.5">
              <Clock className="h-4 w-4 text-green-600" />
              <span className="text-xs font-semibold text-green-700">Daily spin available now!</span>
            </div>
          )}

          {!status.canSpinFree && status.lastSpinAt && (
            <div className="space-y-1">
              <div className="inline-flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-full px-4 py-1.5">
                <Clock className="h-4 w-4 text-amber-500" />
                <span className="text-xs font-medium text-amber-700">Come back in 24 hours!</span>
              </div>
              {timeUntilReset && (
                <div className="text-xs text-gray-500 font-mono">
                  Available in <span className="font-bold text-purple-600">{timeUntilReset}</span>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Action buttons */}
        <div className="space-y-3">
          {status.canSpinFree && (
            <Button
              onClick={doBaseSpin}
              disabled={spinning || waitingForAd}
              className="w-full h-12 rounded-xl font-bold bg-purple-600 hover:bg-purple-700 text-white"
            >
              {spinning ? <Loader2 className="h-5 w-5 animate-spin mr-2" /> : <Trophy className="h-5 w-5 mr-2" />}
              Spin Now
            </Button>
          )}

          {hasSpunToday && status.canClaimBonusAd && !status.bonusUnlocked && (
            <Button
              onClick={handleBonusUnlock}
              disabled={watchingBonusAd || spinning}
              variant="outline"
              className="w-full h-12 rounded-xl font-bold border-purple-500 text-purple-600 hover:bg-purple-50"
            >
              {watchingBonusAd ? <Loader2 className="h-5 w-5 animate-spin mr-2" /> : <Play className="h-5 w-5 mr-2" />}
              Watch Ad for Bonus Spin
            </Button>
          )}

          {hasSpunToday && status.bonusUnlocked && (
            <Button
              onClick={doBonusSpin}
              disabled={spinning || waitingForAd}
              className="w-full h-12 rounded-xl font-bold bg-purple-600 hover:bg-purple-700 text-white"
            >
              {spinning ? <Loader2 className="h-5 w-5 animate-spin mr-2" /> : <Trophy className="h-5 w-5 mr-2" />}
              Spin Bonus
            </Button>
          )}
        </div>

        {/* Points & convert */}
        <Card>
          <CardContent className="p-4 space-y-3">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-semibold text-gray-800">Spin Points</p>
                <p className="text-xs text-gray-500">
                  10 pts = ₦1 · Convert at {convertThreshold.toLocaleString()} pts (₦{(convertThreshold / 10).toLocaleString()})
                </p>
              </div>
              <span className="text-xl font-extrabold text-amber-700">{spinPoints.toLocaleString()}</span>
            </div>
            <Button
              onClick={handleConvert}
              disabled={!status.canConvert || converting}
              className={`w-full h-11 rounded-xl font-bold ${
                status.canConvert ? "bg-green-600 hover:bg-green-700 text-white" : "bg-gray-200 text-gray-400 cursor-not-allowed"
              }`}
            >
              {converting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Wallet className="h-4 w-4 mr-2" />}
              {status.canConvert
                ? `Convert ${spinPoints.toLocaleString()} pts to ₦${Math.floor(spinPoints / 10).toLocaleString()}`
                : `${spinPoints.toLocaleString()} / ${convertThreshold.toLocaleString()} pts to Convert`}
            </Button>
          </CardContent>
        </Card>

        {gatewayAdPlaying && (
          <div className="fixed inset-0 z-50 bg-gradient-to-b from-purple-50 to-white flex flex-col items-center justify-center px-4 text-center">
            <div className="text-6xl mb-4 animate-bounce">📺</div>
            <h2 className="text-xl font-bold text-gray-900 mb-2">Unlocking Your Spin...</h2>
            <p className="text-gray-500 text-sm mb-6">Please wait while the ad plays to support the platform.</p>
            <div className="w-8 h-8 rounded-full border-2 border-purple-200 border-t-purple-600 animate-spin" />
          </div>
        )}
      </div>
    </div>
  )
}
