import React, { useState, useEffect } from 'react';
import {
  FormControl,
  FormLabel,
  Input,
  Button,
  useToast,
  VStack,
  HStack,
  AlertDialog,
  AlertDialogBody,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogContent,
  AlertDialogOverlay,
  useDisclosure,
} from '@chakra-ui/react';
import { CheckCircleIcon, EditIcon, DeleteIcon } from '@chakra-ui/icons';
import ApiService from '../services/ApiService';

// Free API key that should never be displayed to users
const FREE_API_KEY = '13c25c70-a4fa-4232-9d2c-1c451e71c3b7';

const ApiKeyInputForm = ({ onSuccess, onDelete, initialApiKey = '', compact = false }) => {
  // Filter out the free API key from any initial value
  const sanitizedInitialKey = initialApiKey === FREE_API_KEY ? '' : initialApiKey;
  
  const [apiKeyInput, setApiKeyInput] = useState(sanitizedInitialKey);
  const [isSavingKey, setIsSavingKey] = useState(false);
  const [isDeletingKey, setIsDeletingKey] = useState(false);
  
  const hasExistingKey = !!sanitizedInitialKey;
  const [isEditing, setIsEditing] = useState(!hasExistingKey);
  const toast = useToast();
  
  // Alert dialog for delete confirmation
  const { isOpen, onOpen, onClose } = useDisclosure();
  const cancelRef = React.useRef();

  useEffect(() => {
    // Always filter out the free API key
    const sanitizedKey = initialApiKey === FREE_API_KEY ? '' : initialApiKey;
    setApiKeyInput(sanitizedKey);
    setIsEditing(!sanitizedKey);
  }, [initialApiKey]);

  // Function to mask the first 4 characters of the API key
  const maskApiKey = (apiKey) => {
    if (!apiKey || apiKey.length <= 4 || apiKey === FREE_API_KEY) {
      return '';
    }
    return '****' + apiKey.substring(4);
  };

  // Function to validate API key format
  const validateApiKeyFormat = (apiKey) => {
    if (!apiKey || !apiKey.trim()) {
      return { isValid: false, message: 'API key cannot be empty.' };
    }
    
    const trimmedKey = apiKey.trim();
    
    // Reject the free API key - users should never be able to save this
    if (trimmedKey === FREE_API_KEY) {
      return { 
        isValid: false, 
        message: 'The free testing API key cannot be saved. Please use your own FluentC API key.' 
      };
    }
    
    // UUID format validation (adjust pattern as needed for your API key format)
    const uuidPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
    
    if (!uuidPattern.test(trimmedKey)) {
      return { 
        isValid: false, 
        message: 'Invalid API key format. Copy and paste your API key from the FluentC dashboard.' 
      };
    }
    
    return { isValid: true, message: '' };
  };

  const handleSaveApiKey = async () => {
    // Validate format before saving
    const validation = validateApiKeyFormat(apiKeyInput);
    if (!validation.isValid) {
      toast({
        title: 'Invalid API Key Format',
        description: validation.message,
        status: 'error',
        duration: 9000,
        isClosable: true,
      });
      return;
    }

    setIsSavingKey(true);
    try {
      const response = await ApiService.makeWpAjaxCall('fluentc_save_settings_action', {
        fluentc_api_key: apiKeyInput.trim(),
        fluentc_settings_nonce_field: window.fluentcData?.saveNonce,
      });

      if (response.success) {
        toast({
          title: 'API Key Saved',
          description: 'Your API key has been saved successfully.',
          status: 'success',
          duration: 5000,
          isClosable: true,
        });
        
        const trimmedKey = apiKeyInput.trim();
        if (window.fluentcData) {
          // Never set the free API key in the global data
          window.fluentcData.apiKey = trimmedKey === FREE_API_KEY ? '' : trimmedKey;
          window.fluentcData.hasUserApiKey = trimmedKey !== FREE_API_KEY && trimmedKey !== '';
        }
        
        if (onSuccess) {
          onSuccess();
        }
        setIsEditing(false);
      } else {
        throw new Error(response.data.message || 'An unknown error occurred.');
      }
    } catch (error) {
      toast({
        title: 'Error Saving API Key',
        description: error.message,
        status: 'error',
        duration: 9000,
        isClosable: true,
      });
    } finally {
      setIsSavingKey(false);
    }
  };

  const handleDeleteApiKey = async () => {
    setIsDeletingKey(true);
    try {
      // Use the save nonce for compatibility with the backend
      const response = await ApiService.makeWpAjaxCall('fluentc_delete_api_key', {
        fluentc_settings_nonce_field: window.fluentcData?.saveNonce,
      });

      if (response.success) {
        // Clear global state immediately to prevent further API calls
        if (window.fluentcData) {
          window.fluentcData.apiKey = '';
          window.fluentcData.hasUserApiKey = false;
        }
        
        // Clear local state
        setApiKeyInput('');
        setIsEditing(true);
        
        // Call the delete callback first (to transition to welcome screen)
        if (onDelete) {
          onDelete();
        }
        
        // Show success toast after a brief delay to avoid conflict
        setTimeout(() => {
          toast({
            title: 'API Key Deleted',
            description: 'Your API key has been removed successfully. You can now test FluentC with free translations.',
            status: 'success',
            duration: 5000,
            isClosable: true,
          });
        }, 100);
        
      } else {
        throw new Error(response.data.message || 'An unknown error occurred.');
      }
    } catch (error) {
      console.error('Delete API key error:', error);
      toast({
        title: 'Error Deleting API Key',
        description: error.message || 'Failed to delete API key. Please try refreshing the page.',
        status: 'error',
        duration: 9000,
        isClosable: true,
      });
    } finally {
      setIsDeletingKey(false);
      onClose();
    }
  };

  const handleEdit = () => {
    setIsEditing(true);
  };

  const handleCancel = () => {
    const sanitizedKey = initialApiKey === FREE_API_KEY ? '' : initialApiKey;
    setApiKeyInput(sanitizedKey);
    setIsEditing(false);
  };

  const handleDeleteClick = () => {
    onOpen(); // Open confirmation dialog
  };

  const handleInputChange = (e) => {
    const value = e.target.value;
    // Prevent the free API key from being entered
    if (value === FREE_API_KEY) {
      toast({
        title: 'Invalid API Key',
        description: 'The free testing API key cannot be saved. Please use your own FluentC API key.',
        status: 'warning',
        duration: 5000,
        isClosable: true,
      });
      return;
    }
    setApiKeyInput(value);
  };

  // Get the display value for the input
  const getDisplayValue = () => {
    if (isEditing) {
      return apiKeyInput;
    } else if (hasExistingKey) {
      return maskApiKey(sanitizedInitialKey);
    } else {
      return apiKeyInput;
    }
  };

  // Compact mode for secondary placement
  if (compact) {
    if (hasExistingKey && !isEditing) {
      return (
        <Button 
          variant="link" 
          colorScheme="blue" 
          size="sm"
          onClick={handleEdit}
        >
          Edit API Key
        </Button>
      );
    }
    
    if (isEditing) {
      return (
        <VStack align="stretch" spacing={2} minW="300px">
          <FormControl>
            <Input
              type="text"
              placeholder="Enter your FluentC API key"
              value={apiKeyInput}
              onChange={handleInputChange}
              isDisabled={isSavingKey}
              size="sm"
            />
          </FormControl>
          <HStack spacing={2}>
            <Button
              onClick={handleSaveApiKey}
              colorScheme="blue"
              isLoading={isSavingKey}
              loadingText="Saving..."
              size="sm"
              flex="1"
            >
              Save
            </Button>
            <Button 
              onClick={handleCancel} 
              size="sm"
              flex="1"
              isDisabled={isSavingKey}
            >
              Cancel
            </Button>
          </HStack>
        </VStack>
      );
    }
    
    return (
      <Button 
        variant="link" 
        colorScheme="blue" 
        size="sm"
        onClick={() => setIsEditing(true)}
      >
        Enter API Key
      </Button>
    );
  }

  return (
    <VStack align="stretch" w="full" spacing={4}>
      <FormControl>
        <FormLabel htmlFor="fluentc-api-key">API Key</FormLabel>
        <Input
          id="fluentc-api-key"
          type="text"
          placeholder={!isEditing && hasExistingKey ? maskApiKey(sanitizedInitialKey) : 'Enter your FluentC API key '}
          value={getDisplayValue()}
          onChange={handleInputChange}
          isDisabled={isSavingKey || isDeletingKey || !isEditing}
          isReadOnly={!isEditing}
        />
      </FormControl>
      {isEditing ? (
        <VStack spacing={3}>
          <HStack w="full">
            <Button
              onClick={handleSaveApiKey}
              colorScheme="blue"
              isLoading={isSavingKey}
              loadingText="Saving..."
              w="full"
              leftIcon={<CheckCircleIcon />}
              isDisabled={isDeletingKey}
            >
              Save API Key
            </Button>
            {hasExistingKey && (
              <Button 
                onClick={handleCancel} 
                w="full" 
                isDisabled={isSavingKey || isDeletingKey}
              >
                Cancel
              </Button>
            )}
          </HStack>
          {hasExistingKey && (
            <Button
              onClick={handleDeleteClick}
              colorScheme="red"
              variant="outline"
              w="full"
              leftIcon={<DeleteIcon />}
              isLoading={isDeletingKey}
              loadingText="Deleting..."
              isDisabled={isSavingKey}
            >
              Delete API Key
            </Button>
          )}
        </VStack>
      ) : (
        <HStack>
          <Button
            onClick={handleEdit}
            w="full"
            leftIcon={<EditIcon />}
            isDisabled={isDeletingKey}
          >
            Edit API Key
          </Button>
          <Button
            onClick={handleDeleteClick}
            colorScheme="gray"
            variant="outline"
            w="full"
            leftIcon={<DeleteIcon />}
            isLoading={isDeletingKey}
            loadingText="Deleting..."
          >
            Delete API Key
          </Button>
        </HStack>
      )}

      {/* Delete Confirmation Dialog */}
      <AlertDialog
        isOpen={isOpen}
        leastDestructiveRef={cancelRef}
        onClose={onClose}
      >
        <AlertDialogOverlay>
          <AlertDialogContent>
            <AlertDialogHeader fontSize="lg" fontWeight="bold">
              Delete API Key
            </AlertDialogHeader>

            <AlertDialogBody>
              Are you sure you want to delete your API key? This will disable all FluentC translation features and you won't be able to access language options until you add a new valid API key.
            </AlertDialogBody>

            <AlertDialogFooter>
              <Button 
                ref={cancelRef} 
                onClick={onClose}
                isDisabled={isDeletingKey}
              >
                Cancel
              </Button>
              <Button 
                colorScheme="red" 
                onClick={handleDeleteApiKey} 
                ml={3}
                isLoading={isDeletingKey}
                loadingText="Deleting..."
              >
                Delete
              </Button>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialogOverlay>
      </AlertDialog>
    </VStack>
  );
};

export default ApiKeyInputForm; 