'use client';

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

export default function DebugPage() {
  const { user, session, isLoading } = useAuth();
  const [cookies, setCookies] = useState<Record<string, string>>({});
  const [rawCookies, setRawCookies] = useState('');
  const [sessionData, setSessionData] = useState<{ session: any; user: any } | null>(null);
  const [redirectTarget, setRedirectTarget] = useState('/analytics');
  
  useEffect(() => {
    // 获取所有cookie
    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);
    
    // 测试supabase会话
    const testSession = async () => {
      try {
        console.log('正在获取Supabase会话');
        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('获取会话出错:', err);
      }
    };
    
    testSession();
  }, []);
  
  const refreshSession = async () => {
    try {
      console.log('手动刷新会话');
      const { data, error } = await supabase.auth.refreshSession();
      console.log('刷新结果:', { data, error });
      alert('会话刷新完成，请查看控制台日志');
      
      if (!error && data.session) {
        window.location.reload();
      }
    } catch (err) {
      console.error('刷新会话出错:', err);
      alert('刷新会话出错: ' + 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">认证调试页面</h1>
      
      <div className="bg-gray-100 p-6 rounded-lg mb-6">
        <h2 className="text-xl font-semibold mb-4">用户状态</h2>
        <div className="space-y-2">
          <p>加载状态: {isLoading ? '加载中...' : '已加载'}</p>
          <p>已登录: {user ? '是' : '否'}</p>
          <p>用户邮箱: {user?.email || '未登录'}</p>
          <p>用户ID: {user?.id || '未登录'}</p>
          <p>会话有效: {session ? '是' : '否'}</p>
          <p>会话过期时间: {session?.expires_at ? new Date(session.expires_at * 1000).toLocaleString() : '无会话'}</p>
        </div>
      </div>
      
      <div className="bg-gray-100 p-6 rounded-lg mb-6">
        <h2 className="text-xl font-semibold mb-4">Supabase 会话数据</h2>
        <pre className="bg-gray-200 p-4 rounded text-xs overflow-auto max-h-60">
          {sessionData ? JSON.stringify(sessionData, null, 2) : '加载中...'}
        </pre>
        
        <button 
          onClick={refreshSession}
          className="mt-4 px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
        >
          刷新会话
        </button>
      </div>
      
      <div className="bg-gray-100 p-6 rounded-lg mb-6">
        <h2 className="text-xl font-semibold mb-4">Cookies 信息</h2>
        <div className="space-y-2">
          <p className="text-sm mb-2">原始Cookie字符串:</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">解析后的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相关Cookies:</p>
          <div className="space-y-1">
            <p>sb-access-token: {cookies['sb-access-token'] ? '存在' : '不存在'}</p>
            <p>sb-refresh-token: {cookies['sb-refresh-token'] ? '存在' : '不存在'}</p>
            <p>supabase-auth-token: {cookies['supabase-auth-token'] ? '存在' : '不存在'}</p>
          </div>
        </div>
      </div>
      
      <div className="bg-gray-100 p-6 rounded-lg mb-6">
        <h2 className="text-xl font-semibold mb-4">手动重定向</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"
          >
            强制重定向
          </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"
        >
          去登录页
        </button>
        <button 
          onClick={async () => {
            try {
              await supabase.auth.signOut();
              alert('已登出，刷新页面中...');
              window.location.reload();
            } catch (err) {
              alert('登出出错: ' + String(err));
            }
          }} 
          className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
        >
          登出
        </button>
      </div>
    </div>
  );
} 