import React, { useState } from 'react';
import { 
  Box, 
  Typography, 
  Button, 
  TextInput, 
  Grid, 
  Card,
  CardBody,
  CardHeader,
  CardContent,
  Badge,
  Flex,
  Divider
} from '@strapi/design-system';
import { Play, CheckCircle, Key } from '@strapi/icons';
import logo from '../assets/logo.svg';

const App = () => {
  const [testToken, setTestToken] = useState('');
  const [testResult, setTestResult] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  const handleTestToken = async () => {
    if (!testToken.trim()) {
      setTestResult({ success: false, message: 'Please enter a token to test' });
      return;
    }

    setIsLoading(true);
    try {
      const response = await fetch('/api/obo-auth/exchange-token', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ token: testToken }),
      });

      const data = await response.json();
      
      if (response.ok) {
        setTestResult({ 
          success: true, 
          message: 'Token exchange successful!', 
          data: data 
        });
      } else {
        setTestResult({ 
          success: false, 
          message: data.error?.message || 'Token exchange failed',
          details: data.error?.details 
        });
      }
    } catch (error) {
      setTestResult({ 
        success: false, 
        message: 'Network error: ' + error.message 
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleTestEndpoint = async () => {
    setIsLoading(true);
    try {
      const response = await fetch('/api/obo-auth/test');
      const data = await response.json();
      
      if (response.ok) {
        setTestResult({ 
          success: true, 
          message: 'Test endpoint working!', 
          data: data 
        });
      } else {
        setTestResult({ 
          success: false, 
          message: 'Test endpoint failed' 
        });
      }
    } catch (error) {
      setTestResult({ 
        success: false, 
        message: 'Network error: ' + error.message 
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Box padding={8} background="neutral100" minHeight="100vh">
      {/* Header with Logo */}
      <Box 
        padding={6} 
        background="neutral0" 
        hasRadius 
        shadow="filterShadow"
        marginBottom={6}
      >
        <Flex direction="column" alignItems="center" gap={4}>
          <img src={logo} alt="tenx OBO" style={{ height: '80px' }} />
          <Typography variant="alpha" textColor="neutral800" fontWeight="bold">
            OBO Authentication Plugin
          </Typography>
          <Typography variant="pi" textColor="neutral600" textAlign="center" style={{ maxWidth: '600px' }}>
            Secure On-Behalf-Of token exchange for microservice authentication. 
            Exchange existing JWT tokens for new ones with proper validation and user verification.
          </Typography>
        </Flex>
      </Box>

      <Flex direction="column" gap={4}>
        {/* Status Card */}
        <Card shadow="filterShadow">
          <CardHeader>
            <Flex alignItems="center" gap={3}>
              <Box 
                padding={2} 
                background="success100" 
                hasRadius 
                style={{ borderRadius: '50%' }}
              >
                <CheckCircle color="success600" width="20px" height="20px" />
              </Box>
              <Typography variant="beta" fontWeight="bold">System Status</Typography>
            </Flex>
          </CardHeader>
          <CardContent>
            <Flex direction="column" gap={3}>
              <Flex alignItems="center" gap={3} padding={3} background="success50" hasRadius>
                <Badge backgroundColor="success100" textColor="success600" fontWeight="bold">
                  ✓ ACTIVE
                </Badge>
                <Typography variant="pi" fontWeight="medium">Plugin is loaded and running</Typography>
              </Flex>
              <Flex alignItems="center" gap={3} padding={3} background="primary50" hasRadius>
                <Badge backgroundColor="primary100" textColor="primary600" fontWeight="bold">
                  ✓ API READY
                </Badge>
                <Typography variant="pi" fontWeight="medium">Endpoint: /api/obo-auth/exchange-token</Typography>
              </Flex>
            </Flex>
          </CardContent>
        </Card>

        <Flex gap={4} alignItems="stretch">
          {/* Test Endpoint Card */}
          <Box style={{ flex: 1, display: 'flex' }}>
            <Card shadow="filterShadow" style={{ width: '100%', display: 'flex', flexDirection: 'column' }}>
              <CardHeader>
                <Flex alignItems="center" gap={3}>
                  <Box 
                    padding={2} 
                    background="primary100" 
                    hasRadius 
                    style={{ borderRadius: '50%' }}
                  >
                    <Play color="primary600" width="20px" height="20px" />
                  </Box>
                  <Typography variant="beta" fontWeight="bold">Connection Test</Typography>
                </Flex>
              </CardHeader>
              <CardContent style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
                <Flex direction="column" gap={4} style={{ flex: 1 }}>
                  <Typography variant="pi" textColor="neutral600">
                    Verify that the plugin endpoint is responding correctly and the API is accessible.
                  </Typography>
                  <Box style={{ marginTop: 'auto' }}>
                    <Button 
                      onClick={handleTestEndpoint}
                      loading={isLoading}
                      startIcon={<Play />}
                      fullWidth
                      size="L"
                    >
                      Test Connection
                    </Button>
                  </Box>
                </Flex>
              </CardContent>
            </Card>
          </Box>

          {/* Token Exchange Card */}
          <Box style={{ flex: 1, display: 'flex' }}>
            <Card shadow="filterShadow" style={{ width: '100%', display: 'flex', flexDirection: 'column' }}>
              <CardHeader>
                <Flex alignItems="center" gap={3}>
                  <Box 
                    padding={2} 
                    background="warning100" 
                    hasRadius 
                    style={{ borderRadius: '50%' }}
                  >
                    <Key color="warning600" width="20px" height="20px" />
                  </Box>
                  <Typography variant="beta" fontWeight="bold">Token Exchange</Typography>
                </Flex>
              </CardHeader>
              <CardContent style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
                <Flex direction="column" gap={4} style={{ flex: 1 }}>
                  <Typography variant="pi" textColor="neutral600">
                    Test the OBO token exchange flow with a valid JWT token.
                  </Typography>
                  <TextInput
                    placeholder="Enter JWT token to test..."
                    value={testToken}
                    onChange={(e) => setTestToken(e.target.value)}
                    size="L"
                  />
                  <Box style={{ marginTop: 'auto' }}>
                    <Button 
                      onClick={handleTestToken}
                      loading={isLoading}
                      startIcon={<Key />}
                      fullWidth
                      size="L"
                    >
                      Exchange Token
                    </Button>
                  </Box>
                </Flex>
              </CardContent>
            </Card>
          </Box>
        </Flex>

        {/* Results Card */}
        {testResult && (
          <Card shadow="filterShadow">
            <CardHeader>
              <Flex alignItems="center" gap={3}>
                <Box 
                  padding={2} 
                  background={testResult.success ? "success100" : "danger100"} 
                  hasRadius 
                  style={{ borderRadius: '50%' }}
                >
                  <CheckCircle color={testResult.success ? "success600" : "danger600"} width="20px" height="20px" />
                </Box>
                <Typography variant="beta" fontWeight="bold">Test Results</Typography>
              </Flex>
            </CardHeader>
            <CardContent>
              <Flex direction="column" gap={4}>
                <Box 
                  padding={3} 
                  background={testResult.success ? "success50" : "danger50"} 
                  hasRadius
                >
                  <Badge 
                    backgroundColor={testResult.success ? "success100" : "danger100"}
                    textColor={testResult.success ? "success600" : "danger600"}
                    fontWeight="bold"
                  >
                    {testResult.success ? "✓ SUCCESS" : "✗ ERROR"}
                  </Badge>
                  <Typography variant="pi" fontWeight="medium" style={{ marginTop: '8px' }}>
                    {testResult.message}
                  </Typography>
                </Box>
                
                {testResult.details && (
                  <Box padding={3} background="neutral50" hasRadius>
                    <Typography variant="pi" fontWeight="bold" marginBottom={2}>Error Details:</Typography>
                    <Typography variant="pi" textColor="neutral600" style={{ fontFamily: 'monospace', fontSize: '12px' }}>
                      {JSON.stringify(testResult.details, null, 2)}
                    </Typography>
                  </Box>
                )}
                
                {testResult.data && (
                  <Box padding={3} background="neutral50" hasRadius>
                    <Typography variant="pi" fontWeight="bold" marginBottom={2}>Response Data:</Typography>
                    <Typography variant="pi" textColor="neutral600" style={{ fontFamily: 'monospace', fontSize: '12px' }}>
                      {JSON.stringify(testResult.data, null, 2)}
                    </Typography>
                  </Box>
                )}
              </Flex>
            </CardContent>
          </Card>
        )}

        {/* API Documentation Card */}
        <Card shadow="filterShadow">
          <CardHeader>
            <Typography variant="beta" fontWeight="bold">API Documentation</Typography>
          </CardHeader>
          <CardContent>
            <Flex direction="column" gap={4}>
              <Box padding={3} background="primary50" hasRadius>
                <Typography variant="pi" fontWeight="bold" color="primary600" marginBottom={2}>
                  POST /api/obo-auth/exchange-token
                </Typography>
                <Typography variant="pi" textColor="neutral600">
                  Exchange an existing JWT token for a new one using the On-Behalf-Of (OBO) authentication flow.
                </Typography>
              </Box>
              
              <Box padding={3} background="neutral50" hasRadius>
                <Typography variant="pi" fontWeight="bold" marginBottom={2}>Request Body:</Typography>
                <Box padding={2} background="neutral0" hasRadius>
                  <Typography variant="pi" textColor="neutral600" style={{ fontFamily: 'monospace' }}>
                    {`{ "token": "your-jwt-token-here" }`}
                  </Typography>
                </Box>
              </Box>
              
              <Box padding={3} background="neutral50" hasRadius>
                <Typography variant="pi" fontWeight="bold" marginBottom={2}>Success Response:</Typography>
                <Box padding={2} background="neutral0" hasRadius>
                  <Typography variant="pi" textColor="neutral600" style={{ fontFamily: 'monospace' }}>
                    {`{ "jwt": "new-jwt-token", "user": { ... } }`}
                  </Typography>
                </Box>
              </Box>
              
              <Box padding={3} background="neutral50" hasRadius>
                <Typography variant="pi" fontWeight="bold" marginBottom={2}>Error Response:</Typography>
                <Box padding={2} background="neutral0" hasRadius>
                  <Typography variant="pi" textColor="neutral600" style={{ fontFamily: 'monospace' }}>
                    {`{ "data": null, "error": { "status": 400, "name": "BadRequestError", "message": "Invalid token provided." } }`}
                  </Typography>
                </Box>
              </Box>
            </Flex>
          </CardContent>
        </Card>
      </Flex>
    </Box>
  );
};

export default App;