import { Machine } from '../types'
import { Trash2, Clock } from 'lucide-react'
import { useMachineStore } from '../store/machineStore'
import { useState, useEffect } from 'react'
import { log } from '../utils/logger'

interface MachineDetailsProps {
  machine: Machine;
  machineStatus?: Machine['status'];
  isConnected?: boolean;
  connectionInfo?: {
    connectionId: string;
    connectedAt: Date;
    expiresAt: Date;
  };
  onDelete?: () => void;
  onExtendConnection?: (additionalMinutes?: number) => Promise<void>;
}

function MachineDetails({ machine, machineStatus, isConnected = false, connectionInfo, onDelete, onExtendConnection }: MachineDetailsProps) {
  // Use passed status or fallback to machine status
  const currentStatus = machineStatus || machine.status;
  
  const { deleteSavedMachine } = useMachineStore();
  const [isDeleting, setIsDeleting] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  
  // Connection timer state (updates every second)
  const [connectionDuration, setConnectionDuration] = useState<string>('');
  
  // Time until TTL expiry state
  const [timeUntilExpiry, setTimeUntilExpiry] = useState<{ minutes: number; isWarning: boolean }>({
    minutes: 0,
    isWarning: false,
  });
  
  // Extension process state
  const [isExtending, setIsExtending] = useState(false);
  
  // Determine if machine is "saved" (not mock data)
  const isSavedMachine = machine.hypervisor === 'Saved';
  
  // Update connection timer every second
  useEffect(() => {
    if (!isConnected || !connectionInfo) {
      setConnectionDuration('');
      return;
    }
    
    const updateDuration = () => {
      const now = Date.now();
      const connectedAt = connectionInfo.connectedAt.getTime();
      const diffMs = now - connectedAt;
      const diffSeconds = Math.floor(diffMs / 1000);
      const diffMinutes = Math.floor(diffSeconds / 60);
      const diffHours = Math.floor(diffMinutes / 60);
      
      if (diffHours > 0) {
        setConnectionDuration(`${diffHours}h ${diffMinutes % 60}m`);
      } else if (diffMinutes > 0) {
        setConnectionDuration(`${diffMinutes}m ${diffSeconds % 60}s`);
      } else if (diffSeconds > 5) {
        setConnectionDuration(`${diffSeconds}s`);
      } else {
        setConnectionDuration('just now');
      }
    };
    
    // Update immediately
    updateDuration();
    
    // And every second
    const interval = setInterval(updateDuration, 1000);
    
    return () => clearInterval(interval);
  }, [isConnected, connectionInfo]);
  
  // Track time until TTL expiry
  useEffect(() => {
    if (!isConnected || !connectionInfo?.expiresAt) {
      setTimeUntilExpiry({ minutes: 0, isWarning: false });
      return;
    }
    
    const updateTimeUntilExpiry = () => {
      const now = Date.now();
      const expiresAt = connectionInfo.expiresAt.getTime();
      const diffMs = expiresAt - now;
      const minutesRemaining = Math.floor(diffMs / 60000);
      
      setTimeUntilExpiry({
        minutes: minutesRemaining,
        isWarning: minutesRemaining <= 10 && minutesRemaining > 0, // Warning if 10 minutes or less remaining
      });
    };
    
    // Update immediately
    updateTimeUntilExpiry();
    
    // And every 30 seconds (doesn't need to be as frequent as duration)
    const interval = setInterval(updateTimeUntilExpiry, 30000);
    
    return () => clearInterval(interval);
  }, [isConnected, connectionInfo]);
  
  // Connection extension handler
  const handleExtend = async () => {
    if (!onExtendConnection || isExtending) return;
    
    setIsExtending(true);
    try {
      await onExtendConnection(60); // Extend by 60 minutes by default
      log.info('machine-details', 'Connection extended successfully');
    } catch (error) {
      log.error('machine-details', 'Failed to extend connection', { error });
    } finally {
      setIsExtending(false);
    }
  };
  
  const handleDelete = async () => {
    if (!isSavedMachine) return;
    
    setIsDeleting(true);
    try {
      log.info('machine-details', 'Deleting saved machine', { machineId: machine.id });
      await deleteSavedMachine(machine.id);
      log.info('machine-details', 'Saved machine deleted successfully');
      setShowDeleteConfirm(false);
      
      if (onDelete) {
        onDelete();
      }
    } catch (error) {
      log.error('machine-details', 'Failed to delete machine', { error });
    } finally {
      setIsDeleting(false);
    }
  };
  return (
    <div className="flex-1 p-6 overflow-auto select-none">
      <div className="bg-kaspersky-bg-card rounded-lg p-6 shadow-kaspersky">
        <div className="mb-6">
          <div className="flex items-start justify-between gap-4">
            <div className="flex-1 min-w-0">
              <h1 className="text-2xl font-semibold text-kaspersky-text-dark break-words">{machine.name}</h1>
              <div className="flex items-center mt-2 gap-4 flex-wrap">
                {/* If connected - show only Connected block with status indicator color */}
                {isConnected && connectionInfo ? (
                  <>
                    <div className="flex items-center px-3 py-1.5 bg-kaspersky-primary bg-opacity-10 border border-kaspersky-primary border-opacity-30 rounded-lg">
                      {/* Indicator color reflects machine availability status */}
                      <div
                        className={`w-2.5 h-2.5 rounded-full mr-2 shadow-sm ${
                          currentStatus === 'running' ? 'bg-kaspersky-success animate-pulse' :
                          currentStatus === 'stopped' ? 'bg-kaspersky-danger' :
                          currentStatus === 'checking' ? 'bg-kaspersky-warning animate-pulse' :
                          currentStatus === 'unknown' ? 'bg-gray-400' :
                          'bg-kaspersky-primary animate-pulse'
                        }`}
                      />
                      <span className="text-xs text-kaspersky-primary font-semibold">
                        Connected {connectionDuration ? `(${connectionDuration})` : ''}
                      </span>
                    </div>
                    
                    {/* Кнопка продления - показываем всегда когда подключены */}
                    {onExtendConnection && (
                      <button
                        onClick={handleExtend}
                        disabled={isExtending}
                        className={`flex items-center gap-2 px-3 py-1.5 rounded-lg transition-all duration-200 ${
                          timeUntilExpiry.isWarning
                            ? 'bg-kaspersky-warning bg-opacity-10 border border-kaspersky-warning border-opacity-30 text-kaspersky-warning hover:bg-opacity-20 animate-pulse'
                            : 'bg-kaspersky-success bg-opacity-10 border border-kaspersky-success border-opacity-30 text-kaspersky-success hover:bg-opacity-20'
                        } disabled:opacity-50 disabled:cursor-not-allowed`}
                        title={`Extend connection by 60 minutes (${timeUntilExpiry.minutes}m remaining)`}
                      >
                        <Clock className="w-3.5 h-3.5" />
                        <span className="text-xs font-semibold">
                          {isExtending ? 'Extending...' : `Extend (${timeUntilExpiry.minutes}m left)`}
                        </span>
                      </button>
                    )}
                  </>
                ) : (
                  /* If not connected - show regular availability status */
                  <div className="flex items-center">
                    <div
                      className={`w-3 h-3 rounded-full mr-2 shadow-sm ${
                        currentStatus === 'running' ? 'bg-kaspersky-success' :
                        currentStatus === 'stopped' ? 'bg-kaspersky-danger' :
                        currentStatus === 'checking' ? 'bg-kaspersky-warning animate-pulse' :
                        currentStatus === 'unknown' ? 'bg-gray-400' :
                        'bg-kaspersky-warning'
                      }`}
                    />
                    <span className="text-sm text-kaspersky-text capitalize font-medium">
                      {currentStatus === 'checking' ? 'Checking...' : currentStatus}
                    </span>
                  </div>
                )}
              </div>
            </div>
            
            {/* Delete Button для сохраненных машин */}
            {isSavedMachine && (
              <button
                onClick={() => setShowDeleteConfirm(true)}
                disabled={isDeleting || isConnected}
                className="flex-shrink-0 px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
                title={isConnected ? "Disconnect first to delete" : "Delete saved machine"}
              >
                <Trash2 size={18} />
                <span className="text-sm font-medium">Delete</span>
              </button>
            )}
          </div>
        </div>
        
        <div className={isSavedMachine ? "flex flex-col gap-6" : "grid grid-cols-2 gap-6"}>
          <div>
            <h2 className="text-lg font-semibold mb-4 text-kaspersky-primary">System Information</h2>
            <div className="space-y-3">
              <div>
                <label className="text-sm text-kaspersky-text-light font-medium">Operating System</label>
                <div className="text-kaspersky-text-dark font-medium">{machine.os}</div>
              </div>
              <div>
                <label className="text-sm text-kaspersky-text-light font-medium">Hostname</label>
                <div className="text-kaspersky-text-dark font-medium">{machine.ip}</div>
              </div>
              {machine.port && (
                <div>
                  <label className="text-sm text-kaspersky-text-light font-medium">Port</label>
                  <div className="text-kaspersky-text-dark font-medium">{machine.port}</div>
                </div>
              )}
              {machine.protocol && (
                <div>
                  <label className="text-sm text-kaspersky-text-light font-medium">Protocol</label>
                  <div className="text-kaspersky-text-dark font-medium">{machine.protocol.toUpperCase()}</div>
                </div>
              )}
              {/* Показываем Hypervisor только для НЕ сохраненных машин */}
              {!isSavedMachine && (
                <div>
                  <label className="text-sm text-kaspersky-text-light font-medium">Hypervisor</label>
                  <div className="text-kaspersky-text-dark font-medium">{machine.hypervisor}</div>
                </div>
              )}
            </div>
          </div>

          {/* Показываем Hardware Specifications только для НЕ сохраненных машин */}
          {!isSavedMachine && (
            <div>
              <h2 className="text-lg font-semibold mb-4 text-kaspersky-primary">Hardware Specifications</h2>
              <div className="space-y-3">
                <div>
                  <label className="text-sm text-kaspersky-text-light font-medium">CPU</label>
                  <div className="text-kaspersky-text-dark font-medium">{machine.specs.cpu}</div>
                </div>
                <div>
                  <label className="text-sm text-kaspersky-text-light font-medium">Memory</label>
                  <div className="text-kaspersky-text-dark font-medium">{machine.specs.ram}</div>
                </div>
                <div>
                  <label className="text-sm text-kaspersky-text-light font-medium">Storage</label>
                  <div className="text-kaspersky-text-dark font-medium">{machine.specs.disk}</div>
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="mt-6">
          <h2 className="text-lg font-medium mb-4 text-kaspersky-primary">Test Links</h2>
          <div className="flex flex-wrap gap-2">
            {machine.testLinks?.map((link, index) => (
              <a
                key={index}
                href={link.url}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-block px-3 py-1 bg-kaspersky-primary text-white rounded-lg hover:bg-kaspersky-primary-dark hover:shadow-kaspersky transition-all duration-300"
              >
                {link.name}
              </a>
            ))}
          </div>
        </div>

        <div className="mt-6">
          <h2 className="text-lg font-semibold mb-4 text-kaspersky-primary">Execution Log</h2>
          <div className="bg-kaspersky-bg rounded-lg p-4 font-mono text-sm max-h-48 overflow-auto border border-kaspersky-border">
            {machine.logs?.map((log, index) => (
              <div key={index} className="text-kaspersky-text mb-1">
                <span className="text-kaspersky-text-light">[{new Date(log.timestamp).toLocaleString()}]</span>
                <span className={`ml-2 font-medium ${
                  log.level === 'error' ? 'text-kaspersky-danger' : 
                  log.level === 'warn' ? 'text-kaspersky-warning' : 
                  'text-kaspersky-text-dark'
                }`}>
                  [{log.level.toUpperCase()}] {log.message}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>
      
      {/* Delete Confirmation Modal */}
      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-kaspersky-bg-card rounded-lg p-6 max-w-md w-full shadow-2xl border border-kaspersky-border">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-3 bg-red-600 bg-opacity-20 rounded-full">
                <Trash2 size={24} className="text-red-500" />
              </div>
              <h3 className="text-xl font-semibold text-kaspersky-text-dark">Delete Machine</h3>
            </div>
            
            <p className="text-kaspersky-text mb-6">
              Are you sure you want to delete <strong className="text-kaspersky-text-dark">{machine.name}</strong>?
              This action cannot be undone.
            </p>
            
            <div className="flex gap-3">
              <button
                onClick={handleDelete}
                disabled={isDeleting}
                className="flex-1 px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed font-medium"
              >
                {isDeleting ? 'Deleting...' : 'Delete'}
              </button>
              <button
                onClick={() => setShowDeleteConfirm(false)}
                disabled={isDeleting}
                className="flex-1 px-4 py-2 bg-kaspersky-bg hover:bg-kaspersky-border text-kaspersky-text-dark rounded-lg transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed font-medium border border-kaspersky-border"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default MachineDetails 