import React, { useEffect, useState } from 'react';
import { useTranscriptionStore } from '../stores/transcriptionStore';
import { CheckCircleIcon, ClockIcon, InformationCircleIcon } from '@heroicons/react/24/outline';

const ServerStatusIndicator: React.FC = () => {
  const {
    serverStatus,
    serverHealth,
    startStatusPolling,
    stopStatusPolling,
    fetchServerHealth
  } = useTranscriptionStore();

  const [showTooltip, setShowTooltip] = useState(false);

  // Start polling when component mounts
  useEffect(() => {
    startStatusPolling();
    // Also fetch server health initially
    fetchServerHealth();

    // Cleanup on unmount
    return () => {
      stopStatusPolling();
    };
  }, [startStatusPolling, stopStatusPolling, fetchServerHealth]);

  if (!serverStatus) {
    return (
      <div className="flex items-center gap-2 text-gray-300 text-sm">
        <div className="w-2 h-2 bg-gray-400 rounded-full animate-pulse"></div>
        <span>Connecting to server...</span>
      </div>
    );
  }

  const formatDuration = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const getOperationLabel = (operation: string): string => {
    switch (operation) {
      case 'transcribe':
        return 'Short Transcription';
      case 'transcribe_long':
        return 'Long Transcription';
      case 'align':
        return 'Alignment';
      default:
        return 'Processing';
    }
  };

  const renderHealthTooltip = () => {
    if (!serverHealth) return null;

    return (
      <div className="fixed z-50 p-3 bg-gray-900 text-white text-xs rounded-lg shadow-xl border border-gray-600 min-w-64 max-w-80"
           style={{
             left: '280px', // Position just outside the sidebar (sidebar width is 256px + padding)
             top: '120px'    // Position near the status indicator
           }}>
        <div className="font-semibold mb-2 text-blue-300">Server Health</div>

        <div className="space-y-1">
          <div className="flex justify-between">
            <span className="text-gray-300">Status:</span>
            <span className="text-green-400">{serverHealth.status}</span>
          </div>

          <div className="flex justify-between">
            <span className="text-gray-300">Version:</span>
            <span>{serverHealth.version}</span>
          </div>

          <div className="flex justify-between">
            <span className="text-gray-300">Device:</span>
            <span className="font-mono">{serverHealth.device}</span>
          </div>

          <div className="flex justify-between">
            <span className="text-gray-300">CUDA:</span>
            <span className={serverHealth.cuda_available ? "text-green-400" : "text-red-400"}>
              {serverHealth.cuda_available ? "Available" : "Unavailable"}
            </span>
          </div>

          <div className="flex justify-between">
            <span className="text-gray-300">FFmpeg:</span>
            <span className={serverHealth.ffmpeg_available ? "text-green-400" : "text-red-400"}>
              {serverHealth.ffmpeg_available ? "Available" : "Unavailable"}
            </span>
          </div>

          {serverHealth.gpu_name && (
            <div className="flex justify-between">
              <span className="text-gray-300">GPU:</span>
              <span className="text-blue-400 text-right max-w-32 truncate" title={serverHealth.gpu_name}>
                {serverHealth.gpu_name}
              </span>
            </div>
          )}

          {serverHealth.gpu_count && serverHealth.gpu_count > 1 && (
            <div className="flex justify-between">
              <span className="text-gray-300">GPU Count:</span>
              <span>{serverHealth.gpu_count}</span>
            </div>
          )}

          {/* GPU Memory Information */}
          {serverHealth.gpu_memory_total_mb && (
            <>
              <div className="border-t border-gray-600 pt-1 mt-2">
                <div className="text-xs text-blue-300 font-semibold mb-1">GPU Memory</div>
              </div>

              <div className="flex justify-between">
                <span className="text-gray-300">Used:</span>
                <span className="text-orange-400">
                  {serverHealth.gpu_memory_reserved_mb?.toFixed(1)} MB
                </span>
              </div>

              <div className="flex justify-between">
                <span className="text-gray-300">Total:</span>
                <span className="text-blue-400">
                  {serverHealth.gpu_memory_total_mb?.toFixed(1)} MB
                </span>
              </div>

              <div className="flex justify-between">
                <span className="text-gray-300">Free:</span>
                <span className="text-green-400">
                  {serverHealth.gpu_memory_free_mb?.toFixed(1)} MB
                </span>
              </div>

              {/* Memory usage bar */}
              {serverHealth.gpu_memory_total_mb && serverHealth.gpu_memory_reserved_mb && (
                <div className="mt-1">
                  <div className="w-full bg-gray-600 rounded-full h-1.5">
                    <div
                      className="bg-orange-500 h-1.5 rounded-full transition-all duration-300"
                      style={{
                        width: `${Math.min(100, (serverHealth.gpu_memory_reserved_mb / serverHealth.gpu_memory_total_mb) * 100)}%`
                      }}
                    ></div>
                  </div>
                  <div className="text-xs text-gray-400 mt-0.5 text-center">
                    {((serverHealth.gpu_memory_reserved_mb / serverHealth.gpu_memory_total_mb) * 100).toFixed(1)}% used
                  </div>
                </div>
              )}
            </>
          )}
        </div>

        {/* Tooltip arrow pointing to the left (towards the info icon) */}
        <div className="absolute left-0 top-4 w-0 h-0 border-t-4 border-t-transparent border-b-4 border-b-transparent border-r-4 border-r-gray-900 transform -translate-x-full"></div>
      </div>
    );
  };

  if (serverStatus.is_busy) {
    const progress = serverStatus.progress || 0;
    const progressPercent = Math.round(progress * 100);

    return (
      <div className="flex flex-col gap-1">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2 text-orange-300 text-sm">
            <ClockIcon className="w-4 h-4 animate-spin" />
            <span className="font-medium">Server Busy</span>
          </div>

          {/* Health info icon with tooltip */}
          <div className="relative">
            <InformationCircleIcon
              className="w-4 h-4 text-gray-400 hover:text-gray-200 cursor-help transition-colors"
              onMouseEnter={() => setShowTooltip(true)}
              onMouseLeave={() => setShowTooltip(false)}
            />
            {showTooltip && renderHealthTooltip()}
          </div>
        </div>

        <div className="text-xs text-gray-300 space-y-1">
          <div className="flex justify-between items-center">
            <span>{getOperationLabel(serverStatus.current_operation || 'processing')}</span>
            <span className="font-mono text-orange-300">{progressPercent}%</span>
          </div>

          {serverStatus.duration_seconds && (
            <div className="flex justify-between items-center">
              <span className="text-gray-400">Duration:</span>
              <span className="font-mono">{formatDuration(serverStatus.duration_seconds)}</span>
            </div>
          )}

          {/* Progress bar */}
          <div className="w-full bg-gray-600 rounded-full h-1.5 mt-2">
            <div
              className="bg-orange-500 h-1.5 rounded-full transition-all duration-300"
              style={{ width: `${progressPercent}%` }}
            ></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-1">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2 text-green-300 text-sm">
          <CheckCircleIcon className="w-4 h-4" />
          <span className="font-medium">Server Ready</span>
        </div>

        {/* Health info icon with tooltip */}
        <div className="relative">
          <InformationCircleIcon
            className="w-4 h-4 text-gray-400 hover:text-gray-200 cursor-help transition-colors"
            onMouseEnter={() => setShowTooltip(true)}
            onMouseLeave={() => setShowTooltip(false)}
          />
          {showTooltip && renderHealthTooltip()}
        </div>
      </div>

      <div className="text-xs text-gray-300">
        <span>Completed: {serverStatus.total_completed} transcriptions</span>
      </div>
    </div>
  );
};

export default ServerStatusIndicator;
