'use client';

import { useState } from 'react';
import { Button, Card, Collapse, Input, Space, Spin, Tag, Typography } from 'antd';

import { apiClient } from '@/lib/api/client';
import { AUTH_ENDPOINTS, API_BASE_URL } from '@/lib/api/endpoints';

const { Title, Paragraph, Text } = Typography;

export default function DebugPageClient() {
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<Array<{ name: string; result: string; status: 'success' | 'error' | 'info' }>>([]);
  const [apiUrl, setApiUrl] = useState(API_BASE_URL);

  const addResult = (name: string, result: string, status: 'success' | 'error' | 'info' = 'info') => {
    setResults((prev) => [...prev, { name, result, status }]);
  };

  const clearResults = () => {
    setResults([]);
  };

  const testLogin = async () => {
    setLoading(true);
    clearResults();
    addResult('API Base URL', apiUrl, 'info');

    try {
      addResult('Testing', `Calling POST ${AUTH_ENDPOINTS.login}...`, 'info');
      const response = await apiClient.post(AUTH_ENDPOINTS.login);

      addResult('Response Status', `${response.status}`, 'success');
      addResult('Response Data', JSON.stringify(response.data, null, 2), 'success');

      if (response.data?.data?.session) {
        addResult('Session Found', 'Login endpoint returns session (bypass_sso: true)', 'success');
      } else if (response.data?.data?.url) {
        addResult('OAuth URL Found', 'Login endpoint returns OAuth URL (bypass_sso: false)', 'info');
      } else {
        addResult('Unexpected Response', 'Response does not contain session or url', 'error');
      }
    } catch (error: any) {
      addResult('Error Type', error.name || 'Unknown', 'error');
      addResult('Error Message', error.message, 'error');

      if (error.response) {
        addResult('Response Status', `${error.response.status}`, 'error');
        addResult('Response Data', JSON.stringify(error.response.data, null, 2), 'error');
      } else if (error.request) {
        addResult('Request Error', 'No response from server (CORS or network issue)', 'error');
        addResult(
          'Debugging Tips',
          'Check:\n' +
            '1. Backend is running on ' + apiUrl + '\n' +
            '2. No firewall blocking port\n' +
            '3. CORS headers in backend response',
          'error',
        );
      }
    } finally {
      setLoading(false);
    }
  };

  const testBackendHealth = async () => {
    setLoading(true);
    clearResults();

    try {
      addResult('Testing', 'Checking if backend is accessible...', 'info');
      const response = await fetch(`${apiUrl}/health`, { method: 'GET' });

      if (response.ok) {
        addResult('Backend Status', 'Backend is running ✅', 'success');
        const data = await response.json();
        addResult('Health Response', JSON.stringify(data, null, 2), 'success');
      } else {
        addResult('Backend Status', `HTTP ${response.status}`, 'error');
      }
    } catch (error: any) {
      addResult('Backend Status', `Cannot reach backend at ${apiUrl}`, 'error');
      addResult(
        'Debugging Tips',
        'Check:\n' +
          '1. Backend is running: cd security-center-backend && make run\n' +
          '2. Backend is on port 8080\n' +
          '3. API URL is correct: ' + apiUrl,
        'error',
      );
    } finally {
      setLoading(false);
    }
  };

  const testCORS = async () => {
    setLoading(true);
    clearResults();

    try {
      addResult('Testing', 'Checking CORS headers...', 'info');
      const response = await fetch(`${apiUrl}${AUTH_ENDPOINTS.login}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      const corsHeader = response.headers.get('access-control-allow-origin');
      addResult('CORS Allow-Origin', corsHeader || 'Not set', corsHeader ? 'success' : 'error');

      const data = await response.json();
      addResult('Response', JSON.stringify(data, null, 2), response.ok ? 'success' : 'error');
    } catch (error: any) {
      addResult('CORS Test', `Error: ${error.message}`, 'error');
    } finally {
      setLoading(false);
    }
  };

  const testConfig = async () => {
    setLoading(true);
    clearResults();

    addResult('Frontend Config', `API_BASE_URL = ${API_BASE_URL}`, 'info');
    addResult('Login Endpoint', `${AUTH_ENDPOINTS.login}`, 'info');
    addResult('Callback Endpoint', `${AUTH_ENDPOINTS.callback}`, 'info');
    addResult('Me Endpoint', `${AUTH_ENDPOINTS.me}`, 'info');
    addResult('Logout Endpoint', `${AUTH_ENDPOINTS.logout}`, 'info');

    try {
      const localStorageData = localStorage.getItem('security-center:tokens');
      addResult('Stored Tokens', localStorageData ? '✓ Found' : '✗ Not found', localStorageData ? 'success' : 'info');
    } catch {
      addResult('Storage Check', 'Cannot access localStorage', 'error');
    }

    setLoading(false);
  };

  return (
    <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
      <Title level={2}>🔧 Security Center Debug Page</Title>
      <Paragraph>Use this page to diagnose login issues.</Paragraph>

      <Card style={{ marginBottom: '20px' }}>
        <Title level={4}>API Configuration</Title>
        <Space direction="vertical" style={{ width: '100%' }}>
          <div>
            <Text>API Base URL:</Text>
            <Input
              value={apiUrl}
              onChange={(e) => setApiUrl(e.target.value)}
              style={{ width: '400px' }}
              placeholder="http://localhost:8080/api/v1"
            />
          </div>
          <div>
            <Button onClick={testConfig} loading={loading}>
              Show Configuration
            </Button>
          </div>
        </Space>
      </Card>

      <Card style={{ marginBottom: '20px' }}>
        <Title level={4}>Diagnostics</Title>
        <Space wrap>
          <Button type="primary" onClick={testBackendHealth} loading={loading}>
            Test Backend Health
          </Button>
          <Button onClick={testCORS} loading={loading}>
            Test CORS Headers
          </Button>
          <Button onClick={testLogin} loading={loading} danger>
            Test Login Endpoint
          </Button>
          <Button onClick={clearResults}>Clear Results</Button>
        </Space>
      </Card>

      {loading && <Spin style={{ display: 'block', textAlign: 'center', marginBottom: '20px' }} />}

      {results.length > 0 && (
        <Card title="Results">
          <Space direction="vertical" style={{ width: '100%' }}>
            {results.map((item, index) => (
              <Card
                key={index}
                style={{
                  backgroundColor:
                    item.status === 'success'
                      ? '#f6ffed'
                      : item.status === 'error'
                        ? '#fff1f0'
                        : '#e6f7ff',
                }}
              >
                <div style={{ marginBottom: '8px' }}>
                  <Text strong>{item.name}</Text>
                  <Tag
                    color={
                      item.status === 'success'
                        ? 'green'
                        : item.status === 'error'
                          ? 'red'
                          : 'blue'
                    }
                    style={{ marginLeft: '10px' }}
                  >
                    {item.status.toUpperCase()}
                  </Tag>
                </div>
                <pre
                  style={{
                    backgroundColor: 'white',
                    padding: '10px',
                    borderRadius: '4px',
                    overflow: 'auto',
                    maxHeight: '300px',
                    whiteSpace: 'pre-wrap',
                    wordWrap: 'break-word',
                  }}
                >
                  {item.result}
                </pre>
              </Card>
            ))}
          </Space>
        </Card>
      )}

      <Card style={{ marginTop: '20px', backgroundColor: '#fafafa' }}>
        <Title level={4}>💡 How to Use</Title>
        <ol>
          <li>
            Make sure backend is running:
            <code style={{ backgroundColor: '#f0f0f0', padding: '2px 6px', borderRadius: '3px', marginLeft: '5px' }}>
              cd security-center-backend && make run
            </code>
          </li>
          <li>
            Click <strong>Test Backend Health</strong> to verify backend is accessible
          </li>
          <li>
            Click <strong>Test Login Endpoint</strong> to simulate the login click
          </li>
          <li>
            Check the browser console (F12) for detailed logs marked with [API]
          </li>
          <li>If tests pass, the issue is in the frontend. If they fail, the issue is the backend.</li>
        </ol>
      </Card>

      <Card style={{ marginTop: '20px', backgroundColor: '#fff7e6' }}>
        <Title level={4}>🔍 What to Look For</Title>
        <Collapse
          items={[
            {
              key: '1',
              label: 'Test Backend Health Fails',
              children:
                'Backend is not running or not accessible. Verify:\n' +
                '1. Terminal shows "http server listening"\n' +
                '2. Port 8080 is not in use: lsof -i :8080\n' +
                '3. Firewall is not blocking localhost:8080',
            },
            {
              key: '2',
              label: 'Test Login Returns Error Response',
              children:
                'Backend is running but returning an error. Check:\n' +
                '1. Database is running and initialized\n' +
                '2. Backend logs show "bypass_sso":true\n' +
                '3. Run: bash scripts/reset-db-simple.sh',
            },
            {
              key: '3',
              label: 'Test Login Returns Wrong Format',
              children:
                'Response exists but missing session/url field. Check:\n' +
                '1. Verify response includes data.session or data.url\n' +
                '2. Frontend expects: {"data": {"session": {...}}}\n' +
                '3. If you see URL instead of session, bypass_sso is false',
            },
            {
              key: '4',
              label: 'CORS Error (No Access-Control-Allow-Origin)',
              children:
                'Browser blocks request due to CORS. Verify:\n' +
                '1. Backend CORS middleware is enabled\n' +
                '2. Frontend URL http://localhost:3000 is in allowed_origins\n' +
                '3. Check config.yaml: http.allowed_origins',
            },
          ]}
        />
      </Card>
    </div>
  );
}
