'use client'

import { useEffect, useState } from 'react'
import useAuthStore from '../store/authStore'
import { useUserStatus } from '../hooks/useUserStatus'

export default function DebugAuthPage() {
  const [debugInfo, setDebugInfo] = useState<any>({})
  const { accessToken, user, isAuthReady, refreshAuthToken, getAuthState } = useAuthStore()
  const { userStatus, loading, error } = useUserStatus()

  useEffect(() => {
    const updateDebugInfo = () => {
      const authState = getAuthState()
      setDebugInfo({
        ...authState,
        timestamp: new Date().toISOString(),
        sessionStorageUser: typeof window !== 'undefined' ? sessionStorage.getItem('user') : null,
        sessionStorageToken: typeof window !== 'undefined' ? sessionStorage.getItem('accessToken') : null,
        apiBaseUrl: process.env.NEXT_PUBLIC_API_BASE_URL
      })
    }

    updateDebugInfo()
    const interval = setInterval(updateDebugInfo, 1000)
    return () => clearInterval(interval)
  }, [getAuthState])

  const handleRefreshToken = async () => {
    console.log('Manual token refresh...')
    const result = await refreshAuthToken()
    console.log('Refresh result:', result)
  }

  const handleTestApiCall = async () => {
    if (!accessToken) {
      console.error('No access token available')
      return
    }

    try {
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/user/status`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${accessToken}`,
          'Content-Type': 'application/json'
        }
      })

      console.log('API Response Status:', response.status)
      const data = await response.json().catch(() => null)
      console.log('API Response Data:', data)
    } catch (error) {
      console.error('API Test Error:', error)
    }
  }

  return (
    <div className="min-h-screen bg-gray-100 p-8">
      <div className="max-w-4xl mx-auto">
        <h1 className="text-3xl font-bold mb-8">Auth Debug Page</h1>
        
        <div className="grid gap-6 md:grid-cols-2">
          {/* Auth Store State */}
          <div className="bg-white rounded-lg p-6 shadow">
            <h2 className="text-xl font-semibold mb-4">Auth Store State</h2>
            <pre className="text-xs bg-gray-100 p-4 rounded overflow-auto">
              {JSON.stringify(debugInfo, null, 2)}
            </pre>
            <div className="mt-4 space-x-2">
              <button
                onClick={handleRefreshToken}
                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
              >
                Refresh Token
              </button>
              <button
                onClick={handleTestApiCall}
                className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
              >
                Test API Call
              </button>
            </div>
          </div>

          {/* User Status */}
          <div className="bg-white rounded-lg p-6 shadow">
            <h2 className="text-xl font-semibold mb-4">User Status Hook</h2>
            <div className="space-y-2 text-sm">
              <p><strong>Loading:</strong> {loading ? 'Yes' : 'No'}</p>
              <p><strong>Error:</strong> {error || 'None'}</p>
              <p><strong>Status:</strong></p>
              <pre className="text-xs bg-gray-100 p-4 rounded overflow-auto">
                {JSON.stringify(userStatus, null, 2)}
              </pre>
            </div>
          </div>

          {/* Environment */}
          <div className="bg-white rounded-lg p-6 shadow md:col-span-2">
            <h2 className="text-xl font-semibold mb-4">Environment</h2>
            <div className="text-sm space-y-1">
              <p><strong>API Base URL:</strong> {process.env.NEXT_PUBLIC_API_BASE_URL}</p>
              <p><strong>Node Env:</strong> {process.env.NODE_ENV}</p>
              <p><strong>Current URL:</strong> {typeof window !== 'undefined' ? window.location.href : 'SSR'}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}