'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/lib/auth';
import supabase from '@/lib/supabase';
import { Session, User } from '@supabase/supabase-js';

interface SessionData {
  session: Session | null;
  user?: User | null;
}

export default function DebugPage() {
  const { user, session, isLoading } = useAuth();
  const [cookies, setCookies] = useState<Record<string, string>>({});
  const [rawCookies, setRawCookies] = useState('');
  const [sessionData, setSessionData] = useState<SessionData | null>(null);
  const [redirectTarget, setRedirectTarget] = useState('/analytics');
  
  useEffect(() => {
    // Get all cookies
    const allCookies = document.cookie.split(';').reduce((acc, cookie) => {
      const [key, value] = cookie.trim().split('=');
      if (key) acc[key] = value || '';
      return acc;
    }, {} as Record<string, string>);
    
    setCookies(allCookies);
    setRawCookies(document.cookie);
    
    // Test Supabase session
    const testSession = async () => {
      try {
        console.log('Getting Supabase session');
        const { data, error } = await supabase.auth.getSession();
        console.log('Supabase session result:', { data, error });
        
        if (error) {
          console.error('Session error:', error);
        } else {
          setSessionData(data);
        }
      } catch (err) {
        console.error('Error getting session:', err);
      }
    };
    
    testSession();
  }, []);
  
  const refreshSession = async () => {
    try {
      console.log('Manually refreshing session');
      const { data, error } = await supabase.auth.refreshSession();
      console.log('Refresh result:', { data, error });
      alert('Session refresh complete, please check console logs');
      
      if (!error && data.session) {
        window.location.reload();
      }
    } catch (err) {
      console.error('Error refreshing session:', err);
      alert('Error refreshing session: ' + String(err));
    }
  };
  
  const forceRedirect = () => {
    if (redirectTarget) {
      window.location.href = redirectTarget;
    }
  };
  
  return (
    <div className="container mx-auto p-8">
      <h1 className="text-3xl font-bold mb-6">Authentication Debug Page</h1>
      
      <div className="bg-gray-100 p-6 rounded-lg mb-6">
        <h2 className="text-xl font-semibold mb-4">User Status</h2>
        <div className="space-y-2">
          <p>Loading status: {isLoading ? 'Loading...' : 'Loaded'}</p>
          <p>Logged in: {user ? 'Yes' : 'No'}</p>
          <p>User email: {user?.email || 'Not logged in'}</p>
          <p>User ID: {user?.id || 'Not logged in'}</p>
          <p>Session valid: {session ? 'Yes' : 'No'}</p>
          <p>Session expires: {session?.expires_at ? new Date(session.expires_at * 1000).toLocaleString() : 'No session'}</p>
        </div>
      </div>
      
      <div className="bg-gray-100 p-6 rounded-lg mb-6">
        <h2 className="text-xl font-semibold mb-4">Supabase Session Data</h2>
        <pre className="bg-gray-200 p-4 rounded text-xs overflow-auto max-h-60">
          {sessionData ? JSON.stringify(sessionData, null, 2) : 'Loading...'}
        </pre>
        
        <button 
          onClick={refreshSession}
          className="mt-4 px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
        >
          Refresh Session
        </button>
      </div>
      
      <div className="bg-gray-100 p-6 rounded-lg mb-6">
        <h2 className="text-xl font-semibold mb-4">Cookie Information</h2>
        <div className="space-y-2">
          <p className="text-sm mb-2">Raw cookie string:</p>
          <pre className="bg-gray-200 p-4 rounded overflow-x-auto text-xs">
            {rawCookies || '(empty)'}
          </pre>
          
          <p className="text-sm mt-4 mb-2">Parsed cookies:</p>
          <pre className="bg-gray-200 p-4 rounded overflow-x-auto text-xs">
            {JSON.stringify(cookies, null, 2) || '{}'}
          </pre>
          
          <p className="text-sm mt-4 mb-2">Supabase-related cookies:</p>
          <div className="space-y-1">
            <p>sb-access-token: {cookies['sb-access-token'] ? 'Exists' : 'Not found'}</p>
            <p>sb-refresh-token: {cookies['sb-refresh-token'] ? 'Exists' : 'Not found'}</p>
            <p>supabase-auth-token: {cookies['supabase-auth-token'] ? 'Exists' : 'Not found'}</p>
          </div>
        </div>
      </div>
      
      <div className="bg-gray-100 p-6 rounded-lg mb-6">
        <h2 className="text-xl font-semibold mb-4">Manual Redirect</h2>
        <div className="flex space-x-2 items-center">
          <input
            type="text"
            value={redirectTarget}
            onChange={(e) => setRedirectTarget(e.target.value)}
            className="flex-1 px-3 py-2 border border-gray-300 rounded"
            placeholder="/analytics"
          />
          <button
            onClick={forceRedirect}
            className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            Force Redirect
          </button>
        </div>
      </div>
      
      <div className="flex space-x-4">
        <button 
          onClick={() => window.location.href = '/login'} 
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
        >
          Go to Login
        </button>
        <button 
          onClick={async () => {
            try {
              await supabase.auth.signOut();
              alert('Signed out, refreshing page...');
              window.location.reload();
            } catch (err) {
              alert('Error signing out: ' + String(err));
            }
          }} 
          className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
        >
          Sign Out
        </button>
      </div>
    </div>
  );
} 