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

const LanguagesPanel = ({ languages, onSync }) => {
  const [isSyncing, setIsSyncing] = useState(false);
  const toast = useToast();

  const handleSync = async () => {
    setIsSyncing(true);
    try {
      const response = await ApiService.makeWpAjaxCall('fluentc_sync_settings', {
        nonce: window.fluentcData?.dashboardNonce,
      });
      if (response.success) {
        toast({
          title: 'Settings Synchronized',
          description: 'Your FluentC settings and languages have been updated.',
          status: 'success',
          duration: 5000,
          isClosable: true,
        });
        if (onSync) {
          onSync(); // Callback to refresh dashboard data
        }
      } else {
        throw new Error(response.data.message || 'Failed to sync settings.');
      }
    } catch (error) {
      toast({
        title: 'Sync Failed',
        description: error.message,
        status: 'error',
        duration: 9000,
        isClosable: true,
      });
    } finally {
      setIsSyncing(false);
    }
  };

  return (
    <Box p={5} shadow="md" borderWidth="1px" borderRadius="md">
      <VStack align="stretch" spacing={4}>
        <HStack justify="space-between">
          <HStack>
            <Icon as={ChatIcon} w={6} h={6} color="blue.500" />
            <Heading size="md">Your Languages</Heading>
          </HStack>
          <Tooltip label={
            (!languages || languages.length === 0) 
              ? "After enabling languages in FluentC, click here to sync and update your WordPress site."
              : "Sync with FluentC to get the latest language and display settings."
          }>
            <Button
              size={(!languages || languages.length === 0) ? "md" : "sm"}
              colorScheme={(!languages || languages.length === 0) ? "blue" : "gray"}
              variant={(!languages || languages.length === 0) ? "solid" : "outline"}
              onClick={handleSync}
              isLoading={isSyncing}
              leftIcon={<RepeatIcon />}
              fontWeight={(!languages || languages.length === 0) ? "bold" : "normal"}
              _hover={{
                transform: (!languages || languages.length === 0) ? "translateY(-1px)" : "none",
                boxShadow: (!languages || languages.length === 0) ? "lg" : "sm"
              }}
            >
              Sync Settings
            </Button>
          </Tooltip>
        </HStack>
        <Text fontSize="sm" color="gray.600">
          This is the list of languages currently enabled for your site.
        </Text>
        {languages && languages.length > 0 ? (
          <List spacing={3}>
            {languages.map(([name, code]) => (
              <ListItem key={code}>
                <ListIcon as={CheckCircleIcon} color="green.500" />
                {name} ({code})
              </ListItem>
            ))}
          </List>
        ) : (
          <Alert status="info" variant="subtle">
            <AlertIcon />
            <Box>
              <AlertTitle>No Languages Enabled Yet!</AlertTitle>
              <AlertDescription>
                <VStack align="start" spacing={3} mt={2}>
                  <Text fontSize="sm">
                    To start translating your website, you need to enable languages in your FluentC account first.
                  </Text>
                  <VStack align="start" spacing={2}>
                    <Text fontSize="sm" fontWeight="semibold">Next steps:</Text>
                    <Text fontSize="sm">
                      1. Visit your{' '}
                      <Link
                        href="https://dashboard.fluentc.ai/"
                        isExternal
                        color="blue.500"
                        textDecoration="underline"
                      >
                        FluentC Dashboard <ExternalLinkIcon mx="2px" />
                      </Link>{' '}
                      to enable languages
                    </Text>
                    <Text fontSize="sm">
                      2. Click the{' '}
                      <Text as="span" fontWeight="bold" color="blue.600">
                        "Sync Settings"
                      </Text>{' '}
                      button above to update your WordPress site
                    </Text>
                    <Text fontSize="sm">
                      3. Once languages are enabled, the content scanner will become available
                    </Text>
                  </VStack>
                </VStack>
              </AlertDescription>
            </Box>
          </Alert>
        )}
      </VStack>
    </Box>
  );
};

export default LanguagesPanel; 