import React, { useState, useEffect } from 'react';
import './CapabilityManager.css';

interface Capability {
  id: string;
  capabilityId: string;
  name: string;
  version: string;
  defaultState: string;
  status: string;
}

interface Entitlement {
  id: string;
  tenantId: string;
  capabilityId: string;
  stateOverride?: string;
}

const API_BASE = process.env.REACT_APP_API_URL || 'http://localhost:3000';

export const CapabilityManager: React.FC = () => {
  const [capabilities, setCapabilities] = useState<Capability[]>([]);
  const [entitlements, setEntitlements] = useState<Entitlement[]>([]);
  const [selectedTenant, setSelectedTenant] = useState<string>('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchCapabilities();
    if (selectedTenant) {
      fetchEntitlements(selectedTenant);
    }
  }, [selectedTenant]);

  const fetchCapabilities = async () => {
    try {
      const response = await fetch(`${API_BASE}/api/v1/solacenet/capabilities`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
        },
      });
      const data = await response.json();
      setCapabilities(data);
    } catch (error) {
      console.error('Failed to fetch capabilities:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchEntitlements = async (tenantId: string) => {
    try {
      const response = await fetch(
        `${API_BASE}/api/v1/solacenet/tenants/${tenantId}/programs/entitlements`,
        {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
          },
        }
      );
      const data = await response.json();
      setEntitlements(data);
    } catch (error) {
      console.error('Failed to fetch entitlements:', error);
    }
  };

  const toggleCapability = async (capabilityId: string, newState: string) => {
    try {
      // Create or update entitlement
      const existing = entitlements.find(e => e.capabilityId === capabilityId);
      
      if (existing) {
        // Update existing entitlement
        await fetch(`${API_BASE}/api/v1/solacenet/entitlements/${existing.id}`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            stateOverride: newState,
          }),
        });
      } else {
        // Create new entitlement
        await fetch(`${API_BASE}/api/v1/solacenet/entitlements`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            tenantId: selectedTenant,
            capabilityId,
            stateOverride: newState,
          }),
        });
      }

      await fetchEntitlements(selectedTenant);
      alert(`Capability ${capabilityId} set to ${newState}`);
    } catch (error) {
      console.error('Failed to toggle capability:', error);
      alert('Failed to toggle capability');
    }
  };

  const getCurrentState = (capabilityId: string): string => {
    const entitlement = entitlements.find(e => e.capabilityId === capabilityId);
    return entitlement?.stateOverride || 'disabled';
  };

  if (loading) {
    return <div className="loading">Loading capabilities...</div>;
  }

  return (
    <div className="capability-manager">
      <div className="header">
        <h2>Capability Management</h2>
        <div className="tenant-selector">
          <label>Tenant ID:</label>
          <input
            type="text"
            value={selectedTenant}
            onChange={(e) => setSelectedTenant(e.target.value)}
            placeholder="Enter tenant ID"
          />
        </div>
      </div>

      <div className="capabilities-grid">
        {capabilities.map((cap) => {
          const currentState = getCurrentState(cap.capabilityId);
          return (
            <div key={cap.id} className="capability-card">
              <h3>{cap.name}</h3>
              <p className="capability-id">{cap.capabilityId}</p>
              <p className="version">v{cap.version}</p>
              <div className="state-indicator">
                <span className={`state-badge state-${currentState}`}>
                  {currentState}
                </span>
              </div>
              <div className="actions">
                <select
                  value={currentState}
                  onChange={(e) => toggleCapability(cap.capabilityId, e.target.value)}
                  disabled={!selectedTenant}
                >
                  <option value="disabled">Disabled</option>
                  <option value="pilot">Pilot</option>
                  <option value="enabled">Enabled</option>
                  <option value="suspended">Suspended</option>
                  <option value="drain">Drain</option>
                </select>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};
