import React, { useState, useEffect } from 'react';
import {
  Box,
  Heading,
  Text,
  VStack,
  Button,
  Progress,
  useToast,
  Icon,
  HStack,
  Alert,
  AlertIcon,
  AlertTitle,
  AlertDescription,
  Spinner,
} from '@chakra-ui/react';
import { CheckCircleIcon, SettingsIcon } from '@chakra-ui/icons';
import ApiService from '../../services/ApiService';

const ScannerPanel = () => {
  const [jobStatus, setJobStatus] = useState(null);
  const [isStarting, setIsStarting] = useState(false);
  const [isLoadingInitialStatus, setIsLoadingInitialStatus] = useState(true);
  const toast = useToast();

  const isJobActive = jobStatus?.status === 'processing' || jobStatus?.status === 'queued';

  useEffect(() => {
    const fetchLatestStatus = async () => {
      setIsLoadingInitialStatus(true);
      try {
        const response = await ApiService.getLatestBatchStatus({ site_id: window.fluentcData?.siteId });
        if (response.success && response.data) {
          setJobStatus(response.data);
        } else if (!response.success) {
          toast({
            title: 'Could not fetch status',
            description: response.data?.message || 'Failed to retrieve initial job status.',
            status: 'warning',
            duration: 5000,
            isClosable: true,
          });
        }
      } catch (error) {
        toast({
          title: 'Error',
          description: 'An error occurred while fetching the translation job status.',
          status: 'error',
          duration: 9000,
          isClosable: true,
        });
      } finally {
        setIsLoadingInitialStatus(false);
      }
    };

    fetchLatestStatus();
  }, [toast]);

  useEffect(() => {
    let interval;
    if (isJobActive) {
      interval = setInterval(async () => {
        const response = await ApiService.getLatestBatchStatus({ site_id: window.fluentcData?.siteId });
        if (response.success && response.data) {
          setJobStatus(response.data);
        } else {
          setJobStatus(prev => ({ ...(prev || {}), status: 'failed', message: 'Could not retrieve scan status.' }));
        }
      }, 5000);
    }
    return () => clearInterval(interval);
  }, [isJobActive]);


  const handleStartScan = async () => {
    setIsStarting(true);
    try {
      const response = await ApiService.makeWpAjaxCall('fluentc_start_site_scan', {
        nonce: window.fluentcData?.dashboardNonce,
      });

      if (response.success) {
        setJobStatus({ status: 'queued', jobId: response.data.jobId });
        toast({
          title: 'Site Scan Queued',
          description: 'FluentC is preparing to translate your site. The process will begin shortly.',
          status: 'info',
          duration: 9000,
          isClosable: true,
        });
        const statusResponse = await ApiService.getLatestBatchStatus({ site_id: window.fluentcData?.siteId });
        if (statusResponse.success) {
          setJobStatus(statusResponse.data);
        }
      } else {
        throw new Error(response.data.message || 'Failed to start site scan.');
      }
    } catch (error) {
      toast({
        title: 'Scan Failed',
        description: error.message,
        status: 'error',
        duration: 9000,
        isClosable: true,
      });
    } finally {
      setIsStarting(false);
    }
  };

  const getProgress = () => {
    if (!jobStatus || !jobStatus.totalSteps || jobStatus.totalSteps === 0) {
      return 0;
    }
    return (jobStatus.completedSteps / jobStatus.totalSteps) * 100;
  };

  const renderStatus = () => {
    if (isLoadingInitialStatus) {
      return <Spinner color="blue.500" />;
    }

    if (!jobStatus || jobStatus.status === 'unknown') {
      return (
        <Button
          colorScheme="blue"
          onClick={handleStartScan}
          isLoading={isStarting}
          loadingText="Starting Scan..."
          w="full"
          size="lg"
          disabled={isJobActive}
        >
          Translate Entire Site
        </Button>
      );
    }

    switch (jobStatus.status) {
      case 'queued':
        return (
          <VStack spacing={3} w="full" p={4}>
             <Spinner color="blue.500" />
             <Text fontWeight="bold">Translation Queued</Text>
             <Text fontSize="sm" color="gray.600" textAlign="center">
              Your site translation will begin shortly. We&apos;re getting things ready.
            </Text>
          </VStack>
        );
      case 'processing':
        const progress = getProgress();
        return (
          <VStack spacing={3} w="full">
            <Box w="full">
              <HStack justify="space-between" mb={1}>
                <Text fontSize="md" fontWeight="bold" color="blue.600">
                  Status: Translating...
                </Text>
                <Text fontSize="md" fontWeight="bold" color="blue.600">{`${Math.round(progress)}%`}</Text>
              </HStack>
              <Progress
                value={progress}
                size="lg"
                colorScheme="blue"
                w="full"
                hasStripe
                isAnimated
                borderRadius="md"
              />
              <Text fontSize="sm" color="gray.500" textAlign="center" mt={2}>
                Number of Pages Translated: {jobStatus.completedSteps} / {jobStatus.totalSteps}
              </Text>
            </Box>
          </VStack>
        );
      case 'completed':
        return (
           <VStack spacing={3} alignItems="stretch" w="full">
            <Alert status="success" variant="subtle" borderRadius="md" w="full" flexDirection="column" alignItems="center" justifyContent="center" textAlign="center" p={4}>
              <AlertIcon as={CheckCircleIcon} boxSize="40px" mr={0} />
              <AlertTitle mt={4} mb={1} fontSize="lg">Translation Completed!</AlertTitle>
              <AlertDescription>
                <Text><strong>Total Pages Translated:</strong> {jobStatus.completedUrls}</Text>
                <Text><strong>Date:</strong> {new Date(jobStatus.createdAt).toLocaleString()}</Text>
              </AlertDescription>
            </Alert>
             <Button onClick={handleStartScan} isLoading={isStarting} loadingText="Starting new scan..." w="full" size="sm" variant="outline">Start New Translation</Button>
           </VStack>
        );
      case 'failed':
         return (
           <VStack spacing={3} w="full">
            <Alert status="error" variant="subtle" borderRadius="md">
              <AlertIcon />
              <Box>
                <AlertTitle>Translation Job Failed</AlertTitle>
                <AlertDescription>{jobStatus.message || 'Please try again. If the problem persists, contact support.'}</AlertDescription>
              </Box>
            </Alert>
             <Button onClick={handleStartScan} isLoading={isStarting} loadingText="Retrying..." w="full">Try Again</Button>
           </VStack>
        );
      default:
         return (
            <Button
                colorScheme="blue"
                onClick={handleStartScan}
                isLoading={isStarting}
                loadingText="Starting Scan..."
                w="full"
                size="lg"
                disabled={isJobActive}
            >
                Translate Entire Site
            </Button>
      );
    }
  };

  return (
    <Box p={5} shadow="md" borderWidth="1px" borderRadius="md">
      <VStack align="stretch" spacing={4}>
        <HStack>
          <Icon as={SettingsIcon} w={6} h={6} color="blue.500" />
          <Heading size="md">Automatic Site Translation</Heading>
        </HStack>
        <Text fontSize="sm" color="gray.600">
          Click the button to have FluentC automatically find, translate, and publish content for all pages on your site. This may take several minutes to complete. 
        </Text>
        <Text fontSize="sm" color="gray.600">
        You only ever have to do this once when you first install FluentC. We automatically update your site with new translations as they are completed.
        </Text>
        <Box minH="80px" w="full" display="flex" alignItems="center" justifyContent="center" p={2} bg="gray.50" borderRadius="md">
          {renderStatus()}
        </Box>
      </VStack>
    </Box>
  );
};

export default ScannerPanel; 