/**
 * URL Tracking Page for Redirect Intelligence v2
 * 
 * Advanced form for tracking URLs with analysis options
 */

import React, { useState } from 'react';
import {
  Box,
  Heading,
  Text,
  VStack,
  HStack,
  FormControl,
  FormLabel,
  Input,
  Select,
  Switch,
  Button,
  Card,
  CardBody,
  CardHeader,
  Container,
  useToast,
  Alert,
  AlertIcon,
  Collapse,
  FormHelperText,
  Slider,
  SliderTrack,
  SliderFilledTrack,
  SliderThumb,
  NumberInput,
  NumberInputField,
  NumberInputStepper,
  NumberIncrementStepper,
  NumberDecrementStepper,
  Textarea,
  Badge,
  Divider,
} from '@chakra-ui/react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';

import { trackingApi, TrackRequestV2 } from '../services/api';
import { TrackingResults } from '../components/Tracking/TrackingResults';
import { useAuth } from '../contexts/AuthContext';

const trackingSchema = z.object({
  url: z.string().min(1, 'URL is required').url('Invalid URL format'),
  method: z.enum(['GET', 'POST', 'HEAD']),
  userAgent: z.string().optional(),
  maxHops: z.number().min(1).max(20),
  timeout: z.number().min(1000).max(30000),
  enableSSLAnalysis: z.boolean(),
  enableSEOAnalysis: z.boolean(),
  enableSecurityAnalysis: z.boolean(),
  customHeaders: z.string().optional(),
});

type TrackingFormData = z.infer<typeof trackingSchema>;

export function TrackingPage() {
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [trackingResult, setTrackingResult] = useState<any>(null);
  const toast = useToast();
  const navigate = useNavigate();
  const { isAuthenticated } = useAuth();

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    formState: { errors },
  } = useForm<TrackingFormData>({
    resolver: zodResolver(trackingSchema),
    defaultValues: {
      method: 'GET',
      maxHops: 10,
      timeout: 15000,
      enableSSLAnalysis: true,
      enableSEOAnalysis: true,
      enableSecurityAnalysis: true,
    },
  });

  const maxHops = watch('maxHops');
  const timeout = watch('timeout');

  const trackingMutation = useMutation({
    mutationFn: async (data: TrackRequestV2) => {
      return await trackingApi.trackUrlV2(data);
    },
    onSuccess: (result) => {
      setTrackingResult(result);
      toast({
        title: 'Tracking completed',
        description: `Found ${result.check.redirectCount} redirects`,
        status: 'success',
        duration: 3000,
        isClosable: true,
      });

      // Navigate to check detail page for authenticated users
      if (isAuthenticated) {
        navigate(`/check/${result.check.id}`);
      }
    },
    onError: (error: any) => {
      toast({
        title: 'Tracking failed',
        description: error.response?.data?.message || 'An error occurred',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    },
  });

  const onSubmit = (data: TrackingFormData) => {
    let headers: Record<string, string> = {};
    
    // Parse custom headers if provided
    if (data.customHeaders) {
      try {
        const lines = data.customHeaders.split('\n').filter(line => line.trim());
        for (const line of lines) {
          const [key, ...valueParts] = line.split(':');
          if (key && valueParts.length > 0) {
            headers[key.trim()] = valueParts.join(':').trim();
          }
        }
      } catch (error) {
        toast({
          title: 'Invalid headers format',
          description: 'Please use format: Header-Name: Header-Value',
          status: 'error',
          duration: 3000,
          isClosable: true,
        });
        return;
      }
    }

    const trackRequest: TrackRequestV2 = {
      url: data.url,
      method: data.method,
      userAgent: data.userAgent,
      headers: Object.keys(headers).length > 0 ? headers : undefined,
      maxHops: data.maxHops,
      timeout: data.timeout,
      enableSSLAnalysis: data.enableSSLAnalysis,
      enableSEOAnalysis: data.enableSEOAnalysis,
      enableSecurityAnalysis: data.enableSecurityAnalysis,
    };

    trackingMutation.mutate(trackRequest);
  };

  return (
    <Container maxW="4xl">
      <VStack spacing={8} align="stretch">
        {/* Header */}
        <Box textAlign="center">
          <Heading as="h1" size="xl" mb={4}>
            URL Redirect Tracker
          </Heading>
          <Text fontSize="lg" color="gray.600">
            Track redirects and analyze SSL, SEO, and security with comprehensive insights
          </Text>
        </Box>

        {/* Tracking Form */}
        <Card>
          <CardHeader>
            <HStack justify="space-between">
              <Heading as="h2" size="md">
                Track URL
              </Heading>
              <Badge colorScheme="brand">Enhanced v2</Badge>
            </HStack>
          </CardHeader>
          
          <CardBody>
            <form onSubmit={handleSubmit(onSubmit)}>
              <VStack spacing={6} align="stretch">
                {/* URL Input */}
                <FormControl isInvalid={!!errors.url}>
                  <FormLabel>URL to Track</FormLabel>
                  <Input
                    {...register('url')}
                    placeholder="https://example.com or example.com"
                    size="lg"
                  />
                  {errors.url && (
                    <Text color="red.500" fontSize="sm" mt={1}>
                      {errors.url.message}
                    </Text>
                  )}
                  <FormHelperText>
                    Enter the URL you want to track. Protocol (http/https) is optional.
                  </FormHelperText>
                </FormControl>

                {/* Method Selection */}
                <FormControl>
                  <FormLabel>HTTP Method</FormLabel>
                  <Select {...register('method')}>
                    <option value="GET">GET</option>
                    <option value="HEAD">HEAD</option>
                    <option value="POST">POST</option>
                  </Select>
                  <FormHelperText>
                    HTTP method to use for the initial request
                  </FormHelperText>
                </FormControl>

                {/* Analysis Options */}
                <FormControl>
                  <FormLabel>Analysis Options</FormLabel>
                  <VStack align="start" spacing={3}>
                    <HStack justify="space-between" w="full">
                      <Text>SSL Certificate Analysis</Text>
                      <Switch {...register('enableSSLAnalysis')} colorScheme="brand" />
                    </HStack>
                    <HStack justify="space-between" w="full">
                      <Text>SEO Optimization Analysis</Text>
                      <Switch {...register('enableSEOAnalysis')} colorScheme="brand" />
                    </HStack>
                    <HStack justify="space-between" w="full">
                      <Text>Security Vulnerability Scan</Text>
                      <Switch {...register('enableSecurityAnalysis')} colorScheme="brand" />
                    </HStack>
                  </VStack>
                  <FormHelperText>
                    Enable advanced analysis features (recommended)
                  </FormHelperText>
                </FormControl>

                {/* Advanced Options Toggle */}
                <Button
                  variant="ghost"
                  onClick={() => setShowAdvanced(!showAdvanced)}
                  size="sm"
                >
                  {showAdvanced ? 'Hide' : 'Show'} Advanced Options
                </Button>

                {/* Advanced Options */}
                <Collapse in={showAdvanced}>
                  <VStack spacing={6} align="stretch">
                    <Divider />

                    {/* Max Hops */}
                    <FormControl>
                      <FormLabel>Maximum Hops: {maxHops}</FormLabel>
                      <Slider
                        value={maxHops}
                        onChange={(value) => setValue('maxHops', value)}
                        min={1}
                        max={20}
                        step={1}
                        colorScheme="brand"
                      >
                        <SliderTrack>
                          <SliderFilledTrack />
                        </SliderTrack>
                        <SliderThumb />
                      </Slider>
                      <FormHelperText>
                        Maximum number of redirects to follow (1-20)
                      </FormHelperText>
                    </FormControl>

                    {/* Timeout */}
                    <FormControl>
                      <FormLabel>Timeout (milliseconds)</FormLabel>
                      <NumberInput
                        value={timeout}
                        onChange={(valueString) => setValue('timeout', parseInt(valueString) || 15000)}
                        min={1000}
                        max={30000}
                        step={1000}
                      >
                        <NumberInputField />
                        <NumberInputStepper>
                          <NumberIncrementStepper />
                          <NumberDecrementStepper />
                        </NumberInputStepper>
                      </NumberInput>
                      <FormHelperText>
                        Request timeout in milliseconds (1000-30000)
                      </FormHelperText>
                    </FormControl>

                    {/* User Agent */}
                    <FormControl>
                      <FormLabel>Custom User Agent</FormLabel>
                      <Input
                        {...register('userAgent')}
                        placeholder="Mozilla/5.0 (compatible; RedirectTracker/2.0)"
                      />
                      <FormHelperText>
                        Custom User-Agent header (optional)
                      </FormHelperText>
                    </FormControl>

                    {/* Custom Headers */}
                    <FormControl>
                      <FormLabel>Custom Headers</FormLabel>
                      <Textarea
                        {...register('customHeaders')}
                        placeholder="Accept: application/json&#10;X-Custom-Header: value"
                        rows={4}
                        resize="vertical"
                      />
                      <FormHelperText>
                        Custom headers, one per line in format: Header-Name: Header-Value
                      </FormHelperText>
                    </FormControl>
                  </VStack>
                </Collapse>

                {/* Rate Limiting Warning */}
                {!isAuthenticated && (
                  <Alert status="info" borderRadius="md">
                    <AlertIcon />
                    <VStack align="start" spacing={1}>
                      <Text fontWeight="medium">Anonymous Usage</Text>
                      <Text fontSize="sm">
                        Anonymous users are limited to 50 requests per hour. 
                        <Text as="span" color="brand.500" fontWeight="medium">
                          {' '}Sign up for higher limits and saved results.
                        </Text>
                      </Text>
                    </VStack>
                  </Alert>
                )}

                {/* Submit Button */}
                <Button
                  type="submit"
                  colorScheme="brand"
                  size="lg"
                  isLoading={trackingMutation.isPending}
                  loadingText="Tracking..."
                >
                  Track URL
                </Button>
              </VStack>
            </form>
          </CardBody>
        </Card>

        {/* Results */}
        {trackingResult && (
          <TrackingResults result={trackingResult} />
        )}
      </VStack>
    </Container>
  );
}
