import React, { useState } from 'react';
import apiService from '../services/apiService';
import { ApiError } from '../services/apiService';

interface TestResults {
  csrfToken?: string;
  dashboardStats?: string;
  userDetails?: string;
  doctypeRecords?: string;
  error?: string;
}

const ApiTest: React.FC = () => {
  const [testResults, setTestResults] = useState<TestResults>({});
  const [loading, setLoading] = useState<boolean>(false);

  const testApiConnection = async (): Promise<void> => {
    setLoading(true);
    const results: TestResults = {};

    try {
      // Test 1: Basic connectivity test (skip CSRF token test)
      console.log('Testing basic connectivity...');
      try {
        // Test with a simple API call instead of CSRF token
        const response = await fetch('/api/method/frappe.desk.doctype.event.event.get_events', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            start: new Date().toISOString().split('T')[0],
            end: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          }),
          signal: AbortSignal.timeout(10000) // 10 second timeout
        });
        
        if (response.ok) {
          results.csrfToken = '✅ Basic Connectivity: SUCCESS';
        } else {
          results.csrfToken = `❌ Basic Connectivity: HTTP ${response.status}`;
        }
      } catch (e) {
        results.csrfToken = `❌ Basic Connectivity: ${e instanceof Error ? e.message : 'Unknown error'}`;
      }

      // Test 2: Test Frappe system endpoint
      console.log('Testing Frappe system endpoint...');
      try {
        // Use a simpler endpoint that doesn't require parameters
        await apiService.apiCall('/api/method/frappe.auth.get_logged_user', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          }
        });
        results.dashboardStats = '✅ Frappe System API: SUCCESS';
      } catch (e) {
        // If this fails, it's likely because user is not logged in, which is OK
        const errorMsg = e instanceof Error ? e.message : 'Unknown';
        if (errorMsg.includes('403') || errorMsg.includes('401')) {
          results.dashboardStats = '✅ Frappe System API: SUCCESS (auth required)';
        } else {
          results.dashboardStats = `❌ Frappe System API: ${errorMsg}`;
        }
      }

      // Test 3: Test custom endpoints (these will fail until you deploy the API file)
      console.log('Testing Custom User Details...');
      try {
        const userDetails = await apiService.getUserDetails();
        results.userDetails = userDetails ? '✅ Custom API: SUCCESS' : '❌ Custom API: Failed';
      } catch (e) {
        results.userDetails = `❌ Custom API (Expected): ${e instanceof Error ? e.message : 'Unknown'}`;
      }

      // Test 4: Test custom dashboard stats
      console.log('Testing Custom Dashboard Stats...');
      try {
        const dashboardStats = await apiService.getDashboardStats();
        results.doctypeRecords = dashboardStats ? '✅ Custom Stats: SUCCESS' : '❌ Custom Stats: Failed';
      } catch (e) {
        results.doctypeRecords = `❌ Custom Stats (Expected): ${e instanceof Error ? e.message : 'Unknown'}`;
      }

    } catch (error) {
      console.error('API Test Error:', error);
      if (error instanceof ApiError) {
        results.error = `${error.message} (Status: ${error.status})`;
      } else {
        results.error = error instanceof Error ? error.message : 'Unknown error';
      }
    }

    setTestResults(results);
    setLoading(false);
  };

  return (
    <div style={{ padding: '20px', border: '1px solid #ccc', margin: '20px' }}>
      <h2>API Connection Test</h2>
      <button 
        onClick={testApiConnection} 
        disabled={loading}
        style={{ 
          padding: '10px 20px', 
          marginBottom: '20px',
          backgroundColor: loading ? '#ccc' : '#007bff',
          color: 'white',
          border: 'none',
          borderRadius: '4px',
          cursor: loading ? 'not-allowed' : 'pointer'
        }}
      >
        {loading ? 'Testing...' : 'Test API Connection'}
      </button>

      <div>
        <h3>Test Results:</h3>
        <div style={{ 
          background: '#f5f5f5', 
          padding: '15px', 
          borderRadius: '5px',
          fontSize: '14px'
        }}>
          <div><strong>1. Basic Connectivity:</strong> {testResults.csrfToken || 'Not tested'}</div>
          <div><strong>2. Frappe System API:</strong> {testResults.dashboardStats || 'Not tested'}</div>
          <div><strong>3. Custom User API:</strong> {testResults.userDetails || 'Not tested'}</div>
          <div><strong>4. Custom Stats API:</strong> {testResults.doctypeRecords || 'Not tested'}</div>
          {testResults.error && <div style={{color: 'red'}}><strong>Error:</strong> {testResults.error}</div>}
        </div>
        <div style={{ marginTop: '10px', fontSize: '12px', color: '#666' }}>
          <p><strong>Expected Results:</strong></p>
          <ul>
            <li>✅ Basic Connectivity should succeed (tests proxy connection)</li>
            <li>✅ Frappe System API should succeed (tests Frappe API)</li>
            <li>❌ Custom APIs will fail until you deploy the API file to your server</li>
          </ul>
          <p><strong>If Basic Connectivity fails:</strong> Check your Frappe server is running and accessible</p>
        </div>
      </div>
    </div>
  );
};

export default ApiTest;
