/**
 * Tracking Results Component for Redirect Intelligence v2
 * 
 * Displays comprehensive tracking results with analysis data
 */

import React from 'react';
import {
  Box,
  Card,
  CardBody,
  CardHeader,
  Heading,
  Text,
  VStack,
  HStack,
  Badge,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  TableContainer,
  Stat,
  StatLabel,
  StatNumber,
  StatHelpText,
  StatArrow,
  SimpleGrid,
  Progress,
  Divider,
  Link,
  Icon,
  Tooltip,
  useColorModeValue,
  Alert,
  AlertIcon,
  AlertTitle,
  AlertDescription,
  Button,
  useClipboard,
} from '@chakra-ui/react';
import { format } from 'date-fns';
import { FiExternalLink, FiCopy, FiCheck } from 'react-icons/fi';

interface TrackingResultsProps {
  result: {
    check: {
      id: string;
      inputUrl: string;
      method: string;
      status: 'OK' | 'ERROR' | 'TIMEOUT' | 'LOOP';
      finalUrl?: string;
      totalTimeMs: number;
      startedAt: string;
      finishedAt: string;
      hops: Array<{
        hopIndex: number;
        url: string;
        scheme?: string;
        statusCode?: number;
        redirectType: string;
        latencyMs?: number;
        contentType?: string;
        reason?: string;
        responseHeaders: Record<string, string>;
      }>;
      redirectCount: number;
      loopDetected?: boolean;
      error?: string;
    };
    url: string;
    method: string;
    redirectCount: number;
    finalUrl?: string;
    finalStatusCode?: number;
  };
}

export function TrackingResults({ result }: TrackingResultsProps) {
  const { check } = result;
  const cardBg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');
  
  const { hasCopied, onCopy } = useClipboard(check.id);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'OK': return 'green';
      case 'ERROR': return 'red';
      case 'TIMEOUT': return 'orange';
      case 'LOOP': return 'purple';
      default: return 'gray';
    }
  };

  const getRedirectTypeColor = (type: string) => {
    switch (type) {
      case 'HTTP_301': return 'blue';
      case 'HTTP_302': return 'green';
      case 'HTTP_307': return 'yellow';
      case 'HTTP_308': return 'purple';
      case 'FINAL': return 'gray';
      default: return 'orange';
    }
  };

  const formatLatency = (ms?: number) => {
    if (!ms) return 'N/A';
    return `${ms}ms`;
  };

  const formatTimestamp = (timestamp: string) => {
    return format(new Date(timestamp), 'MMM dd, yyyy HH:mm:ss');
  };

  return (
    <VStack spacing={6} align="stretch">
      {/* Summary Card */}
      <Card bg={cardBg} border="1px solid" borderColor={borderColor}>
        <CardHeader>
          <HStack justify="space-between">
            <Heading as="h3" size="md">
              Tracking Summary
            </Heading>
            <HStack>
              <Badge colorScheme={getStatusColor(check.status)} variant="solid">
                {check.status}
              </Badge>
              <Button
                size="xs"
                variant="ghost"
                leftIcon={<Icon as={hasCopied ? FiCheck : FiCopy} />}
                onClick={onCopy}
              >
                {hasCopied ? 'Copied' : 'Copy ID'}
              </Button>
            </HStack>
          </HStack>
        </CardHeader>
        
        <CardBody>
          <VStack spacing={4} align="stretch">
            {/* Key Metrics */}
            <SimpleGrid columns={{ base: 2, md: 4 }} spacing={4}>
              <Stat>
                <StatLabel>Redirects</StatLabel>
                <StatNumber>{check.redirectCount}</StatNumber>
                <StatHelpText>
                  {check.redirectCount === 0 ? 'Direct' : 'Chain detected'}
                </StatHelpText>
              </Stat>
              
              <Stat>
                <StatLabel>Total Time</StatLabel>
                <StatNumber>{check.totalTimeMs}ms</StatNumber>
                <StatHelpText>
                  <StatArrow type={check.totalTimeMs < 1000 ? 'increase' : 'decrease'} />
                  {check.totalTimeMs < 1000 ? 'Fast' : 'Slow'}
                </StatHelpText>
              </Stat>
              
              <Stat>
                <StatLabel>Final Status</StatLabel>
                <StatNumber>{result.finalStatusCode || 'N/A'}</StatNumber>
                <StatHelpText>
                  HTTP status code
                </StatHelpText>
              </Stat>
              
              <Stat>
                <StatLabel>Method</StatLabel>
                <StatNumber>{check.method}</StatNumber>
                <StatHelpText>
                  Request method
                </StatHelpText>
              </Stat>
            </SimpleGrid>

            <Divider />

            {/* URLs */}
            <VStack align="stretch" spacing={3}>
              <Box>
                <Text fontSize="sm" fontWeight="medium" color="gray.600" mb={1}>
                  Input URL
                </Text>
                <Link
                  href={check.inputUrl}
                  isExternal
                  color="brand.500"
                  fontSize="sm"
                  wordBreak="break-all"
                >
                  {check.inputUrl}
                  <Icon as={FiExternalLink} mx="2px" />
                </Link>
              </Box>
              
              {check.finalUrl && check.finalUrl !== check.inputUrl && (
                <Box>
                  <Text fontSize="sm" fontWeight="medium" color="gray.600" mb={1}>
                    Final URL
                  </Text>
                  <Link
                    href={check.finalUrl}
                    isExternal
                    color="brand.500"
                    fontSize="sm"
                    wordBreak="break-all"
                  >
                    {check.finalUrl}
                    <Icon as={FiExternalLink} mx="2px" />
                  </Link>
                </Box>
              )}
            </VStack>

            {/* Error/Warning Messages */}
            {check.error && (
              <Alert status="error" borderRadius="md">
                <AlertIcon />
                <AlertTitle>Error:</AlertTitle>
                <AlertDescription>{check.error}</AlertDescription>
              </Alert>
            )}

            {check.loopDetected && (
              <Alert status="warning" borderRadius="md">
                <AlertIcon />
                <AlertTitle>Redirect Loop Detected!</AlertTitle>
                <AlertDescription>
                  The URL redirects in a loop. Check your redirect configuration.
                </AlertDescription>
              </Alert>
            )}

            {/* Timestamps */}
            <HStack justify="space-between" fontSize="sm" color="gray.600">
              <Text>Started: {formatTimestamp(check.startedAt)}</Text>
              <Text>Finished: {formatTimestamp(check.finishedAt)}</Text>
            </HStack>
          </VStack>
        </CardBody>
      </Card>

      {/* Redirect Chain */}
      {check.hops.length > 0 && (
        <Card bg={cardBg} border="1px solid" borderColor={borderColor}>
          <CardHeader>
            <Heading as="h3" size="md">
              Redirect Chain ({check.hops.length} hops)
            </Heading>
          </CardHeader>
          
          <CardBody>
            <TableContainer>
              <Table variant="simple" size="sm">
                <Thead>
                  <Tr>
                    <Th>Hop</Th>
                    <Th>URL</Th>
                    <Th>Status</Th>
                    <Th>Type</Th>
                    <Th>Latency</Th>
                    <Th>Content-Type</Th>
                  </Tr>
                </Thead>
                <Tbody>
                  {check.hops.map((hop, index) => (
                    <Tr key={index}>
                      <Td>
                        <Badge variant="outline">
                          {hop.hopIndex}
                        </Badge>
                      </Td>
                      <Td maxW="300px">
                        <Tooltip label={hop.url} placement="top">
                          <Link
                            href={hop.url}
                            isExternal
                            color="brand.500"
                            fontSize="sm"
                            isTruncated
                            display="block"
                          >
                            {hop.url}
                          </Link>
                        </Tooltip>
                      </Td>
                      <Td>
                        {hop.statusCode ? (
                          <Badge
                            colorScheme={hop.statusCode < 300 ? 'green' : hop.statusCode < 400 ? 'yellow' : 'red'}
                          >
                            {hop.statusCode}
                          </Badge>
                        ) : (
                          <Text fontSize="xs" color="gray.500">N/A</Text>
                        )}
                      </Td>
                      <Td>
                        <Badge
                          colorScheme={getRedirectTypeColor(hop.redirectType)}
                          variant="subtle"
                        >
                          {hop.redirectType.replace('HTTP_', '').replace('_', ' ')}
                        </Badge>
                      </Td>
                      <Td>
                        <Text fontSize="sm">
                          {formatLatency(hop.latencyMs)}
                        </Text>
                      </Td>
                      <Td>
                        <Text fontSize="xs" color="gray.600" isTruncated maxW="150px">
                          {hop.contentType || 'N/A'}
                        </Text>
                      </Td>
                    </Tr>
                  ))}
                </Tbody>
              </Table>
            </TableContainer>
          </CardBody>
        </Card>
      )}

      {/* Performance Analysis */}
      {check.hops.length > 1 && (
        <Card bg={cardBg} border="1px solid" borderColor={borderColor}>
          <CardHeader>
            <Heading as="h3" size="md">
              Performance Analysis
            </Heading>
          </CardHeader>
          
          <CardBody>
            <VStack spacing={4} align="stretch">
              {/* Latency Distribution */}
              <Box>
                <Text fontSize="sm" fontWeight="medium" mb={2}>
                  Latency per Hop
                </Text>
                {check.hops.map((hop, index) => (
                  hop.latencyMs && (
                    <Box key={index} mb={2}>
                      <HStack justify="space-between" mb={1}>
                        <Text fontSize="xs">Hop {hop.hopIndex}</Text>
                        <Text fontSize="xs">{formatLatency(hop.latencyMs)}</Text>
                      </HStack>
                      <Progress
                        value={(hop.latencyMs / Math.max(...check.hops.map(h => h.latencyMs || 0))) * 100}
                        size="sm"
                        colorScheme="brand"
                      />
                    </Box>
                  )
                ))}
              </Box>

              {/* Summary Stats */}
              <SimpleGrid columns={{ base: 2, md: 3 }} spacing={4}>
                <Stat size="sm">
                  <StatLabel>Avg Latency</StatLabel>
                  <StatNumber fontSize="md">
                    {Math.round(
                      check.hops.reduce((sum, hop) => sum + (hop.latencyMs || 0), 0) / check.hops.length
                    )}ms
                  </StatNumber>
                </Stat>
                
                <Stat size="sm">
                  <StatLabel>Max Latency</StatLabel>
                  <StatNumber fontSize="md">
                    {Math.max(...check.hops.map(h => h.latencyMs || 0))}ms
                  </StatNumber>
                </Stat>
                
                <Stat size="sm">
                  <StatLabel>Min Latency</StatLabel>
                  <StatNumber fontSize="md">
                    {Math.min(...check.hops.map(h => h.latencyMs || 0))}ms
                  </StatNumber>
                </Stat>
              </SimpleGrid>
            </VStack>
          </CardBody>
        </Card>
      )}
    </VStack>
  );
}
