import React, { useState, useEffect } from 'react';
import {
  Box,
  VStack,
  HStack,
  Text,
  Button,
  Input,
  FormControl,
  FormLabel,
  Select,
  Progress,
  Alert,
  AlertIcon,
  AlertTitle,
  AlertDescription,
  Card,
  CardBody,
  CardHeader,
  Heading,
  useToast,
  Spinner,
  Divider,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  Badge,
} from '@chakra-ui/react';
import { CheckCircleIcon, DownloadIcon, RepeatIcon } from '@chakra-ui/icons';
import ApiService from '../services/ApiService';
import OrchestrationService from '../services/OrchestrationService';

const TranslatorWidget = () => {
  const [pageUrl, setPageUrl] = useState('');
  const [targetLanguage, setTargetLanguage] = useState('');
  const [sourceLanguage, setSourceLanguage] = useState('');
  const [languageOptions, setLanguageOptions] = useState({ targetLanguages: [], sourceLanguages: [] });
  const [filteredTargetLanguages, setFilteredTargetLanguages] = useState([]);
  const [isTranslating, setIsTranslating] = useState(false);
  const [translationProgress, setTranslationProgress] = useState(0);
  const [translationMessage, setTranslationMessage] = useState('');
  const [translationResults, setTranslationResults] = useState(null);
  const [showResults, setShowResults] = useState(false);
  const toast = useToast();

  const ALLOWED_TARGET_LANGUAGES = ['en', 'es', 'fr', 'de', 'zh', 'ar'];

  // Load language options on component mount
  useEffect(() => {
    loadLanguageOptions();
  }, []);

  // Effect to update filtered target languages when source language changes
  useEffect(() => {
    if (sourceLanguage) {
      setFilteredTargetLanguages(
        languageOptions.targetLanguages.filter(lang => lang.code !== sourceLanguage)
      );
    } else {
      setFilteredTargetLanguages(languageOptions.targetLanguages);
    }
  }, [sourceLanguage, languageOptions.targetLanguages]);

  const loadLanguageOptions = async () => {
    try {
      const response = await ApiService.makeWpAjaxCall('fluentc_get_language_options');
      
      if (response.success) {
        const allTargetLanguages = response.data.targetLanguages || [];
        const filtered = allTargetLanguages.filter(lang => 
          ALLOWED_TARGET_LANGUAGES.includes(lang.code)
        );

        setLanguageOptions({
          targetLanguages: filtered,
          sourceLanguages: response.data.sourceLanguages
        });
        
        setFilteredTargetLanguages(filtered);

        // Set default source language based on WordPress settings
        const siteLanguage = window.fluentcData?.siteLanguage;
        if (siteLanguage && response.data.sourceLanguages?.some(lang => lang.code === siteLanguage)) {
          setSourceLanguage(siteLanguage);
        }
      } else {
        throw new Error(response.data || 'Failed to load language options');
      }
    } catch (error) {
      console.error('Failed to load language options:', error);
      toast({
        title: 'Language Options Failed',
        description: `Failed to load available languages: ${error.message}`,
        status: 'error',
        duration: 10000,
        isClosable: true,
      });
    }
  };

  const handleTranslatePage = async () => {
    // Validation
    if (!pageUrl) {
      toast({
        title: 'URL Required',
        description: 'Please enter a page URL to translate',
        status: 'warning',
        duration: 3000,
        isClosable: true,
      });
      return;
    }

    if (!targetLanguage) {
      toast({
        title: 'Target Language Required',
        description: 'Please select a target language',
        status: 'warning',
        duration: 3000,
        isClosable: true,
      });
      return;
    }

    if (!sourceLanguage) {
      toast({
        title: 'Source Language Required',
        description: 'Please select the source language of your content',
        status: 'warning',
        duration: 3000,
        isClosable: true,
      });
      return;
    }

    setIsTranslating(true);
    setTranslationProgress(0);
    setTranslationMessage('Starting translation...');
    setTranslationResults(null);
    setShowResults(false);

    try {
      // Initialize OrchestrationService with API key
      const apiKey = window.fluentcData?.apiKey || 'demo-key-for-free-trial';
      OrchestrationService.initialize(apiKey);

      const result = await OrchestrationService.translateUrlWithSamples({
        pageUrl: pageUrl,
        targetLanguage: targetLanguage,
        sourceLanguage: sourceLanguage === 'auto' ? undefined : sourceLanguage,
        maxSamples: 5,
        allowExternal: true,
        onProgress: (progress) => {
          setTranslationProgress(progress.progress);
          setTranslationMessage(progress.message);
        }
      });

      setTranslationResults(result);
      setShowResults(true);
      
      toast({
        title: 'Translation Completed',
        description: `Found ${result.totalNodes} nodes, showing first ${result.samples.length} translations`,
        status: 'success',
        duration: 5000,
        isClosable: true,
      });

    } catch (error) {
      toast({
        title: 'Translation Failed',
        description: error.message,
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
      
      setTranslationMessage(`Translation failed: ${error.message}`);
    } finally {
      setIsTranslating(false);
    }
  };

  const handleResetForm = () => {
    setShowResults(false);
    setTranslationResults(null);
    setPageUrl('');
    setTranslationMessage('');
    setTranslationProgress(0);
  };

  return (
    <Box w="full" maxW="4xl" mx="auto" p={6}>
      <Card>
        <CardHeader>
          <Heading size="lg" textAlign="center">
            FluentC Translation Demo
          </Heading>
          <Text textAlign="center" color="gray.600" mt={2}>
            Test our AI translation quality by translating any page on your site
          </Text>
        </CardHeader>
        <CardBody>
          <VStack spacing={6}>
            {!showResults && (
              <>
                {/* URL Input */}
                <FormControl>
                  <FormLabel>Page URL</FormLabel>
                  <Input 
                    type="url" 
                    placeholder="Enter the page URL from your WordPress site" 
                    value={pageUrl} 
                    onChange={(e) => setPageUrl(e.target.value)}
                    isDisabled={isTranslating}
                  />
                </FormControl>

                {/* Language Selection */}
                {languageOptions.sourceLanguages.length > 0 && languageOptions.targetLanguages.length > 0 ? (
                  <HStack spacing={4} w="full">
                    <FormControl flex="1">
                      <FormLabel>From Language</FormLabel>
                      <Select 
                        placeholder="Select source language"
                        value={sourceLanguage}
                        onChange={(e) => setSourceLanguage(e.target.value)}
                        isDisabled={isTranslating}
                      >
                        {languageOptions.sourceLanguages.map((lang) => (
                          <option key={lang.code} value={lang.code}>
                            {lang.name}
                          </option>
                        ))}
                      </Select>
                    </FormControl>

                    <FormControl flex="1">
                      <FormLabel>To Language</FormLabel>
                      <Select 
                        placeholder="Select target language"
                        value={targetLanguage}
                        onChange={(e) => setTargetLanguage(e.target.value)}
                        isDisabled={isTranslating}
                      >
                        {filteredTargetLanguages.map((lang) => (
                          <option key={lang.code} value={lang.code}>
                            {lang.name}
                          </option>
                        ))}
                      </Select>
                    </FormControl>
                  </HStack>
                ) : (
                  <Alert status="info" variant="subtle">
                    <AlertIcon />
                    <Box>
                      <AlertTitle>Loading Languages...</AlertTitle>
                      <AlertDescription>
                        Please wait while we load available translation languages.
                      </AlertDescription>
                    </Box>
                  </Alert>
                )}
              </>
            )}

            {/* Progress Bar */}
            {isTranslating && (
              <VStack spacing={2} w="full">
                <Progress 
                  value={translationProgress} 
                  size="lg" 
                  colorScheme="blue" 
                  w="full"
                  hasStripe
                  isAnimated
                />
                <Text fontSize="sm" color="gray.600" textAlign="center">
                  {translationMessage}
                </Text>
              </VStack>
            )}

            {!showResults && (
              <Button
                colorScheme="blue"
                size="lg"
                onClick={handleTranslatePage}
                isLoading={isTranslating}
                loadingText="Translating..."
                w="full"
                isDisabled={isTranslating || languageOptions.sourceLanguages.length === 0 || languageOptions.targetLanguages.length === 0}
              >
                Translate Page
              </Button>
            )}

            {/* Translation Results */}
            {showResults && translationResults && (
              <Box w="full" mt={6}>
                <Divider mb={4} />
                
                <VStack spacing={4} align="start" w="full">
                  <Box>
                    <Heading size="md" mb={2}>Translation Results</Heading>
                    <HStack spacing={4}>
                      <Badge colorScheme="blue" variant="solid">
                        Total Content: {translationResults.totalNodes}
                      </Badge>
                      <Badge colorScheme="green" variant="solid">
                        Samples Shown: {translationResults.samples.length}
                      </Badge>
                      {translationResults.errors.length > 0 && (
                        <Badge colorScheme="red" variant="solid">
                          Errors: {translationResults.errors.length}
                        </Badge>
                      )}
                    </HStack>
                  </Box>

                  {translationResults.samples.length > 0 && (
                    <Box w="full">
                      <Text fontWeight="bold" mb={3} color="gray.700">
                        Sample Translations (Random 5 Results):
                      </Text>
                      
                      <Table variant="simple" size="sm">
                        <Thead>
                          <Tr>
                            <Th width="50%">Original Text</Th>
                            <Th width="50%">Translation</Th>
                          </Tr>
                        </Thead>
                        <Tbody>
                          {translationResults.samples.map((sample, index) => (
                            <Tr key={index}>
                              <Td>
                                <Text fontSize="sm" 
                                      maxHeight="100px" 
                                      overflowY="auto"
                                      p={2}
                                      bg="gray.50"
                                      borderRadius="md">
                                  {sample.original}
                                </Text>
                              </Td>
                              <Td>
                                <Text fontSize="sm"
                                      maxHeight="100px"
                                      overflowY="auto"
                                      p={2}
                                      bg="blue.50"
                                      borderRadius="md">
                                  {sample.translation || 'Translation in progress...'}
                                </Text>
                              </Td>
                            </Tr>
                          ))}
                        </Tbody>
                      </Table>
                    </Box>
                  )}

                  {translationResults.errors.length > 0 && (
                    <Alert status="warning" variant="left-accent">
                      <AlertIcon />
                      <Box>
                        <AlertTitle>Translation Notices</AlertTitle>
                        <AlertDescription>
                          {translationResults.errors.length} text nodes could not be translated due to API limits or errors.
                        </AlertDescription>
                      </Box>
                    </Alert>
                  )}

                  <VStack spacing={4} mt={8} align="stretch" w="full">
                    <Heading size="md" textAlign="center">
                      Like what you see?
                    </Heading>
                    <Text textAlign="center" color="gray.600" mt={-2}>
                      Take the next step to make your site multilingual.
                    </Text>
                    
                    <Button 
                      colorScheme="green" 
                      size="lg"
                      leftIcon={<CheckCircleIcon />}
                      onClick={() => {window.open('https://dashboard.fluentc.ai/users/sign_up', '_blank')}}
                    >
                      Sign Up for Free & Get Full Access
                    </Button>

                    <Button 
                      colorScheme="blue" 
                      variant="outline"
                      leftIcon={<DownloadIcon />}
                      onClick={() => {window.open('https://downloads.wordpress.org/plugin/fluentc-translation.zip', '_blank')}}
                    >
                      Download Full WordPress Plugin
                    </Button>

                    <Divider my={4} />

                    <Button 
                      variant="ghost" 
                      colorScheme="gray"
                      leftIcon={<RepeatIcon />}
                      onClick={handleResetForm}
                    >
                      Translate Another Page
                    </Button>
                  </VStack>
                </VStack>
              </Box>
            )}
          </VStack>
        </CardBody>
      </Card>
    </Box>
  );
};

export default TranslatorWidget; 