/**
 * Connection Status Component
 * 
 * Shows the connection status to ProRank.io audit servers
 */

import React, { useState, useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import { Spinner } from '../../../components/ui';
import { CheckIcon, XMarkIcon, InformationCircleIcon } from '@heroicons/react/24/outline';

const ConnectionStatus = ({ apiGet }) => {
  const [status, setStatus] = useState('checking');
  const [message, setMessage] = useState('');
  const [lastChecked, setLastChecked] = useState(null);

  useEffect(() => {
    checkConnection();
    const interval = setInterval(checkConnection, 30000); // Check every 30 seconds
    return () => clearInterval(interval);
  }, []);

  const checkConnection = async () => {
    try {
      const response = await apiGet('prorank-seo/v1/audit/ping');
      
      if (response && response.status === 'ok') {
        setStatus('connected');
        setMessage(__('Connected to ProRank.io', 'prorank-seo'));
      } else {
        setStatus('error');
        setMessage(__('Connection issue', 'prorank-seo'));
      }
    } catch (error) {
      setStatus('error');
      setMessage(__('Cannot reach ProRank.io servers', 'prorank-seo'));
    }
    
    setLastChecked(new Date());
  };

  const getStatusIcon = () => {
    switch (status) {
      case 'connected':
        return <CheckIcon className="status-icon connected pr:w-5 pr:h-5 pr:text-success-500" />;
      case 'error':
        return <XMarkIcon className="status-icon error pr:w-5 pr:h-5 pr:text-error-500" />;
      case 'checking':
        return <Spinner size="sm" />;
      default:
        return <InformationCircleIcon className="status-icon pr:w-5 pr:h-5 pr:text-gray-500" />;
    }
  };

  const getStatusClass = () => {
    return `connection-status connection-status--${status}`;
  };

  return (
    <div className={`${getStatusClass()} pr:p-4 pr:border pr:rounded-md pr:transition-all pr:duration-300`}>
      <div className="connection-status__indicator pr:flex pr:items-center pr:gap-2">
        {getStatusIcon()}
        <span className="connection-status__message pr:font-medium">{message || __('Checking...', 'prorank-seo')}</span>
      </div>
      {lastChecked && (
        <span className="connection-status__last-checked pr:text-sm pr:text-gray-500 pr:mt-2 pr:block">
          {__('Last checked:', 'prorank-seo')} {lastChecked.toLocaleTimeString()}
        </span>
      )}
    </div>
  );
};

export default ConnectionStatus;