'use client'

import { useState } from 'react'
import { useAuthUser } from '@/hooks/useAuthUser'
import { userCache } from '@/lib/user-cache'
import { Header } from '@/components/layout/Header'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'

export default function CacheDebugPage() {
  const { user, userData, loading, isAdmin, refreshUserData } = useAuthUser()
  const [cacheStats, setCacheStats] = useState(userCache.getCacheStats())

  const updateCacheStats = () => {
    setCacheStats(userCache.getCacheStats())
  }

  const handleRefresh = async (force = false) => {
    await refreshUserData(force)
    updateCacheStats()
  }

  const handleClearCache = () => {
    if (user) {
      userCache.clearUserCache(user.id)
      updateCacheStats()
    }
  }

  const handleClearAllCache = () => {
    userCache.clearAllCache()
    updateCacheStats()
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="text-center">Loading...</div>
        </div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="text-center">Please sign in to access this page</div>
        </div>
      </div>
    )
  }

  if (!isAdmin) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="text-center">
            <h1 className="text-2xl font-bold text-red-600 mb-4">Access Denied</h1>
            <p className="text-muted-foreground">This page is only accessible to administrators.</p>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />
      <div className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto space-y-6">
          <div>
            <div className="flex items-center gap-4 mb-4">
              <Link
                href="/admin"
                className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
              >
                <ArrowLeft className="h-4 w-4" />
                Back to Admin Panel
              </Link>
            </div>
            <h1 className="text-3xl font-bold">User Cache Debug</h1>
            <p className="text-muted-foreground mt-2">
              Monitor and debug the user cache mechanism and API call optimization. This tool helps administrators
              verify cache performance and troubleshoot user data synchronization issues.
            </p>
          </div>

          <div className="grid gap-6 md:grid-cols-2">
            {/* Cache Statistics */}
            <Card>
              <CardHeader>
                <CardTitle>Cache Statistics</CardTitle>
                <CardDescription>Current cache state and metrics</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <div className="font-medium">User Data Cache</div>
                    <div className="text-muted-foreground">{cacheStats.userDataCacheSize} entries</div>
                  </div>
                  <div>
                    <div className="font-medium">Sync Timestamps</div>
                    <div className="text-muted-foreground">{cacheStats.syncTimestampsSize} entries</div>
                  </div>
                  <div>
                    <div className="font-medium">Active Sync Promises</div>
                    <div className="text-muted-foreground">{cacheStats.activeSyncPromises} promises</div>
                  </div>
                </div>
                <Button onClick={updateCacheStats} variant="outline" size="sm">
                  Refresh Stats
                </Button>
              </CardContent>
            </Card>

            {/* User Data */}
            <Card>
              <CardHeader>
                <CardTitle>Current User Data</CardTitle>
                <CardDescription>Data from cache or API</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                {userData ? (
                  <div className="space-y-2 text-sm">
                    <div><span className="font-medium">ID:</span> {userData.id}</div>
                    <div><span className="font-medium">Email:</span> {userData.email}</div>
                    <div><span className="font-medium">Username:</span> {userData.username || 'N/A'}</div>
                    <div><span className="font-medium">Plan:</span> {userData.subscribePlan}</div>
                    <div><span className="font-medium">Credit Balance:</span> ${userData.creditBalance}</div>
                    <div><span className="font-medium">Is Admin:</span> {userData.isAdmin ? 'Yes' : 'No'}</div>
                  </div>
                ) : (
                  <div className="text-muted-foreground">No user data available</div>
                )}
              </CardContent>
            </Card>
          </div>

          {/* Cache Actions */}
          <Card>
            <CardHeader>
              <CardTitle>Cache Actions</CardTitle>
              <CardDescription>Test cache behavior and API calls</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex flex-wrap gap-3">
                <Button 
                  onClick={() => handleRefresh(false)}
                  variant="default"
                >
                  Refresh (Use Cache)
                </Button>
                <Button
                  onClick={() => handleRefresh(true)}
                  variant="outline"
                >
                  Force Refresh (Skip Cache)
                </Button>
                <Button 
                  onClick={handleClearCache}
                  variant="outline"
                >
                  Clear User Cache
                </Button>
                <Button 
                  onClick={handleClearAllCache}
                  variant="destructive"
                >
                  Clear All Cache
                </Button>
              </div>
            </CardContent>
          </Card>

          {/* Instructions */}
          <Card>
            <CardHeader>
              <CardTitle>Testing Instructions</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3 text-sm">
              <div>
                <strong>1. Normal Refresh:</strong> Should use cached data if available and within TTL (5 minutes).
              </div>
              <div>
                <strong>2. Force Refresh:</strong> Should bypass cache and fetch fresh data from API.
              </div>
              <div>
                <strong>3. Clear Cache:</strong> Should remove cached data for current user only.
              </div>
              <div>
                <strong>4. Clear All Cache:</strong> Should remove all cached data.
              </div>
              <div className="mt-4 p-3 bg-muted rounded-lg">
                <strong>Expected Behavior:</strong> After the initial load, subsequent page refreshes or navigation 
                should use cached data and not trigger new API calls unless the cache has expired or been cleared.
                Check the Network tab in browser dev tools to verify API call frequency.
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}
