"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { useToast } from "@/hooks/use-toast"
import { Coins, Loader2, RefreshCw, Trophy, Users, Gift, Clock, CheckCircle2, Search, Minus, Plus } from "lucide-react"

interface SpinAnalytics {
  totalSpins: number
  totalBonusSpins: number
  totalJackpots: number
  totalPointsAwarded: number
  totalUsersWithPoints: number
  totalConverted: number
  pointsLeaderboard: Array<{ id: string; fullName: string; email: string; spinPoints: number }>
  spinners: Array<{ id: string; fullName: string; email: string; spinPoints: number; lastSpinAt: string | null }>
  recentRecords: Array<{
    id: string
    type: string
    points: number
    timestamp: string
    user: { fullName: string; email: string } | null
  }>
}

interface SpinConfig {
  enabled: boolean
  bonusPoints: number
  jackpotPoints: number
  convertThreshold: number
  maxBonusPerDay: number
}

export function SpinManagementPanel() {
  const { toast } = useToast()
  const [analytics, setAnalytics] = useState<SpinAnalytics | null>(null)
  const [config, setConfig] = useState<SpinConfig>({
    enabled: true,
    bonusPoints: 50,
    jackpotPoints: 5000,
    convertThreshold: 10000,
    maxBonusPerDay: 1,
  })
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [drawing, setDrawing] = useState(false)
  const [resetAllLoading, setResetAllLoading] = useState(false)
  const [resetUserLoading, setResetUserLoading] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState("")
  const [adjustUserId, setAdjustUserId] = useState<string | null>(null)
  const [adjustPoints, setAdjustPoints] = useState<number>(0)
  const [adjustLoading, setAdjustLoading] = useState(false)

  const load = async () => {
    setLoading(true)
    try {
      const [aRes, cRes] = await Promise.all([
        fetch("/api/admin/spin/analytics"),
        fetch("/api/admin/spin/config"),
      ])
      if (aRes.ok) setAnalytics(await aRes.json())
      if (cRes.ok) setConfig(await cRes.json())
    } catch (e) {
      console.error("Failed to load spin data", e)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    load()
  }, [])

  const handleSave = async () => {
    setSaving(true)
    try {
      const res = await fetch("/api/admin/spin/config", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(config),
      })
      const data = await res.json()
      if (res.ok) {
        toast({ title: "Saved", description: "Spin configuration updated" })
      } else {
        toast({ title: "Error", description: data.error, variant: "destructive" })
      }
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setSaving(false)
    }
  }

  const handleDrawJackpot = async () => {
    setDrawing(true)
    try {
      const res = await fetch("/api/admin/spin/draw-jackpot", { method: "POST" })
      const data = await res.json()
      if (res.ok && data.drawn) {
        toast({ title: "🎰 Jackpot Drawn!", description: `Winner: ${data.winner} (+${data.points} pts)` })
        load()
      } else {
        toast({ title: "Info", description: data.message || "Draw already completed this month" })
      }
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setDrawing(false)
    }
  }

  const handleResetAll = async () => {
    setResetAllLoading(true)
    try {
      const res = await fetch("/api/admin/spin/reset-all", { method: "POST" })
      const data = await res.json()
      if (res.ok) {
        toast({ title: "Success", description: data.message })
        load()
      } else {
        toast({ title: "Error", description: data.error, variant: "destructive" })
      }
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setResetAllLoading(false)
    }
  }

  const handleResetUser = async (userId: string, name: string) => {
    setResetUserLoading(userId)
    try {
      const res = await fetch("/api/admin/spin/reset-user", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId }),
      })
      const data = await res.json()
      if (res.ok) {
        toast({ title: "Success", description: `Spin timer reset for ${name}` })
        load()
      } else {
        toast({ title: "Error", description: data.error, variant: "destructive" })
      }
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setResetUserLoading(null)
    }
  }

  const openAdjust = (userId: string, currentPoints: number) => {
    setAdjustUserId(userId)
    setAdjustPoints(currentPoints)
  }

  const handleAdjustPoints = async () => {
    if (!adjustUserId || adjustPoints < 0) return
    setAdjustLoading(true)
    try {
      const res = await fetch("/api/admin/spin/adjust-points", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId: adjustUserId, points: adjustPoints }),
      })
      const data = await res.json()
      if (res.ok) {
        toast({ title: "Points Adjusted", description: data.message })
        setAdjustUserId(null)
        load()
      } else {
        toast({ title: "Error", description: data.error, variant: "destructive" })
      }
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setAdjustLoading(false)
    }
  }

  const filteredUsers = analytics?.spinners?.filter((u) =>
    (u.fullName || "").toLowerCase().includes(searchQuery.toLowerCase()) ||
    (u.email || "").toLowerCase().includes(searchQuery.toLowerCase())
  ) || []

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="flex flex-col items-center gap-3">
          <div className="h-8 w-8 border-4 border-teal-200 border-t-teal-600 rounded-full animate-spin" />
          <p className="text-sm text-gray-500">Loading spin analytics...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2 mb-1">
              <Clock className="h-4 w-4 text-teal-500" />
              <span className="text-xs text-gray-500">Total Spins</span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{analytics?.totalSpins || 0}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2 mb-1">
              <Gift className="h-4 w-4 text-purple-500" />
              <span className="text-xs text-gray-500">Bonus Spins</span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{analytics?.totalBonusSpins || 0}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2 mb-1">
              <Trophy className="h-4 w-4 text-amber-500" />
              <span className="text-xs text-gray-500">Jackpots</span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{analytics?.totalJackpots || 0}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2 mb-1">
              <Coins className="h-4 w-4 text-emerald-500" />
              <span className="text-xs text-gray-500">Points Awarded</span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{(analytics?.totalPointsAwarded || 0).toLocaleString()}</p>
          </CardContent>
        </Card>
      </div>

      {/* Spin Timer Controls */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <RefreshCw className="h-4 w-4 text-purple-600" /> Spin Timer Controls
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <p className="text-sm text-gray-500">
            Reset the daily spin cooldown for all users, or search for a specific user to reset their timer and adjust their spin points.
          </p>
          <Button
            onClick={handleResetAll}
            disabled={resetAllLoading}
            className="w-full bg-purple-600 hover:bg-purple-700 text-white"
          >
            {resetAllLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <RefreshCw className="h-4 w-4 mr-2" />}
            Reset All Spin Timers
          </Button>

          <div className="border-t pt-3">
            <p className="text-sm font-medium text-gray-700 mb-2">Reset Individual User</p>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
              <Input
                placeholder="Search by name or email..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9"
              />
            </div>
            {searchQuery && (
              <div className="mt-2 max-h-48 overflow-y-auto space-y-1">
                {filteredUsers.length === 0 ? (
                  <p className="text-xs text-gray-400 py-2 text-center">No users found</p>
                ) : (
                  filteredUsers.slice(0, 10).map((user) => (
                    <div key={user.id} className="flex items-center justify-between py-1.5 px-2 rounded-lg hover:bg-gray-50">
                      <div className="min-w-0 flex-1">
                        <p className="text-sm font-medium text-gray-800 truncate">{user.fullName || "Unknown"}</p>
                        <p className="text-xs text-gray-400 truncate">{user.email} • {(user.spinPoints || 0).toLocaleString()} pts</p>
                      </div>
                      <div className="flex items-center gap-1">
                        <Button
                          size="sm"
                          variant="ghost"
                          className="h-7 w-7 p-0 text-gray-400 hover:text-purple-600"
                          title="Adjust points"
                          onClick={() => openAdjust(user.id, user.spinPoints || 0)}
                        >
                          <Coins className="h-3.5 w-3.5" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          disabled={resetUserLoading === user.id}
                          onClick={() => handleResetUser(user.id, user.fullName || user.email)}
                          className="shrink-0 text-xs h-7"
                        >
                          {resetUserLoading === user.id ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
                          Reset
                        </Button>
                      </div>
                    </div>
                  ))
                )}
              </div>
            )}
          </div>

          {adjustUserId && (
            <div className="mt-3 p-3 bg-purple-50 rounded-xl border border-purple-200">
              <p className="text-xs font-medium text-purple-700 mb-2">Adjust Spin Points (set to 0 to clear)</p>
              <div className="flex items-center gap-2">
                <Button
                  size="sm"
                  variant="outline"
                  className="h-8 w-8 p-0"
                  onClick={() => setAdjustPoints((p) => Math.max(0, p - 100))}
                >
                  <Minus className="h-3 w-3" />
                </Button>
                <Input
                  type="number"
                  min={0}
                  value={adjustPoints}
                  onChange={(e) => setAdjustPoints(Math.max(0, parseInt(e.target.value) || 0))}
                  className="h-8 w-24 text-center text-sm font-bold"
                />
                <Button
                  size="sm"
                  variant="outline"
                  className="h-8 w-8 p-0"
                  onClick={() => setAdjustPoints((p) => p + 100)}
                >
                  <Plus className="h-3 w-3" />
                </Button>
                <Button
                  size="sm"
                  onClick={handleAdjustPoints}
                  disabled={adjustLoading}
                  className="h-8 bg-purple-600 hover:bg-purple-700 text-white text-xs"
                >
                  {adjustLoading ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
                  Save
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  className="h-8 text-xs text-gray-400"
                  onClick={() => setAdjustUserId(null)}
                >
                  Cancel
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Config */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <RefreshCw className="h-4 w-4 text-teal-600" /> Spin Configuration
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-800">Enable Spin &amp; Win</p>
                <p className="text-xs text-gray-400">Turn the whole feature on/off</p>
              </div>
              <Switch checked={config.enabled} onCheckedChange={(v) => setConfig((c) => ({ ...c, enabled: v }))} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <LabeledInput
                  label="Bonus Spin Points"
                  value={config.bonusPoints}
                  onChange={(v) => setConfig((c) => ({ ...c, bonusPoints: v }))}
                />
              </div>
              <div>
                <LabeledInput
                  label="Jackpot Points"
                  value={config.jackpotPoints}
                  onChange={(v) => setConfig((c) => ({ ...c, jackpotPoints: v }))}
                />
              </div>
              <div>
                <LabeledInput
                  label="Convert Threshold (pts)"
                  value={config.convertThreshold}
                  onChange={(v) => setConfig((c) => ({ ...c, convertThreshold: v }))}
                />
              </div>
              <div>
                <LabeledInput
                  label="Max Bonus / Day"
                  value={config.maxBonusPerDay}
                  onChange={(v) => setConfig((c) => ({ ...c, maxBonusPerDay: v }))}
                />
              </div>
            </div>
            <Button onClick={handleSave} disabled={saving} className="w-full bg-teal-600 hover:bg-teal-700 text-white">
              {saving ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
              Save Configuration
            </Button>

            <div className="border-t pt-3">
              <p className="text-sm font-medium text-gray-700 mb-1">Monthly Jackpot</p>
              <p className="text-xs text-gray-400 mb-2">
                One random user who spun this month wins the jackpot. Normally drawn automatically by the cron job.
              </p>
              <Button onClick={handleDrawJackpot} disabled={drawing} className="w-full bg-amber-600 hover:bg-amber-700 text-white">
                {drawing ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Trophy className="h-4 w-4 mr-2" />}
                Draw Jackpot Now
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* Top holders */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <Users className="h-4 w-4 text-teal-500" /> Top Spin Point Holders
            </CardTitle>
          </CardHeader>
          <CardContent>
            {!analytics?.pointsLeaderboard?.length ? (
              <p className="text-sm text-gray-400 text-center py-8">No spin points earned yet</p>
            ) : (
              <div className="space-y-2">
                {analytics.pointsLeaderboard.map((user, idx) => (
                  <div key={user.id} className="flex items-center gap-3 py-2">
                    <span
                      className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${
                        idx === 0
                          ? "bg-amber-100 text-amber-700"
                          : idx === 1
                            ? "bg-gray-200 text-gray-600"
                            : idx === 2
                              ? "bg-orange-100 text-orange-700"
                              : "bg-gray-100 text-gray-500"
                      }`}
                    >
                      {idx + 1}
                    </span>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-gray-800 truncate">{user.fullName || "Unknown"}</p>
                      <p className="text-xs text-gray-400 truncate">{user.email}</p>
                    </div>
                    <span className="text-sm font-bold text-teal-600">{user.spinPoints.toLocaleString()} pts</span>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Recent records */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <CheckCircle2 className="h-4 w-4 text-blue-500" /> Recent Spin Activity
          </CardTitle>
        </CardHeader>
        <CardContent>
          {!analytics?.recentRecords?.length ? (
            <p className="text-sm text-gray-400 text-center py-8">No spin activity yet</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b text-left">
                    <th className="pb-2 font-medium text-gray-500">User</th>
                    <th className="pb-2 font-medium text-gray-500">Type</th>
                    <th className="pb-2 font-medium text-gray-500">Points</th>
                    <th className="pb-2 font-medium text-gray-500">Time</th>
                  </tr>
                </thead>
                <tbody>
                  {analytics.recentRecords.map((r) => (
                    <tr key={r.id} className="border-b last:border-0">
                      <td className="py-2 font-medium text-gray-800">{r.user?.fullName || "Unknown"}</td>
                      <td className="py-2">
                        <span
                          className={`text-xs font-semibold px-2 py-0.5 rounded-full ${
                            r.type === "bonus"
                              ? "bg-purple-100 text-purple-700"
                              : r.type === "jackpot"
                                ? "bg-amber-100 text-amber-700"
                                : r.type === "convert"
                                  ? "bg-green-100 text-green-700"
                                  : "bg-gray-100 text-gray-600"
                          }`}
                        >
                          {r.type}
                        </span>
                      </td>
                      <td className="py-2 text-teal-600 font-medium">{r.points > 0 ? `+${r.points}` : r.points}</td>
                      <td className="py-2 text-gray-500 text-xs">{new Date(r.timestamp).toLocaleString()}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

function LabeledInput({
  label,
  value,
  onChange,
}: {
  label: string
  value: number
  onChange: (v: number) => void
}) {
  return (
    <div>
      <p className="text-xs font-medium text-gray-600 mb-1">{label}</p>
      <Input
        type="number"
        min={0}
        value={value}
        onChange={(e) => onChange(Math.max(0, parseInt(e.target.value) || 0))}
        className="h-9 text-sm"
      />
    </div>
  )
}
