import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Heading,
  Text,
  VStack,
  Grid,
  GridItem,
  Alert,
  AlertIcon,
  AlertTitle,
  AlertDescription,
  Spinner,
  useToast,
} from '@chakra-ui/react';
import ApiService from '../../services/ApiService';
import LanguagesPanel from './LanguagesPanel';
import ScannerPanel from './ScannerPanel';
import ApiKeyInputForm from '../ApiKeyInputForm';
import PageLayout from '../layout/PageLayout';
import SitemapAndValidationPanel from './SitemapAndValidationPanel';

const Dashboard = ({ onDisconnect }) => {
  const [dashboardData, setDashboardData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const [hasCompletedValidation, setHasCompletedValidation] = useState(() => Boolean(window.fluentcData?.hasCompletedValidation));
  const toast = useToast();

  useEffect(() => {
    fetchDashboardData();
  }, []);

  const fetchDashboardData = async () => {
    // Don't fetch if we're transitioning away from dashboard
    if (isTransitioning) return;
    
    setIsLoading(true);
    setError(null);
    try {
      const response = await ApiService.makeWpAjaxCall('fluentc_get_dashboard_data', {
        nonce: window.fluentcData?.dashboardNonce,
      });
      if (response.success) {
        setDashboardData(response.data);
        if (typeof response.data.hasCompletedValidation !== 'undefined') {
          const completed = Boolean(response.data.hasCompletedValidation);
          setHasCompletedValidation(completed);
          if (window.fluentcData) {
            window.fluentcData.hasCompletedValidation = completed;
            window.fluentcData.validationCompletedAt = response.data.validationCompletedAt || 0;
          }
        }
      } else {
        throw new Error(response.data.message || 'Failed to load dashboard data.');
      }
    } catch (err) {
      // Don't show errors if we're transitioning (e.g., API key was deleted)
      if (!isTransitioning) {
        setError(err.message);
        toast({
          title: 'Error',
          description: err.message,
          status: 'error',
          duration: 9000,
          isClosable: true,
        });
      }
    } finally {
      setIsLoading(false);
    }
  };

  const handleValidationComplete = () => {
    setHasCompletedValidation(true);
    if (window.fluentcData) {
      window.fluentcData.hasCompletedValidation = true;
      window.fluentcData.validationCompletedAt = Math.floor(Date.now() / 1000);
    }
  };

  const handleApiKeyDelete = () => {
    // Set transitioning state to prevent further API calls and error displays
    setIsTransitioning(true);
    
    // Clear any existing errors
    setError(null);
    
    // Call the parent disconnect handler
    if (onDisconnect) {
      onDisconnect();
    }
  };

  if (isLoading && !isTransitioning) {
    return (
      <Container centerContent p={10}>
        <Spinner size="xl" />
        <Text mt={4}>Loading Dashboard...</Text>
      </Container>
    );
  }

  if (error && !isTransitioning) {
    return (
      <Container>
        <Alert status="error">
          <AlertIcon />
          <AlertTitle>Could not load dashboard!</AlertTitle>
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      </Container>
    );
  }

  return (
    <PageLayout>
      <VStack spacing={4} align="stretch" mb={8}>
        <Heading size="lg">Dashboard</Heading>
      </VStack>
      
      <Grid templateColumns={{ base: "1fr", md: "2fr 1fr" }} gap={6}>
        <GridItem colSpan={1}>
          <VStack spacing={6} align="stretch">
            <SitemapAndValidationPanel
              hasCompletedValidation={hasCompletedValidation}
              onValidationComplete={handleValidationComplete}
            />
            {dashboardData?.languages && dashboardData.languages.length > 0 && (
              <ScannerPanel />
            )}
          </VStack>
        </GridItem>
        <GridItem colSpan={1}>
          <VStack spacing={6} align="stretch">
            <LanguagesPanel languages={dashboardData?.languages} onSync={fetchDashboardData} />
            <ApiKeyInputForm 
              initialApiKey={window.fluentcData?.apiKey || ''} 
              onSuccess={fetchDashboardData}
              onDelete={handleApiKeyDelete}
            />
          </VStack>
        </GridItem>
      </Grid>
    </PageLayout>
  );
};

export default Dashboard; 