import { useState } from 'react'
import { Play, Power, HeartPulse, AlertCircle, Sparkles } from 'lucide-react'
import { Machine } from '../types'
import { log } from '../utils/logger'
import { useMachineStore } from '../store/machineStore'
import { Button } from './shared/Button'

interface ActionPanelProps {
  machine: Machine;
  onConnect?: () => void;
  isConnected?: boolean;
  onDisconnect?: () => void;
  userRole?: string;
}

function ActionPanel({ machine, onConnect, isConnected, onDisconnect, userRole }: ActionPanelProps) {
  const [isLoading, setIsLoading] = useState<{[key: string]: boolean}>({
    connect: false,
    health: false,
    issue: false
  });
  const { controlMachine: _controlMachine } = useMachineStore();

  const setActionLoading = (action: string, loading: boolean) => {
    setIsLoading(prev => ({ ...prev, [action]: loading }));
  };

  const handleConnect = async () => {
    if (isConnected && onDisconnect) {
      onDisconnect();
    } else if (onConnect) {
      onConnect();
    }
  };



  const handleHealthCheck = async () => {
    setActionLoading('health', true);
    try {
      log.info('action-panel', 'Starting health check', {
        machineId: machine.id,
        machineName: machine.name
      });

      // TODO: Implement health check logic
      await new Promise(resolve => setTimeout(resolve, 1500)); // Имитация запроса
      
      log.info('action-panel', 'Health check completed', {
        machineId: machine.id,
        status: 'healthy' // Пример результата
      });
    } catch (error) {
      log.error('action-panel', 'Health check failed', {
        machineId: machine.id,
        error: error instanceof Error ? error.message : String(error)
      });
    } finally {
      setActionLoading('health', false);
    }
  };

  const handleCreateIssue = async () => {
    setActionLoading('issue', true);
    try {
      log.info('action-panel', 'Creating issue', {
        machineId: machine.id,
        machineName: machine.name
      });

      // TODO: Implement issue creation logic
      await new Promise(resolve => setTimeout(resolve, 1000)); // Имитация запроса
      
      log.info('action-panel', 'Issue created successfully', {
        machineId: machine.id,
        issueId: 'MOCK-123' // Пример ID созданной задачи
      });
    } catch (error) {
      log.error('action-panel', 'Failed to create issue', {
        machineId: machine.id,
        error: error instanceof Error ? error.message : String(error)
      });
    } finally {
      setActionLoading('issue', false);
    }
  };

  const isGuestRole = userRole === 'GUEST';
  const isConnectDisabled = isGuestRole && !isConnected; // Disable only for GUEST when not connected

  return (
    <div className="bg-white border-t border-kaspersky-border p-4 shadow-kaspersky select-none">
      <div className="flex justify-end gap-3">
        <Button
          variant={isConnected ? 'danger' : 'primary'}
          size="md"
          onClick={handleConnect}
          isLoading={isLoading.connect}
          disabled={isConnectDisabled}
          leftIcon={isConnected ? <Power size={18} /> : <Play size={18} />}
          title={isConnectDisabled ? 'Access denied: GUEST role cannot create connections. Contact your administrator.' : undefined}
        >
          {isConnected ? 'Disconnect' : 'Connect'}
        </Button>

        <Button
          variant="secondary"
          size="md"
          onClick={handleHealthCheck}
          isLoading={isLoading.health}
          leftIcon={<HeartPulse size={18} />}
        >
          {isLoading.health ? 'Checking...' : 'Health Check'}
        </Button>

        <Button
          variant="ghost"
          size="md"
          onClick={handleCreateIssue}
          isLoading={isLoading.issue}
          leftIcon={<AlertCircle size={18} />}
        >
          {isLoading.issue ? 'Creating...' : 'Create Issue'}
        </Button>

        {/* LLM Help кнопка - показывается только при активном подключении */}
        {isConnected && (
          <div className="relative">
            <Button
              variant="ghost"
              size="md"
              disabled
              leftIcon={<Sparkles size={18} />}
              className="opacity-50 cursor-not-allowed"
            >
              LLM Help
            </Button>
            {/* Бейдж SOON */}
            <span className="absolute -top-1 -right-1 bg-gradient-to-r from-kaspersky-primary to-kaspersky-danger text-white text-[9px] font-bold px-1.5 py-0.5 rounded-full uppercase tracking-wide shadow-sm">
              Soon
            </span>
          </div>
        )}
      </div>
    </div>
  )
}

export default ActionPanel 