import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Heading,
  Text,
  Button,
  VStack,
  HStack,
  Card,
  CardBody,
  CardHeader,
  Icon,
  Flex,
  useToast,
  Spinner,
  Image,
  Input,
  FormControl,
  FormLabel,
  Select,
  Progress,
  Alert,
  AlertIcon,
  AlertTitle,
  AlertDescription,
  Divider,
  SimpleGrid,
  Highlight,
} from '@chakra-ui/react';
import { ChevronRightIcon, StarIcon, SettingsIcon, CheckCircleIcon, RepeatIcon } from '@chakra-ui/icons';
import ApiService from '../services/ApiService';
import OrchestrationService from '../services/OrchestrationService';
import Dashboard from './dashboard/Dashboard';
import ApiKeyInputForm from './ApiKeyInputForm';
import PageLayout from './layout/PageLayout';

const WelcomePage = () => {
  const [email, setEmail] = useState('');
  const [isSubscribing, setIsSubscribing] = useState(false);
  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 [translationResult, setTranslationResult] = useState(null);
  const toast = useToast();

  const [isConnected, setIsConnected] = useState(false);

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

  // Load language options on component mount
  useEffect(() => {
    if (window.fluentcData?.hasUserApiKey) {
      setIsConnected(true);
    } else {
      loadLanguageOptions();
    }
  }, []);

  // Clear any error states when isConnected changes to false
  useEffect(() => {
    if (!isConnected) {
      // Clear any error states that might be showing
      setTranslationResult(null);
      setTranslationProgress(0);
      setTranslationMessage('');
    }
  }, [isConnected]);

  // 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 {
      // Use WordPress AJAX to get language options server-side (avoids CORS)
      const response = await ApiService.makeWpAjaxCall('fluentc_get_language_options');
      
      // Debug: Log the response structure
      console.log('AJAX Response:', response);
      console.log('Response type:', typeof response);
      console.log('Response keys:', Object.keys(response));
      
      if (response.success) {
        console.log('Response data:', response.data);
        console.log('Target languages count:', response.data.targetLanguages?.length);
        console.log('Source languages count:', response.data.sourceLanguages?.length);
        
        const allTargetLanguages = response.data.targetLanguages || [];
        
        // Filter target languages to only include the allowed list
        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);
      
      // Only show error toasts if we're not in a transitional state
      // (e.g., user just deleted their API key and we're transitioning to welcome screen)
      if (isConnected === false) {
        // Silently handle the error when we know we're in welcome mode
        console.log('Language options loading failed in welcome mode - this is expected behavior');
        return;
      }
      
      toast({
        title: 'Language Options Failed',
        description: `Failed to load available languages: ${error.message}. Please try again later.`,
        status: 'error',
        duration: 10000,
        isClosable: true,
      });
      // Don't set any fallback options - let the user see the error
    }
  };

  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...');
    setTranslationResult(null);

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

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

      setTranslationResult(result);
      
      toast({
        title: 'Translation Completed',
        description: `Successfully processed ${result.successfulTranslations}/${result.totalNodes} text nodes`,
        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 = () => {
    setPageUrl('');
    setTargetLanguage('');
    setTranslationResult(null);
    setTranslationProgress(0);
    setTranslationMessage('');
  };

  if (isConnected) {
    return <Dashboard onDisconnect={() => setIsConnected(false)} />;
  }

  return (
    <PageLayout containerSize="4xl" centerContent={true}>
      {/* Header Section */}
      <VStack spacing={6} align="center" mb={8} pt={12}>
        <VStack spacing={4} textAlign="center">
          <Heading as="h3">
           <Highlight query="multilingual powerhouse" styles={{ color: "blue.600" }}>
            Transform your WordPress site into a multilingual powerhouse in just a few minutes
           </Highlight>
          </Heading>
        </VStack>
      </VStack>

      {/* Single Primary Action */}
      <VStack spacing={8} w="full" maxW="2xl">
        {/* Main Demo Card - The One Clear Path */}
        <Card w="full" className="hover:shadow-xl transition-shadow duration-300" border="2px solid" borderColor="blue.200">
          <CardHeader textAlign="center" pb={2}>
            <VStack spacing={3}>
              <Icon as={SettingsIcon} w={12} h={12} color="blue.500" />
              <Heading size="lg" color="blue.600">See FluentC in Action</Heading>
              <Text color="gray.600" fontSize="lg">
                Try translating a page from your site right now - no signup required
              </Text>
            </VStack>
          </CardHeader>
          <CardBody>
            <VStack align="stretch" spacing={4}>
              {/* URL Input */}
              <FormControl>
                <FormLabel>Page URL from your WordPress site</FormLabel>
                <Input 
                  type="url" 
                  placeholder="https://yoursite.com/sample-page" 
                  value={pageUrl} 
                  onChange={(e) => setPageUrl(e.target.value)}
                  isDisabled={isTranslating}
                  size="lg"
                />
              </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}
                      size="lg"
                    >
                      {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}
                      size="lg"
                    >
                      {filteredTargetLanguages.map((lang) => (
                        <option key={lang.code} value={lang.code}>
                          {lang.name}
                        </option>
                      ))}
                    </Select>
                  </FormControl>
                </HStack>
              ) : (
                <Alert status="info" variant="subtle">
                  <AlertIcon />
                  <Box>
                    <AlertTitle>Language Options Unavailable</AlertTitle>
                    <AlertDescription>
                      Unable to load available languages. Please try refreshing the page or try again later.
                    </AlertDescription>
                    <Button
                      size="sm"
                      colorScheme="red"
                      variant="outline"
                      mt={2}
                      onClick={loadLanguageOptions}
                      leftIcon={<Icon as={SettingsIcon} />}
                    >
                      Retry Loading Languages
                    </Button>
                  </Box>
                </Alert>
              )}

              {/* Primary CTA Button */}
              {!translationResult ? (
                <Button
                  colorScheme="blue"
                  size="xl"
                  height="60px"
                  fontSize="lg"
                  rightIcon={isTranslating ? <Spinner size="sm" /> : <ChevronRightIcon />}
                  onClick={handleTranslatePage}
                  isLoading={isTranslating}
                  loadingText="Translating your page..."
                  w="full"
                  isDisabled={isTranslating || languageOptions.sourceLanguages.length === 0 || languageOptions.targetLanguages.length === 0}
                  _hover={{ transform: "translateY(-2px)", boxShadow: "lg" }}
                  transition="all 0.2s"
                >
                  {isTranslating ? "Translating..." : "Translate My Page Now"}
                </Button>
              ) : (
                <VStack spacing={4}>
                  <Button 
                    colorScheme="green" 
                    size="xl"
                    height="60px"
                    fontSize="lg"
                    leftIcon={<CheckCircleIcon />}
                    onClick={() => {window.open(`${pageUrl}?translate=${targetLanguage}&source=${sourceLanguage}`, '_blank')}}
                    w="full"
                    _hover={{ transform: "translateY(-2px)", boxShadow: "lg" }}
                    transition="all 0.2s"
                  >
                    🎉 View Your Translated Page
                  </Button>
                  
                  <Button
                    variant="ghost"
                    colorScheme="gray"
                    leftIcon={<RepeatIcon />}
                    onClick={handleResetForm}
                    w="full"
                  >
                    Try Another Page
                  </Button>
                </VStack>
              )}

              {/* 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>
              )}

              {/* Translation Result */}
              {translationResult && !isTranslating && (
                <Alert status="success" variant="subtle">
                  <AlertIcon />
                  <Box>
                    <AlertDescription>
                      <Text>Translation Completed!</Text>
                      Successfully processed {translationResult.successfulTranslations} out of {translationResult.totalNodes} text nodes.
                      {translationResult.errors.length > 0 && (
                        <Text mt={1} fontSize="sm" color="orange.600">
                          {translationResult.errors.length} nodes had translation errors.
                        </Text>
                      )}
                    </AlertDescription>
                  </Box>
                </Alert>
              )}
            </VStack>
          </CardBody>
        </Card>

        {/* Progressive Disclosure - Only show after demo */}
        {translationResult && (
          <VStack spacing={6}>
            <Card w="full" bg="green.50" border="2px solid" borderColor="green.200">
              <CardHeader textAlign="center">
                <Heading size="md" color="green.700">Love what you see?</Heading>
              </CardHeader>
              <CardBody>
                <VStack spacing={4}>
                  <Text textAlign="center" color="green.700">
                    Get unlimited translations for your entire WordPress site
                  </Text>
                  
                  <SimpleGrid columns={{ base: 1, md: 2 }} spacing={4} w="full">
                    <Button
                      colorScheme="green"
                      size="lg"
                      onClick={() => {window.open('https://dashboard.fluentc.ai/users/sign_up', '_blank')}}
                    >
                      Subscribe to FluentC
                    </Button>
                    
                    <Button
                      variant="outline"
                      colorScheme="green"
                      size="lg"
                      onClick={() => {
                        // Scroll to the API key form in the footer and focus it
                        const apiKeySection = document.querySelector('[data-api-key-section]');
                        if (apiKeySection) {
                          apiKeySection.scrollIntoView({ behavior: 'smooth', block: 'center' });
                          // Trigger the compact form to show if it's hidden
                          const apiKeyButton = apiKeySection.querySelector('button');
                          if (apiKeyButton) {
                            setTimeout(() => apiKeyButton.click(), 500);
                          }
                        }
                      }}
                    >
                      I have an API Key
                    </Button>
                  </SimpleGrid>
                </VStack>
              </CardBody>
            </Card>

            {/* Post-Demo Engagement */}
            <Card w="full" variant="outline">
              <CardBody>
                <VStack spacing={4}>
                  <Heading size="sm" color="gray.700">Need Help Getting Started?</Heading>
                  
                  <SimpleGrid columns={{ base: 1, md: 3 }} spacing={4} w="full">
                    <VStack spacing={2} p={4} borderRadius="md" bg="blue.50">
                      <Icon as={SettingsIcon} w={6} h={6} color="blue.500" />
                      <Text fontSize="sm" fontWeight="semibold">Setup Guide</Text>
                      <Button
                        variant="link"
                        colorScheme="blue"
                        size="sm"
                        onClick={() => {window.open('https://www.fluentc.ai/category/how-to/', '_blank')}}
                      >
                        View Documentation
                      </Button>
                    </VStack>

                    <VStack spacing={2} p={4} borderRadius="md" bg="green.50">
                      <Icon as={CheckCircleIcon} w={6} h={6} color="green.500" />
                      <Text fontSize="sm" fontWeight="semibold">Step-by-Step Tutorial</Text>
                      <Button
                        variant="link"
                        colorScheme="green"
                        size="sm"
                        onClick={() => {window.open('https://www.fluentc.ai/step-by-step-setup-of-fluentc-wordpress-translation-plugin/', '_blank')}}
                      >
                        Read Setup Guide
                      </Button>
                    </VStack>

                    <VStack spacing={2} p={4} borderRadius="md" bg="orange.50">
                      <Image 
                        src="https://www.fluentc.ai/wp-content/uploads/2024/06/support-team.jpg" 
                        alt="FluentC Support Team" 
                        borderRadius="full" 
                        boxSize="40px" 
                        objectFit="cover"
                        fallback={<Icon as={StarIcon} w={6} h={6} color="orange.500" />}
                      />
                      <Text fontSize="sm" fontWeight="semibold">Live Support</Text>
                      <Button
                        variant="link"
                        colorScheme="orange"
                        size="sm"
                        onClick={() => {window.open('https://www.fluentc.ai/contact/', '_blank')}}
                      >
                        Get Help
                      </Button>
                    </VStack>
                  </SimpleGrid>
                </VStack>
              </CardBody>
            </Card>
          </VStack>
        )}

        {/* Secondary Options - Collapsed by default */}
        <Card w="full" variant="outline" data-api-key-section>
          <CardBody>
            <VStack spacing={4}>
              <Text fontSize="sm" color="gray.600" textAlign="center">
                This demo translation is temporary and visible only to admins. 
                No changes are made to your live site.
              </Text>
              
              <Divider />
              
              <HStack spacing={4} fontSize="sm">
                <Button 
                  variant="link" 
                  colorScheme="blue" 
                  size="sm"
                  onClick={() => {window.open('https://dashboard.fluentc.ai/users/sign_up', '_blank')}}
                >
                  Subscribe to FluentC
                </Button>
                <Text color="gray.400">•</Text>
                <ApiKeyInputForm
                  onSuccess={() => setIsConnected(true)}
                  onDelete={() => setIsConnected(false)}
                  initialApiKey={window.fluentcData?.apiKey || ''}
                  compact={true}
                />
              </HStack>
            </VStack>
          </CardBody>
        </Card>
      </VStack>
    </PageLayout>
  );
};

export default WelcomePage; 