"use client"

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

interface QuizAnalytics {
  totalCompletions: number
  totalPoints: number
  totalUsersWithPoints: number
  conversionCount: number
  recentCompleters: Array<{
    id: string; fullName: string; email: string; lastQuizCompletedAt: string; quizPoints: number
  }>
  topPointHolders: Array<{
    id: string; fullName: string; email: string; quizPoints: number; lastQuizCompletedAt: string | null
  }>
  pointsLeaderboard: Array<{
    id: string; fullName: string; email: string; quizPoints: number; lastQuizCompletedAt: string | null
  }>
}

export function QuizManagementPanel() {
  const { toast } = useToast()
  const [analytics, setAnalytics] = useState<QuizAnalytics | null>(null)
  const [loading, setLoading] = useState(true)
  const [resetAllLoading, setResetAllLoading] = useState(false)
  const [searchQuery, setSearchQuery] = useState("")
  const [resetUserLoading, setResetUserLoading] = useState<string | null>(null)
  const [regenerateLoading, setRegenerateLoading] = useState(false)
  const [adjustUserId, setAdjustUserId] = useState<string | null>(null)
  const [adjustPoints, setAdjustPoints] = useState<number>(0)
  const [adjustLoading, setAdjustLoading] = useState(false)

  const loadAnalytics = async () => {
    setLoading(true)
    try {
      const res = await fetch("/api/admin/quiz/analytics")
      if (res.ok) setAnalytics(await res.json())
    } catch (e) {
      console.error("Failed to load quiz analytics", e)
    } finally {
      setLoading(false)
    }
  }

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

  const handleResetAll = async () => {
    setResetAllLoading(true)
    try {
      const res = await fetch("/api/admin/quiz/reset-all", { method: "POST" })
      const data = await res.json()
      if (res.ok) {
        toast({ title: "Success", description: data.message })
        loadAnalytics()
      } 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/quiz/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: `Quiz timer reset for ${name}` })
        loadAnalytics()
      } else {
        toast({ title: "Error", description: data.error, variant: "destructive" })
      }
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setResetUserLoading(null)
    }
  }

  const handleRegenerateAll = async () => {
    setRegenerateLoading(true)
    try {
      const controller = new AbortController()
      const timeout = setTimeout(() => controller.abort(), 120_000) // 2 minute timeout

      const res = await fetch("/api/admin/quiz/regenerate-all", {
        method: "POST",
        signal: controller.signal,
      })
      clearTimeout(timeout)

      // Check if response is actually JSON before parsing
      const contentType = res.headers.get("content-type") || ""
      if (!contentType.includes("application/json")) {
        const text = await res.text()
        if (text.startsWith("<!DOCTYPE") || text.startsWith("<html")) {
          throw new Error("Server timed out. Some categories may have been regenerated — please check the question bank.")
        }
        throw new Error("Server returned an unexpected response. Try again.")
      }

      const data = await res.json()
      if (res.ok) {
        const succeeded = Object.values(data.results || {}).filter((r: any) => r.status === 'regenerated').length
        const failed = Object.values(data.results || {}).filter((r: any) => r.status !== 'regenerated').length
        let msg = `Regenerated ${succeeded}/9 categories with fresh questions`
        if (failed > 0) msg += `. ${failed} categories failed — you can retry.`
        toast({ title: succeeded > 0 ? "Success" : "Partial Success", description: msg })
        loadAnalytics()
      } else {
        toast({ title: "Error", description: data.error || "Failed to regenerate", variant: "destructive" })
      }
    } catch (e: any) {
      if (e.name === "AbortError") {
        toast({ title: "Request Timed Out", description: "The server is still processing. Some categories may have been regenerated — check the question bank.", variant: "destructive" })
      } else {
        toast({ title: "Error", description: e.message || "An unexpected error occurred", variant: "destructive" })
      }
    } finally {
      setRegenerateLoading(false)
    }
  }

  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/quiz/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)
        loadAnalytics()
      } 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?.pointsLeaderboard?.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-purple-200 border-t-purple-600 rounded-full animate-spin" />
          <p className="text-sm text-gray-500">Loading quiz analytics...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Stats Cards */}
      <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">
              <CheckCircle2 className="h-4 w-4 text-green-500" />
              <span className="text-xs text-gray-500">Completions</span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{analytics?.totalCompletions || 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-amber-500" />
              <span className="text-xs text-gray-500">Total Points</span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{(analytics?.totalPoints || 0).toLocaleString()}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2 mb-1">
              <Users className="h-4 w-4 text-blue-500" />
              <span className="text-xs text-gray-500">Active Players</span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{analytics?.totalUsersWithPoints || 0}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2 mb-1">
              <Wallet className="h-4 w-4 text-green-500" />
              <span className="text-xs text-gray-500">Conversions</span>
            </div>
            <p className="text-2xl font-bold text-gray-900">{analytics?.conversionCount || 0}</p>
          </CardContent>
        </Card>
      </div>

      {/* Reset All + Top Holders */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Reset Actions */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <RefreshCw className="h-4 w-4 text-purple-600" /> Quiz Timer Controls
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <p className="text-sm text-gray-500">
              Reset the daily quiz timer for all users or search for a specific user to reset individually.
            </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 Quiz Timers
            </Button>

            <div className="border-t pt-3">
              <p className="text-sm font-medium text-gray-700 mb-2">Question Bank</p>
              <p className="text-xs text-gray-400 mb-2">
                Clear all existing questions and generate 40 fresh questions per category using AI. Use this if answers are buggy or stale.
              </p>
              <Button
                onClick={handleRegenerateAll}
                disabled={regenerateLoading}
                className="w-full bg-amber-600 hover:bg-amber-700 text-white"
              >
                {regenerateLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Zap className="h-4 w-4 mr-2" />}
                Regenerate All Question Banks
              </Button>
            </div>

            <div className="border-t pt-3 mt-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.quizPoints.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.quizPoints)}
                          >
                            <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>

            {/* Inline Point Adjustment */}
            {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 Quiz Points</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>

        {/* Top Point Holders */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <Trophy className="h-4 w-4 text-amber-500" /> Top Point Holders
            </CardTitle>
          </CardHeader>
          <CardContent>
            {!analytics?.topPointHolders?.length ? (
              <p className="text-sm text-gray-400 text-center py-8">No quiz points earned yet</p>
            ) : (
              <div className="space-y-2">
                {analytics.topPointHolders.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-purple-600">{user.quizPoints.toLocaleString()} pts</span>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Recent Completions */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <Clock className="h-4 w-4 text-blue-500" /> Recent Quiz Completions
          </CardTitle>
        </CardHeader>
        <CardContent>
          {!analytics?.recentCompleters?.length ? (
            <p className="text-sm text-gray-400 text-center py-8">No quiz completions 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">Email</th>
                    <th className="pb-2 font-medium text-gray-500">Points</th>
                    <th className="pb-2 font-medium text-gray-500">Completed</th>
                    <th className="pb-2 font-medium text-gray-500">Action</th>
                  </tr>
                </thead>
                <tbody>
                  {analytics.recentCompleters.map((user) => (
                    <tr key={user.id} className="border-b last:border-0">
                      <td className="py-2 font-medium text-gray-800">{user.fullName || "Unknown"}</td>
                      <td className="py-2 text-gray-500">{user.email}</td>
                      <td className="py-2 text-purple-600 font-medium">{user.quizPoints.toLocaleString()}</td>
                      <td className="py-2 text-gray-500 text-xs">
                        {user.lastQuizCompletedAt ? new Date(user.lastQuizCompletedAt).toLocaleString() : "N/A"}
                      </td>
                      <td className="py-2">
                        <div className="flex items-center gap-1">
                          <Button
                            size="sm"
                            variant="ghost"
                            className="text-xs h-7 text-purple-600 hover:text-purple-700 hover:bg-purple-50"
                            title="Adjust points"
                            onClick={() => openAdjust(user.id, user.quizPoints)}
                          >
                            <Coins className="h-3 w-3 mr-1" />Adjust
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            disabled={resetUserLoading === user.id}
                            onClick={() => handleResetUser(user.id, user.fullName || user.email)}
                            className="text-xs h-7 text-purple-600 hover:text-purple-700 hover:bg-purple-50"
                          >
                            {resetUserLoading === user.id ? <Loader2 className="h-3 w-3 animate-spin" /> : "Reset"}
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
