import React, { memo, useState, useEffect } from 'react';
import { Power } from 'lucide-react';
import { useGPUServerStatus } from '~/hooks/useGPUServerStatus';
import { cn } from '~/utils';

interface GPUServerStatusProps {
  isCollapsed?: boolean;
}

const GPUServerStatus = memo(({ isCollapsed = false }: GPUServerStatusProps) => {
  const { state, phase, message, isLoading, refetch } = useGPUServerStatus(60000);
  const [toggleLoading, setToggleLoading] = useState(false);
  const [toggleError, setToggleError] = useState('');
  const [credits, setCredits] = useState({ remaining: 0, cost: 0 });

  // Fetch credits on mount
  useEffect(() => {
    const fetchCredits = async () => {
      try {
        const res = await fetch('/api/credits');
        if (res.ok) {
          const data = await res.json();
          console.log('[GPUServerStatus] Credits API response:', data);
          // Only update if we have valid values - don't reset to 0 if actualCost is 0
          if (data.remainingCredit !== undefined || data.actualCost !== undefined) {
            setCredits(prev => ({
              remaining: data.remainingCredit !== undefined ? data.remainingCredit : prev.remaining,
              cost: data.actualCost !== undefined && data.actualCost !== 0 ? data.actualCost : prev.cost,
            }));
          }
        } else {
          console.warn('[GPUServerStatus] Credits fetch failed:', res.status);
        }
      } catch (err) {
        console.error('[GPUServerStatus] Credits fetch error:', err);
      }
    };
    fetchCredits();
    const int = setInterval(fetchCredits, 60000);
    return () => clearInterval(int);
  }, []);

  // Déterminer le statut d'affichage
  const isOnline = state === true && (phase === 'ready' || phase === 'online');
  const isOffline = state === false && (phase === 'stopped' || !state);
  const isTransitioning = phase === 'starting' || phase === 'stopping';

  console.log('[GPUServerStatus] Rendering:', { state, phase, isOnline, isOffline, isTransitioning });

  // Couleurs et labels
  const getStyle = () => {
    if (isTransitioning) {
      return {
        bg: 'bg-orange-500/10',
        text: 'text-orange-600',
        dot: 'bg-orange-500',
        label: `Server ${phase}...`,
        showButton: false,
        buttonAction: null,
      };
    }
    if (isOnline) {
      return {
        bg: 'bg-green-500/10',
        text: 'text-green-600',
        dot: 'bg-green-500',
        label: 'Server Online',
        showButton: true,
        buttonAction: false, // Envoyer false pour éteindre
      };
    }
    // Offline
    return {
      bg: 'bg-red-500/10',
      text: 'text-red-600',
      dot: 'bg-red-500',
      label: 'Server Offline',
      showButton: true,
      buttonAction: true, // Envoyer true pour allumer
    };
  };

  const style = getStyle();

  const toggleServer = async () => {
    if (toggleLoading) return;
    setToggleLoading(true);
    setToggleError('');

    try {
      const res = await fetch('/api/server/toggle', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ state: style.buttonAction }),
      });

      if (res.ok) {
        console.log('[GPUServerStatus] Toggle successful');
        setTimeout(() => refetch(), 500);
      } else if (res.status === 409) {
        // 409 = serveur déjà en transition, refetch pour voir le vrai état
        console.log('[GPUServerStatus] Server already transitioning, fetching real state');
        refetch();
      } else {
        setToggleError(`Error: ${res.status}`);
      }
    } catch (err) {
      setToggleError(err instanceof Error ? err.message : 'Error');
    } finally {
      setToggleLoading(false);
    }
  };

  if (isCollapsed) {
    return (
      <div className={cn('px-2 py-1 rounded', style.bg)}>
        <div className={cn('inline-flex items-center gap-1', style.text)}>
          <div className={cn('w-2 h-2 rounded-full', style.dot)} />
          <span className="text-xs font-semibold">
            {isOnline && 'Online'}
            {isOffline && 'Offline'}
            {isTransitioning && 'Wait...'}
          </span>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full">
      <div className={cn('p-3 rounded-lg border', style.bg, 'border-current/10')}>
        <div className="flex items-center justify-between gap-2">
          <div className="flex items-center gap-2 min-w-0">
            <div className={cn('w-2.5 h-2.5 rounded-full flex-shrink-0', style.dot)} />
            <div className="min-w-0">
              <p className={cn('text-sm font-semibold', style.text)}>
                {style.label}
              </p>
              {message && (
                <p className="text-xs text-gray-500 truncate">{message}</p>
              )}
              {toggleError && (
                <p className="text-xs text-red-500">{toggleError}</p>
              )}
            </div>
          </div>

          {style.showButton && !isTransitioning && (
            <button
              onClick={toggleServer}
              disabled={toggleLoading || isLoading}
              className={cn(
                'flex-shrink-0 p-1.5 rounded hover:bg-black/10 transition-colors',
                'disabled:opacity-50 disabled:cursor-not-allowed'
              )}
              title={isOnline ? 'Turn off' : 'Turn on'}
            >
              <Power className="w-4 h-4" />
            </button>
          )}
        </div>

        {credits.remaining > 0 && (
          <div className="mt-2 pt-2 border-t border-current/10">
            <div className="flex items-center justify-between text-xs">
              <span className="text-gray-600">Credits:</span>
              <span className="font-mono font-semibold">${credits.remaining.toFixed(2)}</span>
            </div>
            <div className="flex items-center justify-between text-xs mt-1">
              <span className="text-gray-600">Cost:</span>
              <span className="font-mono text-gray-500">${credits.cost.toFixed(2)}/hrs</span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
});

GPUServerStatus.displayName = 'GPUServerStatus';
export default GPUServerStatus;
