import React, { useState } from 'react';
import {
  Box,
  Heading,
  Text,
  VStack,
  Button,
  useToast,
  List,
  ListItem,
  ListIcon,
  Alert,
  AlertIcon,
  AlertTitle,
  AlertDescription,
  HStack,
} from '@chakra-ui/react';
import { CheckCircleIcon, WarningIcon } from '@chakra-ui/icons';
import ApiService from '../../services/ApiService';

const SitemapAndValidationPanel = ({ hasCompletedValidation = false, onValidationComplete }) => {
  const [sitemap, setSitemap] = useState(null);
  const [isFetchingSitemap, setIsFetchingSitemap] = useState(false);
  const [sitemapError, setSitemapError] = useState(null);

  const [validationResult, setValidationResult] = useState(null);
  const [isValidating, setIsValidating] = useState(false);
  const [validationError, setValidationError] = useState(null);
  const toast = useToast();

  const handleFetchSitemap = async () => {
    setIsFetchingSitemap(true);
    setSitemapError(null);
    setValidationResult(null);
    setValidationError(null);
    try {
      const response = await ApiService.getSitemap();
      if (response.success && response.urls.length > 0) {
        setSitemap(response);
        toast({
          title: 'Sitemap Fetched',
          description: `Found ${response.urls.length} URLs in your sitemap.`,
          status: 'success',
          duration: 5000,
          isClosable: true,
        });
      } else {
        throw new Error(response.message || 'No URLs found in sitemap or failed to fetch.');
      }
    } catch (error) {
      setSitemapError(error.message);
      toast({
        title: 'Error Fetching Sitemap',
        description: error.message,
        status: 'error',
        duration: 9000,
        isClosable: true,
      });
    } finally {
      setIsFetchingSitemap(false);
    }
  };

  const handleValidatePages = async () => {
    if (!sitemap?.urls) return;

    setIsValidating(true);
    setValidationError(null);
    setValidationResult(null);

    const pagesToValidate = sitemap.urls.slice(0, 5);

    try {
      const response = await ApiService.validatePages({ pageUrls: pagesToValidate });
      if (response.success) {
        setValidationResult(response.results);
        const allValid = response.results && response.results.every(page => parseInt(page.status, 10) === 200);
        toast({
          title: 'Validation Complete',
          description: 'Page validation process finished.',
          status: 'success',
          duration: 5000,
          isClosable: true,
        });
        if (allValid) {
          onValidationComplete?.();
        }
      } else {
        throw new Error(response.data?.message || 'Page validation failed.');
      }
    } catch (error) {
      setValidationError(error.message);
      toast({
        title: 'Validation Error',
        description: error.message,
        status: 'error',
        duration: 9000,
        isClosable: true,
      });
    } finally {
      setIsValidating(false);
    }
  };

  const allPagesValid = validationResult && validationResult.every(page => page.status == 200);

  if (hasCompletedValidation) {
    return null;
  }

  return (
    <Box p={5} shadow="md" borderWidth="1px" borderRadius="md">
      <VStack align="stretch" spacing={4}>
        <Heading size="md">Site Setup & Validation</Heading>
        
        {/* Step 1: Fetch Sitemap */}
        <Box>
          <HStack justify="space-between">
             <Text fontWeight="bold">Step 1: Fetch Sitemap</Text>
             <Button
                onClick={handleFetchSitemap}
                isLoading={isFetchingSitemap}
                loadingText="Fetching..."
                colorScheme="gray"
                size="sm"
              >
                Fetch Sitemap
              </Button>
          </HStack>
          {sitemapError && <Text color="red.500" mt={2}>{sitemapError}</Text>}
        </Box>

        {/* Step 2: Validate Pages (shows after sitemap is fetched) */}
        {sitemap && (
          <Box mt={4} p={4} bg="gray.50" borderRadius="md">
            <Heading size="sm" mb={2}>Step 2: Validate Plugin Installation</Heading>
            <Text fontSize="sm" color="gray.600">
              We will check a few pages from your sitemap to ensure they can be translated correctly.
            </Text>
            <List spacing={2} my={4}>
              {sitemap.urls.slice(0, 5).map((url, index) => (
                <ListItem key={index} fontSize="sm">
                  <ListIcon as={CheckCircleIcon} color="green.500" />
                  {url}
                </ListItem>
              ))}
            </List>
            <Button
              onClick={handleValidatePages}
              isLoading={isValidating}
              loadingText="Validating..."
              colorScheme="blue"
              w="full"
              disabled={isFetchingSitemap}
            >
              Validate Pages
            </Button>
             {validationError && <Text color="red.500" mt={2}>{validationError}</Text>}
          </Box>
        )}

        {/* Validation Results */}
        {validationResult && (
            <Box mt={4}>
                {allPagesValid ? (
                     <Alert
                        status="success"
                        variant="subtle"
                        flexDirection="column"
                        alignItems="center"
                        justifyContent="center"
                        textAlign="center"
                        borderRadius="md"
                        p={4}
                    >
                        <AlertIcon boxSize="40px" mr={0} />
                        <AlertTitle mt={4} mb={1} fontSize="lg">
                           FluentC is installed correctly and working!
                        </AlertTitle>
                        <AlertDescription>
                            All sample pages passed validation.
                        </AlertDescription>
                    </Alert>
                ) : (
                    <Alert status="warning" borderRadius="md">
                         <AlertIcon />
                         <Box>
                            <AlertTitle>Validation Issues Detected</AlertTitle>
                            <AlertDescription>
                                Some pages could not be validated. Please check your site configuration.
                                <List spacing={1} mt={2}>
                                    {validationResult.map((result, index) => (
                                        <ListItem key={index}>
                                            <ListIcon as={result.status == 200 ? CheckCircleIcon : WarningIcon} color={result.status == 200 ? 'green.500' : 'red.500'} />
                                            <strong>{result.original_url}</strong>: {result.message}
                                        </ListItem>
                                    ))}
                                </List>
                            </AlertDescription>
                        </Box>
                    </Alert>
                )}
            </Box>
        )}

      </VStack>
    </Box>
  );
};

export default SitemapAndValidationPanel; 