import React, { useState } from 'react';
import Layout from '../components/Layout';
import { fredApi } from '../lib/api';

const TestFredPage: React.FC = () => {
  const [result, setResult] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const testUsageStats = async () => {
    setLoading(true);
    setError(null);
    try {
      const stats = await fredApi.getUsageStats();
      setResult({ type: 'Usage Stats', data: stats });
    } catch (err: any) {
      setError(`Error: ${err.message}`);
      console.error('Test error:', err);
    } finally {
      setLoading(false);
    }
  };

  const testSingleSeries = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fredApi.proxyRequest({
        endpoint: 'series',
        params: { series_id: 'GDP' }
      });
      setResult({ type: 'Single Series (GDP)', data: response });
    } catch (err: any) {
      setError(`Error: ${err.message}`);
      console.error('Test error:', err);
    } finally {
      setLoading(false);
    }
  };

  const testPopularSeries = async () => {
    setLoading(true);
    setError(null);
    try {
      const series = await fredApi.getPopularSeries();
      setResult({ type: 'Popular Series', data: series });
    } catch (err: any) {
      setError(`Error: ${err.message}`);
      console.error('Test error:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Layout>
      <div className="space-y-6">
        <h1 className="text-2xl font-bold text-gray-900">🧪 FRED API Test</h1>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <button
            onClick={testUsageStats}
            disabled={loading}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
          >
            Test Usage Stats
          </button>

          <button
            onClick={testSingleSeries}
            disabled={loading}
            className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
          >
            Test Single Series
          </button>

          <button
            onClick={testPopularSeries}
            disabled={loading}
            className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50"
          >
            Test Popular Series
          </button>
        </div>

        {loading && (
          <div className="text-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-2 text-gray-600">Testing API...</p>
          </div>
        )}

        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4">
            <h3 className="text-red-800 font-medium">Error</h3>
            <p className="text-red-600 text-sm mt-1">{error}</p>
          </div>
        )}

        {result && (
          <div className="bg-white rounded-lg shadow p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">
              {result.type} - Result
            </h3>
            <pre className="bg-gray-100 p-4 rounded-lg overflow-auto text-xs">
              {JSON.stringify(result.data, null, 2)}
            </pre>
          </div>
        )}

        <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
          <h3 className="text-yellow-800 font-medium">Debug Info</h3>
          <p className="text-yellow-700 text-sm mt-1">
            API Base URL: {process.env.NEXT_PUBLIC_API_URL || 'http://localhost:18001/api/v1'}
          </p>
          <p className="text-yellow-700 text-sm">
            Open browser dev tools to see network requests and console logs
          </p>
        </div>
      </div>
    </Layout>
  );
};

export default TestFredPage;