import React, { useState, useEffect, useCallback } from 'react';
import { regions, testRegion, templates } from '../constants';
import './Deployments.css';
import config from '../config';
import Cookies from 'js-cookie';
import { authService, isAuthEnabled, getUserRoles, isUserAdmin } from '../services/auth';
import templateService from '../services/templateService';

// Simple Card component (since we don't have a UI library imported)
const Card = ({ className, onClick, children }) => {
  return (
    <div className={className} onClick={onClick}>
      {children}
    </div>
  );
};

// Card subcomponents
Card.Body = ({ children }) => <div className="card-body">{children}</div>;
Card.Title = ({ children }) => <h3 className="card-title">{children}</h3>;
Card.Text = ({ children }) => <p className="card-text">{children}</p>;

// Add URI validation helper
const isValidUrl = (string) => {
  try {
    new URL(string);
    return true;
  } catch (_) {
    return false;
  }
};

// Add container registry validation
const isValidContainerImage = (string) => {
  // Basic container image format validation
  // e.g., registry.example.com/username/image:tag
  const pattern = /^(?:([a-zA-Z0-9\-\.]+(?::\d+)?)\/)?([\w\-\/]+)(?::([\w\-\.]+))?$/;
  return pattern.test(string);
};

// Add these arrays at the top with other constants
const momWords = {
  adjectives: ['warm', 'sweet', 'loving', 'caring', 'gentle', 'kind', 'wise', 'patient', 'cozy'],
  nouns: ['cookies', 'cuddles', 'hugs', 'kisses', 'snuggles', 'comfort', 'wisdom', 'love'],
  traits: ['girlboss', 'rockstar', 'champion', 'superhero', 'warrior', 'legend', 'queen', 'maven']
};

// Add this helper function
const generateSubdomainOptions = (existingDomains = []) => {
  const options = [];

  while (options.length < 3) {
    const adj = momWords.adjectives[Math.floor(Math.random() * momWords.adjectives.length)];
    const noun = momWords.nouns[Math.floor(Math.random() * momWords.nouns.length)];
    const trait = momWords.traits[Math.floor(Math.random() * momWords.traits.length)];

    const subdomain = `${adj}-${noun}-${trait}`;

    if (!existingDomains.includes(subdomain) && !options.includes(subdomain)) {
      options.push(subdomain);
    }
  }

  return options;
};

function CredentialsForm({ type, credentials = {}, onChange, onTest }) {
  const [showPassword, setShowPassword] = useState(false);
  const [isTestingCredentials, setIsTestingCredentials] = useState(false);

  const handleChange = (field, value) => {
    onChange({
      ...credentials,
      type,
      [field]: value
    });
  };

  const handleTest = async () => {
    setIsTestingCredentials(true);
    try {
      await onTest(credentials);
      alert('Credentials verified successfully!');
    } catch (error) {
      alert(`Failed to verify credentials: ${error.message}`);
    } finally {
      setIsTestingCredentials(false);
    }
  };

  return (
    <div className="credentials-form">
      <h4>{type === 'git' ? 'Git Credentials' : 'Registry Credentials'}</h4>

      <div className="auth-type-selector">
        <select
          value={credentials?.authType || 'none'}
          onChange={(e) => handleChange('authType', e.target.value)}
        >
          <option value="none">No Authentication</option>
          {type === 'git' ? (
            <>
              <option value="basic">Username/Password</option>
              <option value="token">Access Token</option>
              <option value="ssh">SSH Key</option>
            </>
          ) : (
            <>
              <option value="basic">Username/Password</option>
              <option value="token">Access Token</option>
            </>
          )}
        </select>
      </div>

      {credentials?.authType === 'basic' && (
        <>
          <div className="input-group">
            <label>Username</label>
            <input
              type="text"
              value={credentials.username || ''}
              onChange={(e) => handleChange('username', e.target.value)}
              placeholder="Username"
            />
          </div>
          <div className="input-group">
            <label>Password</label>
            <div className="password-input">
              <input
                type={showPassword ? 'text' : 'password'}
                value={credentials.password || ''}
                onChange={(e) => handleChange('password', e.target.value)}
                placeholder="Password"
              />
              <button
                type="button"
                className="toggle-password"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? '👁️' : '👁️‍🗨️'}
              </button>
            </div>
          </div>
          {type === 'registry' && (
            <div className="input-group">
              <label>Email</label>
              <input
                type="email"
                value={credentials.email || ''}
                onChange={(e) => handleChange('email', e.target.value)}
                placeholder="Email for registry"
              />
            </div>
          )}
        </>
      )}

      {credentials?.authType === 'token' && (
        <div className="input-group">
          <label>Access Token</label>
          <div className="password-input">
            <input
              type={showPassword ? 'text' : 'password'}
              value={credentials.token || ''}
              onChange={(e) => handleChange('token', e.target.value)}
              placeholder="Access Token"
            />
            <button
              type="button"
              className="toggle-password"
              onClick={() => setShowPassword(!showPassword)}
            >
              {showPassword ? '👁️' : '👁️‍🗨️'}
            </button>
          </div>
        </div>
      )}

      {credentials?.authType === 'ssh' && type === 'git' && (
        <div className="input-group">
          <label>SSH Private Key</label>
          <textarea
            value={credentials.sshKey || ''}
            onChange={(e) => handleChange('sshKey', e.target.value)}
            placeholder="Paste your SSH private key here"
            rows={6}
          />
        </div>
      )}

      {credentials?.authType !== 'none' && (
        <button
          type="button"
          className="test-credentials"
          onClick={handleTest}
          disabled={isTestingCredentials}
        >
          {isTestingCredentials ? 'Testing...' : 'Test Credentials'}
        </button>
      )}
    </div>
  );
}

function Deployments() {
  // Replace the Auth0 hook with our own auth state management
  const [user, setUser] = useState(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isAuthLoading, setIsAuthLoading] = useState(true);
  const [deployments, setDeployments] = useState([]);
  const [showNewDeployment, setShowNewDeployment] = useState(false);
  const [editingDeployment, setEditingDeployment] = useState(null);
  const [initialTab, setInitialTab] = useState('source');
  const [isLoadingData, setIsLoadingData] = useState(true);
  const [error, setError] = useState(null);
  const [viewMode, setViewMode] = useState(Cookies.get('deploymentViewMode') || 'card');
  const [sortBy, setSortBy] = useState('name');
  const [sortOrder, setSortOrder] = useState('asc');
  const [filterStatus, setFilterStatus] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [userRoles, setUserRoles] = useState([]);
  const [apiTemplates, setApiTemplates] = useState([]);
  const [loadingTemplates, setLoadingTemplates] = useState(true);
  const [lastRefresh, setLastRefresh] = useState(Date.now());
  const [isPolling, setIsPolling] = useState(true);
  const [pollingInterval, setPollingInterval] = useState(5000); // 5 seconds

  // Check auth status when component mounts
  useEffect(() => {
    const authenticateUser = async () => {
      try {
        setIsAuthLoading(true);
        const userData = await authService.getUser();
        setUser(userData);
        setIsAuthenticated(!!userData);
      } catch (error) {
        console.error('Auth check error:', error);
        setIsAuthenticated(false);
      } finally {
        setIsAuthLoading(false);
      }
    };
    
    authenticateUser();
  }, []);

  useEffect(() => {
    if (isAuthenticated) {
      fetchDeployments();
    }
  }, [isAuthenticated]);

  useEffect(() => {
    Cookies.set('deploymentViewMode', viewMode, { expires: 365 });
  }, [viewMode]);

  console.log('Auth state:', { isAuthenticated, isAuthLoading });
  console.log('User:', user);

  // Add refresh button and polling toggle
  const togglePolling = () => {
    setIsPolling(!isPolling);
  };
  
  // Use effect to load data
  useEffect(() => {
    fetchTemplates();
    fetchDeployments();
    
    // Only fetch user roles if needed - remove reference to fetchUserRoles
    if (userRoles.length === 0 && isAuthenticated) {
      // Inline the user roles fetching logic instead of calling fetchUserRoles
      (async () => {
        try {
          // Use mock roles for basic auth in development mode
          if (isAuthEnabled() && window.sessionStorage.getItem('test_auth_pwd')) {
            console.log('Using mock roles with basic auth');
            setUserRoles(['admin']);
            return;
          }
          
          const response = await fetch(`/api/auth/roles`, {
            credentials: 'include'
          });
  
          if (!response.ok) {
            throw new Error('Failed to fetch user roles');
          }
  
          const { roles } = await response.json();
          setUserRoles(roles);
        } catch (error) {
          console.error('Error fetching user roles in load effect:', error);
          // Set default roles as fallback to prevent UI issues
          if (user) {
            const extractedRoles = getUserRoles(user);
            setUserRoles(extractedRoles);
          } else {
            setUserRoles([]);
          }
        }
      })();
    }
    
    // Set up polling control
    return () => {
      setIsPolling(false);
    };
  }, []);

  // Use the helper function to determine admin status, with fallback to userRoles state
  const isAdmin = user ? isUserAdmin(user) : userRoles.includes('admin');
  const availableRegions = isAdmin ? [...regions, testRegion] : regions;

  // Fetch API templates
  const fetchTemplates = async () => {
    try {
      setLoadingTemplates(true);
      const templates = await templateService.getAllTemplates();
      // Format templates for UI use
      const formattedTemplates = templates
        .map(templateService.formatTemplateForForm)
        .filter(Boolean); // Filter out null values
      setApiTemplates(formattedTemplates);
    } catch (error) {
      console.error('Error fetching templates:', error);
      setError('Failed to load templates. Using local templates as fallback.');
      // Fall back to local templates if API fails
    } finally {
      setLoadingTemplates(false);
    }
  };

  // Convert to useCallback to avoid recreation on every render
  const fetchDeployments = useCallback(async () => {
    try {
      setIsLoadingData(true);
      
      console.log('Fetching deployments...');
      
      // Use relative URL instead of hardcoded localhost
      const response = await fetch('/api/deployments', {
        credentials: 'include',
        headers: {
          'Accept': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`Failed to fetch deployments: ${response.status}`);
      }

      const data = await response.json();
      console.log(`Fetched ${data.length} deployments:`, data);
      
      // Check if any new deployments were added or updated
      const hasChanges = data.length !== deployments.length || 
                         data.some(newDep => {
                           const existingDep = deployments.find(d => d._id === newDep._id);
                           return !existingDep || existingDep.status !== newDep.status;
                         });
      
      if (hasChanges) {
        console.log('Changes detected in deployments, updating state');
        setDeployments(data);
      }
      
      setError(null);
      setLastRefresh(Date.now());
    } catch (error) {
      console.error('Error fetching deployments:', error);
      setError('Failed to load deployments. Please try again later.');
      // Provide empty deployments array as fallback if we haven't loaded any yet
      if (deployments.length === 0) {
        setDeployments([]);
      }
    } finally {
      setIsLoadingData(false);
    }
  }, [deployments]);
  
  // Add polling for deployments
  useEffect(() => {
    if (!isPolling) return;
    
    const timer = setTimeout(() => {
      fetchDeployments();
    }, pollingInterval);
    
    return () => clearTimeout(timer);
  }, [isPolling, lastRefresh, fetchDeployments, pollingInterval]);

  if (isAuthLoading) {
    return <div>Loading...</div>;
  }

  const handleDeploy = async (deploymentData) => {
    try {
      setIsLoadingData(true);
      
      let newDeployment;
      
      // If using a template, use the template API endpoint
      if (deploymentData.sourceType === 'prebaked' && deploymentData.selectedTemplateId) {
        const templateDeploymentData = {
          name: deploymentData.name,
          subdomain: deploymentData.subdomain,
          clusters: deploymentData.regions,
          params: {} // Add any template parameters here
        };
        
        // If there are environment variables, convert them to template parameters
        if (deploymentData.env && deploymentData.env.length > 0) {
          deploymentData.env.forEach(env => {
            templateDeploymentData.params[env.key] = env.value;
          });
        }
        
        newDeployment = await templateService.createDeploymentFromTemplate(
          deploymentData.selectedTemplateId,
          templateDeploymentData
        );
      } else {
        // Regular deployment creation
        const response = await fetch('/api/deployments', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(deploymentData),
          credentials: 'include'
        });
        
        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.error || 'Failed to create deployment');
        }
        
        newDeployment = await response.json();
      }
      
      // Add the new deployment to state
      setDeployments(prev => [...prev, newDeployment]);
      
      return newDeployment;
    } catch (error) {
      console.error('Error creating deployment:', error);
      setError(error.message);
      throw error;
    } finally {
      setIsLoadingData(false);
    }
  };

  const handleEdit = (deployment, tab = 'source') => {
    setEditingDeployment(deployment);
    setInitialTab(tab);
    setShowNewDeployment(true);
  };

  const updateDeploymentStatus = (deploymentId, status) => {
    setDeployments(deployments.map(d =>
      d._id === deploymentId ? { ...d, status } : d
    ));
  };

  const deleteDeployment = async (deploymentId) => {
    if (window.confirm('Are you sure you want to delete this deployment?')) {
      try {
        const response = await fetch(`/api/deployments/${deploymentId}`, {
          method: 'DELETE',
          credentials: 'include'
        });

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.details || 'Failed to delete deployment');
        }

        // Only remove from state if the delete was successful
        setDeployments(prev => prev.filter(d => d._id !== deploymentId));
      } catch (error) {
        console.error('Error deleting deployment:', error);
        alert(error.message);
      }
    }
  };

  const handleSort = (field) => {
    if (sortBy === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortBy(field);
      setSortOrder('asc');
    }
  };

  const filteredAndSortedDeployments = deployments
    .filter(d => {
      if (filterStatus !== 'all' && d.status !== filterStatus) return false;
      if (searchTerm && !d.name.toLowerCase().includes(searchTerm.toLowerCase())) return false;
      return true;
    })
    .sort((a, b) => {
      const order = sortOrder === 'asc' ? 1 : -1;
      switch (sortBy) {
        case 'name':
          return order * a.name.localeCompare(b.name);
        case 'status':
          return order * a.status.localeCompare(b.status);
        case 'created':
          return order * (new Date(a.createdAt) - new Date(b.createdAt));
        default:
          return 0;
      }
    });

  return (
    <div className="deployments-page">
      {isAdmin && (
        <div className="admin-badge">
          <span className="admin-icon">👑</span>
          Admin Mode
        </div>
      )}

      <header className="deployments-header">
        <div className="header-left">
          <h1>Your Deployments</h1>
          <div className="view-toggle">
            <button
              className={`view-toggle-btn ${viewMode === 'card' ? 'active' : ''}`}
              onClick={() => setViewMode('card')}
            >
              <span className="icon">⊞</span>
              <span className="label">Cards</span>
            </button>
            <button
              className={`view-toggle-btn ${viewMode === 'list' ? 'active' : ''}`}
              onClick={() => setViewMode('list')}
            >
              <span className="icon">☰</span>
              <span className="label">List</span>
            </button>
          </div>
        </div>
        <div className="header-actions">
          <button 
            className="refresh-btn" 
            onClick={fetchDeployments} 
            disabled={isLoadingData}
            title="Refresh Deployments"
          >
            🔄 {isLoadingData ? 'Loading...' : ''}
          </button>
          <button
            className={`auto-refresh-btn ${isPolling ? 'active' : ''}`}
            onClick={togglePolling}
            title={isPolling ? "Disable Auto-refresh" : "Enable Auto-refresh"}
          >
            {isPolling ? '⏸️ Auto' : '▶️ Auto'}
          </button>
          <button
            className="new-deployment-btn"
            onClick={() => setShowNewDeployment(true)}
          >
            New Deployment
          </button>
        </div>
      </header>
      
      {error && (
        <div className="error-banner">
          <span className="error-icon">⚠️</span>
          {error}
          <button className="retry-btn" onClick={fetchDeployments}>Retry</button>
        </div>
      )}
      
      {isLoadingData && deployments.length === 0 && (
        <div className="loading-indicator">
          <div className="spinner"></div>
          <p>Loading deployments...</p>
        </div>
      )}
      
      {!isLoadingData && deployments.length === 0 && !error && (
        <div className="empty-state">
          <div className="empty-icon">📦</div>
          <h3>No deployments found</h3>
          <p>Get started by creating your first deployment</p>
          <button
            className="new-deployment-btn"
            onClick={() => setShowNewDeployment(true)}
          >
            Create Deployment
          </button>
        </div>
      )}

      {viewMode === 'list' && (
        <div className="list-controls">
          <div className="search-filter">
            <input
              type="text"
              placeholder="Search deployments..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
            >
              <option value="all">All Status</option>
              <option value="running">Running</option>
              <option value="paused">Paused</option>
              <option value="error">Error</option>
            </select>
          </div>
        </div>
      )}

      {viewMode === 'card' ? (
        <div className="deployments-grid">
          {/* Existing card view */}
          {filteredAndSortedDeployments.map(deployment => (
            <DeploymentCard
              key={deployment._id}
              deployment={deployment}
              onEdit={(tab) => handleEdit(deployment, tab)}
              onUpdateStatus={updateDeploymentStatus}
              onDelete={() => deleteDeployment(deployment._id)}
            />
          ))}
        </div>
      ) : (
        <div className="deployments-list">
          <table>
            <thead>
              <tr>
                <th onClick={() => handleSort('name')}>
                  Name {sortBy === 'name' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th onClick={() => handleSort('status')}>
                  Status {sortBy === 'status' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th>Source</th>
                <th>Regions</th>
                <th onClick={() => handleSort('created')}>
                  Created {sortBy === 'created' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {filteredAndSortedDeployments.map(deployment => (
                <tr key={deployment._id}>
                  <td>{deployment.name}</td>
                  <td>
                    <span className={`status-dot ${deployment.status}`} />
                    {deployment.status}
                  </td>
                  <td>{deployment.gitUrl || deployment.containerImage}</td>
                  <td>
                    {deployment.regions.map(regionId => {
                      const region = [...regions, testRegion].find(r => r.id === regionId);
                      return region && (
                        <span
                          key={region.id}
                          className="region-tag-small"
                          title={`${region.name} (${region.location})`}
                        >
                          {region.icon}
                        </span>
                      );
                    })}
                  </td>
                  <td>{new Date(deployment.createdAt).toLocaleDateString()}</td>
                  <td className="actions">
                    <button
                      className="action-btn"
                      onClick={() => handleEdit(deployment, 'logs')}
                      data-tooltip="View Logs"
                    >
                      📋
                    </button>
                    <button
                      className="action-btn"
                      onClick={() => handleEdit(deployment, 'source')}
                      data-tooltip="Edit"
                    >
                      ✏️
                    </button>
                    <button
                      className="action-btn"
                      onClick={() => deleteDeployment(deployment._id)}
                      data-tooltip="Delete"
                    >
                      🗑
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {showNewDeployment && (
        <NewDeploymentForm
          deployment={editingDeployment}
          initialTab={initialTab}
          onClose={() => {
            setShowNewDeployment(false);
            setEditingDeployment(null);
            setInitialTab('source');
          }}
          onDeploy={handleDeploy}
          availableRegions={availableRegions}
        />
      )}
    </div>
  );
}

function DeploymentCard({ deployment, onEdit, onUpdateStatus, onDelete }) {
  const deploymentDate = new Date(deployment.createdAt).toLocaleDateString();
  
  // Get region info from the deployment's regions
  const deploymentRegions = deployment.regions.map(regionId => {
    const region = [...regions, testRegion].find(r => r.id === regionId);
    return region || { id: regionId, name: regionId, icon: '🌍' };
  });

  return (
    <div className="deployment-card">
      <div className="deployment-header">
        <div className="deployment-name">{deployment.name}</div>
        <div className={`status-badge ${deployment.status}`}>
          <span className="status-dot" />
          {deployment.status}
        </div>
      </div>
      
      <div className="deployment-body">
        <div className="deployment-info">
          <div className="info-item">
            <span className="label">Source:</span>
            <span className="value">
              {deployment.gitUrl || deployment.containerImage || 'Unknown'}
            </span>
          </div>
          <div className="info-item">
            <span className="label">Created:</span>
            <span className="value">{deploymentDate}</span>
          </div>
          <div className="info-item">
            <span className="label">Regions:</span>
            <div className="region-tags">
              {deploymentRegions.map(region => (
                <span
                  key={region.id}
                  className="region-tag"
                  title={`${region.name} (${region.location || 'Unknown location'})`}
                >
                  {region.icon}
                </span>
              ))}
            </div>
          </div>
        </div>
        
        <div className="deployment-url">
          {deployment.url && (
            <a href={deployment.url} target="_blank" rel="noopener noreferrer">
              {deployment.url} →
            </a>
          )}
        </div>
      </div>
      
      <div className="deployment-actions">
        <button
          className="action-btn"
          onClick={() => onEdit('source')}
          title="Edit Deployment"
        >
          ✏️
        </button>
        <button
          className="action-btn"
          onClick={() => onEdit('logs')}
          title="View Logs"
        >
          📋
        </button>
        <button
          className="action-btn"
          onClick={onDelete}
          title="Delete Deployment"
        >
          🗑️
        </button>
      </div>
    </div>
  );
}

function NewDeploymentForm({
  deployment,
  initialTab,
  onClose,
  onDeploy,
  availableRegions
}) {
  const [activeTab, setActiveTab] = useState(initialTab || 'source');
  const [apiTemplates, setApiTemplates] = useState([]);
  const [loadingTemplates, setLoadingTemplates] = useState(true);

  // Fetch templates on component mount
  useEffect(() => {
    const fetchTemplates = async () => {
      try {
        setLoadingTemplates(true);
        const templates = await templateService.getAllTemplates();
        // Format templates for UI use
        const formattedTemplates = templates
          .map(templateService.formatTemplateForForm)
          .filter(Boolean); // Filter out null values
        setApiTemplates(formattedTemplates);
      } catch (error) {
        console.error('Error fetching templates:', error);
        // Fall back to local templates
        setApiTemplates([]);
      } finally {
        setLoadingTemplates(false);
      }
    };
    
    fetchTemplates();
  }, []);

  // Combine API templates with local templates as fallback
  const combinedTemplates = apiTemplates.length > 0 ? apiTemplates : templates;

  // Initialize sourceType based on existing deployment
  const getInitialSourceType = () => {
    if (!deployment) return 'prebaked';
    if (deployment.gitUrl) return 'git';
    if (deployment.containerImage) {
      // Check if it's one of our templates
      const isTemplate = combinedTemplates.some(t => t.image === deployment.containerImage);
      return isTemplate ? 'prebaked' : 'container';
    }
    return 'prebaked';
  };

  const [sourceType, setSourceType] = useState(getInitialSourceType());

  // Set selected template if editing a template-based deployment
  const [selectedTemplate, setSelectedTemplate] = useState(() => {
    if (!deployment) return null;
    return combinedTemplates.find(t => t.image === deployment.containerImage) || null;
  });

  const [formData, setFormData] = useState({
    name: deployment?.name || '',
    sourceType: deployment?.sourceType || 'prebaked',
    gitUrl: deployment?.gitUrl || '',
    containerImage: deployment?.containerImage || '',
    regions: deployment?.regions || [],
    domain: deployment?.domain || '',
    useWildcard: deployment?.useWildcard ?? true,
    subdomain: deployment?.subdomain || '',
    env: deployment?.env || [],
    resources: deployment?.resources || {
      cpu: 0.5,
      memory: '512Mi'
    },
    selectedTemplateId: deployment?.selectedTemplateId || null
  });

  const [errors, setErrors] = useState({});
  const [subdomainOptions, setSubdomainOptions] = useState(generateSubdomainOptions());
  const [selectedSubdomain, setSelectedSubdomain] = useState(deployment?.subdomain || '');
  const [selectedContainer, setSelectedContainer] = useState('');
  const [autoScroll, setAutoScroll] = useState(true);
  const [logs, setLogs] = useState([
    // Example logs - replace with actual log fetching
    { timestamp: '2024-01-14T12:00:00Z', level: 'info', message: 'Starting deployment...' },
    { timestamp: '2024-01-14T12:00:01Z', level: 'debug', message: 'Pulling container image' },
    { timestamp: '2024-01-14T12:00:02Z', level: 'warn', message: 'Resource limits approaching' },
    { timestamp: '2024-01-14T12:00:03Z', level: 'error', message: 'Failed to connect to database' },
  ]);

  const toggleRegion = (regionId) => {
    setFormData(prev => {
      const newRegions = prev.regions.includes(regionId)
        ? prev.regions.filter(r => r !== regionId)
        : [...prev.regions, regionId];
      return { ...prev, regions: newRegions };
    });
  };

  const addEnvVar = () => {
    setFormData({
      ...formData,
      env: [...formData.env, { key: '', value: '' }]
    });
  };

  const updateEnvVar = (index, key, value) => {
    const newEnv = [...formData.env];
    newEnv[index] = { ...newEnv[index], [key]: value };
    
    // If this is a template parameter, also update the templateParameters object
    if (newEnv[index].isTemplateParam && key === 'value') {
      setFormData({
        ...formData,
        env: newEnv,
        templateParameters: {
          ...formData.templateParameters,
          [newEnv[index].key]: value
        }
      });
    } else {
      setFormData({ ...formData, env: newEnv });
    }
  };

  const removeEnvVar = (index) => {
    setFormData({
      ...formData,
      env: formData.env.filter((_, i) => i !== index)
    });
  };

  const handleSubdomainSelect = (subdomain) => {
    setSelectedSubdomain(subdomain);
    setFormData({
      ...formData,
      subdomain: subdomain,
      domain: `${subdomain}.container.mom`
    });
  };

  const handleDomainToggle = (useWildcard) => {
    setFormData({
      ...formData,
      useWildcard,
      domain: useWildcard ? (selectedSubdomain ? `${selectedSubdomain}.container.mom` : '') : '',
      subdomain: useWildcard ? selectedSubdomain : ''
    });
  };

  const handleTemplateSelect = (template) => {
    setSelectedTemplate(template);
    
    // Update form data with template values
    setFormData(prev => {
      // Initialize with existing form data
      const newFormData = {
        ...prev,
        containerImage: template.image,
        selectedTemplateId: template.id,
        templateParameters: {}, // Container for template parameters
        env: [] // Start with empty env then add both regular env and converted parameters
      };

      // Convert template parameters to environment variables for a unified UI
      if (template.parameters && template.parameters.length > 0) {
        // Add parameters as special environment variables
        template.parameters.forEach(param => {
          const defaultVal = param.generate === 'expression' 
            ? '[auto-generated]' 
            : (param.defaultValue || '');
          
          newFormData.env.push({
            key: param.name,
            value: defaultVal,
            isTemplateParam: true, // Mark as template parameter
            description: param.description,
            required: param.required,
            sensitive: param.type === 'password',
            readonly: param.generate === 'expression',
            displayName: param.displayName || param.name
          });
          
          // Also store in templateParameters for submission
          if (param.defaultValue) {
            newFormData.templateParameters[param.name] = param.defaultValue;
          } else if (param.generate === 'expression') {
            newFormData.templateParameters[param.name] = '[auto-generated]';
          } else {
            newFormData.templateParameters[param.name] = '';
          }
        });
      }

      // If template has regular env variables, include them
      if (template.env && template.env.length > 0) {
        // Add regular env vars after parameters
        template.env.forEach(env => {
          newFormData.env.push({
            ...env,
            isTemplateParam: false
          });
        });
      }

      return newFormData;
    });
  };

  // Update validateForm to include template parameter validation
  const validateForm = () => {
    const newErrors = {};

    // Basic validation
    if (!formData.name.trim()) {
      newErrors.name = 'Deployment name is required';
    } else if (!/^[a-z0-9\-]+$/.test(formData.name)) {
      newErrors.name = 'Name must contain only lowercase letters, numbers, and hyphens';
    }

    // Source-specific validation
    if (sourceType === 'git') {
      if (!formData.gitUrl) {
        newErrors.gitUrl = 'Git repository URL is required';
      } else if (!isValidUrl(formData.gitUrl)) {
        newErrors.gitUrl = 'Please enter a valid URL';
      }
    } else if (sourceType === 'container') {
      if (!formData.containerImage) {
        newErrors.containerImage = 'Container image is required';
      } else if (!isValidContainerImage(formData.containerImage)) {
        newErrors.containerImage = 'Please enter a valid container image';
      }
    } else if (sourceType === 'prebaked') {
      if (!selectedTemplate) {
        newErrors.template = 'Please select a template';
      }
    }

    // Validate required template parameters via env vars
    if (formData.env) {
      formData.env.forEach((env, index) => {
        if (!env.key.trim()) {
          newErrors[`env.${index}.key`] = 'Environment variable name is required';
        }
        if (env.isTemplateParam && env.required && !env.readonly && !env.value.trim()) {
          newErrors[`env.${index}.value`] = `${env.displayName || env.key} is required`;
        }
      });
    }

    // Domain validation
    if (!formData.useWildcard && !formData.domain) {
      newErrors.domain = 'Domain is required if not using a subdomain';
    }

    // Region validation
    if (formData.regions.length === 0) {
      newErrors.regions = 'At least one region must be selected';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // Update handleFormSubmit to include template parameters
  const handleFormSubmit = async () => {
    if (!validateForm()) {
      // Show error message
      alert('Please fix the validation errors before submitting');
      return;
    }

    try {
      let deploymentData;
      
      // If using a template, use the template parameters
      if (sourceType === 'prebaked' && selectedTemplate) {
        deploymentData = {
          name: formData.name,
          sourceType: 'prebaked',
          subdomain: formData.subdomain,
          regions: formData.regions,
          selectedTemplateId: selectedTemplate.id,
          params: formData.templateParameters || {}
        };
      } else {
        // Regular deployment data
        deploymentData = { ...formData };
      }
      
      const deploymentResult = await onDeploy(deploymentData);

      // Trigger reconciliation immediately after successful deployment
      await fetch(`/api/deployments/${deploymentResult._id}/reconcile`, {
        method: 'POST',
        credentials: 'include'
      });

      // Show success message
      alert(`Deployment "${deploymentResult.name}" created successfully!`);

      onClose();
    } catch (error) {
      console.error('Failed to save deployment:', error);
      setErrors({ submit: error.message });
      alert(`Failed to create deployment: ${error.message}`);
    }
  };

  const regenerateSubdomains = () => {
    const newOptions = generateSubdomainOptions();
    setSubdomainOptions(newOptions);
  };

  const refreshLogs = () => {
    // Implement log fetching here
    console.log('Refreshing logs...');
  };

  // Define tabs based on whether we're editing or creating
  const tabs = [
    { id: 'source', label: 'Source', icon: '📦' },
    { id: 'regions', label: 'Regions', icon: '🌎' },
    { id: 'config', label: 'Config', icon: '⚙️' },
    // Only show logs tab when editing
    ...(deployment ? [{ id: 'logs', label: 'Logs', icon: '📋' }] : [])
  ];

  // If we're creating and somehow got logs tab selected, default to source
  React.useEffect(() => {
    if (!deployment && activeTab === 'logs') {
      setActiveTab('source');
    }
  }, [deployment, activeTab]);

  return (
    <div className="deployment-form-overlay">
      <div className="deployment-form">
        <header className="form-header">
          <h2>{deployment ? 'Edit Deployment' : 'New Deployment'}</h2>
          <button className="close-btn" onClick={onClose}>×</button>
        </header>

        <div className="form-tabs">
          {tabs.map(tab => (
            <button
              key={tab.id}
              className={`form-tab ${activeTab === tab.id ? 'active' : ''}`}
              onClick={() => setActiveTab(tab.id)}
            >
              <span className="tab-icon">{tab.icon}</span>
              <span className="tab-label">{tab.label}</span>
            </button>
          ))}
        </div>

        <div className="tab-content">
          {activeTab === 'source' && (
            <div className="source-tab">
              <div className="input-group deployment-name">
                <label>Deployment Name</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="my-awesome-app"
                  className={errors.name ? 'error' : ''}
                />
                {errors.name && <div className="error-text">{errors.name}</div>}
              </div>

              <div className="source-selector">
                <h4>Select Source Type</h4>
                <div className="source-options">
                  <button
                    className={`source-option ${sourceType === 'prebaked' ? 'active' : ''}`}
                    onClick={() => setSourceType('prebaked')}
                  >
                    <span className="option-icon">🛠️</span>
                    <span className="option-label">Template</span>
                  </button>
                  <button
                    className={`source-option ${sourceType === 'git' ? 'active' : ''}`}
                    onClick={() => setSourceType('git')}
                  >
                    <span className="option-icon">📂</span>
                    <span className="option-label">Git Repo</span>
                  </button>
                  <button
                    className={`source-option ${sourceType === 'container' ? 'active' : ''}`}
                    onClick={() => setSourceType('container')}
                  >
                    <span className="option-icon">🐳</span>
                    <span className="option-label">Container</span>
                  </button>
                </div>
              </div>

              {sourceType === 'prebaked' && (
                <div className="prebaked-templates">
                  <h4>Choose a Template</h4>
                  
                  {loadingTemplates ? (
                    <div className="loading-templates">
                      <div className="spinner"></div>
                      <p>Loading templates...</p>
                    </div>
                  ) : (
                    <>
                      {combinedTemplates.length === 0 ? (
                        <div className="no-templates">
                          <p>No templates available. Please try again later.</p>
                        </div>
                      ) : (
                        <div className="templates-grid">
                          {combinedTemplates.map(template => (
                            <Card
                              key={template.id}
                              className={`template-card ${selectedTemplate?.id === template.id ? 'selected' : ''}`}
                              onClick={() => handleTemplateSelect(template)}
                            >
                              <div className="template-icon">{template.icon}</div>
                              <Card.Body>
                                <Card.Title>{template.name}</Card.Title>
                                <Card.Text>{template.description}</Card.Text>
                              </Card.Body>
                            </Card>
                          ))}
                        </div>
                      )}
                    </>
                  )}
                </div>
              )}

              {sourceType === 'git' && (
                <div className="git-source">
                  <div className="input-group">
                    <label>Git Repository URL</label>
                    <input
                      type="text"
                      value={formData.gitUrl}
                      onChange={(e) => setFormData({ ...formData, gitUrl: e.target.value })}
                      placeholder="https://github.com/yourusername/your-repo.git"
                      className={errors.gitUrl ? 'error' : ''}
                    />
                    {errors.gitUrl && <div className="error-text">{errors.gitUrl}</div>}
                  </div>
                  
                  <div className="advanced-options">
                    <h4>Git Options</h4>
                    <div className="input-group">
                      <label>Branch</label>
                      <input
                        type="text"
                        value={formData.gitBranch || ''}
                        onChange={(e) => setFormData({ ...formData, gitBranch: e.target.value })}
                        placeholder="main"
                      />
                    </div>
                  </div>
                </div>
              )}

              {sourceType === 'container' && (
                <div className="container-source">
                  <div className="input-group">
                    <label>Container Image</label>
                    <input
                      type="text"
                      value={formData.containerImage}
                      onChange={(e) => setFormData({ ...formData, containerImage: e.target.value })}
                      placeholder="nginx:latest"
                      className={errors.containerImage ? 'error' : ''}
                    />
                    {errors.containerImage && <div className="error-text">{errors.containerImage}</div>}
                  </div>
                </div>
              )}
            </div>
          )}

          {activeTab === 'regions' && (
            <div className="regions-tab">
              <h4>Select Deployment Regions</h4>
              {errors.regions && <div className="error-text">{errors.regions}</div>}

              <div className="regions-grid">
                {availableRegions.map(region => (
                  <div
                    key={region.id}
                    className={`region-card ${formData.regions.includes(region.id) ? 'selected' : ''}`}
                    onClick={() => toggleRegion(region.id)}
                  >
                    <div className="region-icon">{region.icon}</div>
                    <div className="region-details">
                      <h4>{region.name}</h4>
                      <p>{region.location}</p>
                    </div>
                    {formData.regions.includes(region.id) && (
                      <div className="selected-checkmark">✓</div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {activeTab === 'config' && (
            <div className="config-tab">
              <div className="domain-section">
                <h4>Domain Configuration</h4>
                <div className="domain-type-selector">
                  <button
                    className={`domain-type-btn ${formData.useWildcard ? 'active' : ''}`}
                    onClick={() => handleDomainToggle(true)}
                  >
                    Subdomain
                  </button>
                  <button
                    className={`domain-type-btn ${!formData.useWildcard ? 'active' : ''}`}
                    onClick={() => handleDomainToggle(false)}
                  >
                    Custom Domain
                  </button>
                </div>

                {formData.useWildcard ? (
                  <div className="subdomain-selector">
                    <label>Choose a subdomain</label>
                    {errors.domain && <div className="error-text">{errors.domain}</div>}
                    
                    <div className="subdomain-options">
                      {subdomainOptions.map(option => (
                        <button
                          key={option}
                          className={`subdomain-option ${selectedSubdomain === option ? 'selected' : ''}`}
                          onClick={() => handleSubdomainSelect(option)}
                        >
                          {option}.container.mom
                        </button>
                      ))}
                    </div>
                    <button
                      className="refresh-subdomains"
                      onClick={regenerateSubdomains}
                    >
                      🔄 Generate New Options
                    </button>
                  </div>
                ) : (
                  <div className="custom-domain-input">
                    <div className="input-group">
                      <label>Custom Domain</label>
                      <input
                        type="text"
                        value={formData.domain}
                        onChange={(e) => setFormData({ ...formData, domain: e.target.value })}
                        placeholder="app.yourdomain.com"
                        className={errors.domain ? 'error' : ''}
                      />
                      {errors.domain && <div className="error-text">{errors.domain}</div>}
                    </div>
                  </div>
                )}
              </div>

              <div className="env-vars-section">
                <h4>Environment Variables {selectedTemplate && selectedTemplate.parameters?.length > 0 && '& Template Parameters'}</h4>
                <div className="env-vars-list">
                  {formData.env.map((env, index) => (
                    <div key={`env-${index}`} className={`env-var-row ${env.isTemplateParam ? 'template-param' : ''}`}>
                      <div className="input-group">
                        <label>{env.isTemplateParam ? (env.displayName || env.key) : 'Key'}</label>
                        <input
                          type="text"
                          value={env.key}
                          onChange={(e) => updateEnvVar(index, 'key', e.target.value)}
                          placeholder="KEY"
                          className={errors[`env.${index}.key`] ? 'error' : ''}
                          disabled={env.isTemplateParam} // Template parameters shouldn't have their names changed
                          title={env.isTemplateParam ? 'Template parameter name cannot be changed' : ''}
                        />
                        {env.isTemplateParam && env.description && (
                          <div className="parameter-description">{env.description}</div>
                        )}
                        {errors[`env.${index}.key`] && (
                          <div className="error-text">{errors[`env.${index}.key`]}</div>
                        )}
                      </div>
                      <div className="input-group">
                        <label>Value</label>
                        <input
                          type={env.sensitive ? 'password' : 'text'}
                          value={env.value}
                          onChange={(e) => updateEnvVar(index, 'value', e.target.value)}
                          placeholder="value"
                          className={errors[`env.${index}.value`] ? 'error' : ''}
                          disabled={env.readonly}
                          title={env.readonly ? 'This value will be auto-generated' : ''}
                        />
                        {errors[`env.${index}.value`] && (
                          <div className="error-text">{errors[`env.${index}.value`]}</div>
                        )}
                        {env.isTemplateParam && env.required && (
                          <div className="required-indicator">Required</div>
                        )}
                      </div>
                      <button
                        className="remove-env-var"
                        onClick={() => removeEnvVar(index)}
                        disabled={env.isTemplateParam} // Can't remove template parameters
                        title={env.isTemplateParam ? 'Template parameters cannot be removed' : ''}
                      >
                        🗑
                      </button>
                    </div>
                  ))}
                </div>
                <button className="add-env-var" onClick={addEnvVar}>
                  Add Custom Environment Variable
                </button>
              </div>

              <div className="resources-section">
                <h4>Resource Configuration</h4>
                <div className="resource-slider">
                  <label>CPU: {formData.resources.cpu} cores</label>
                  <input
                    type="range"
                    min="0.1"
                    max="4"
                    step="0.1"
                    value={formData.resources.cpu}
                    onChange={(e) => setFormData({
                      ...formData,
                      resources: {
                        ...formData.resources,
                        cpu: parseFloat(e.target.value)
                      }
                    })}
                  />
                </div>
                <div className="resource-slider">
                  <label>Memory: {formData.resources.memory}</label>
                  <select
                    value={formData.resources.memory}
                    onChange={(e) => setFormData({
                      ...formData,
                      resources: {
                        ...formData.resources,
                        memory: e.target.value
                      }
                    })}
                  >
                    <option value="128Mi">128Mi</option>
                    <option value="256Mi">256Mi</option>
                    <option value="512Mi">512Mi</option>
                    <option value="1Gi">1Gi</option>
                    <option value="2Gi">2Gi</option>
                    <option value="4Gi">4Gi</option>
                  </select>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'logs' && deployment && (
            <div className="logs-tab">
              <div className="logs-controls">
                <select
                  value={selectedContainer}
                  onChange={(e) => setSelectedContainer(e.target.value)}
                >
                  <option value="">All Containers</option>
                  <option value="app">App</option>
                  <option value="init">Init</option>
                </select>
                <button onClick={refreshLogs}>
                  Refresh Logs
                </button>
                <label className="auto-scroll-toggle">
                  <input
                    type="checkbox"
                    checked={autoScroll}
                    onChange={(e) => setAutoScroll(e.target.checked)}
                  />
                  Auto-scroll
                </label>
              </div>
              <div className="logs-container">
                {logs.map((log, index) => (
                  <div key={index} className={`log-line ${log.level}`}>
                    <span className="log-timestamp">
                      {new Date(log.timestamp).toLocaleTimeString()}
                    </span>
                    <span className="log-level">[{log.level.toUpperCase()}]</span>
                    <span className="log-message">{log.message}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {errors.submit && (
            <div className="form-error">
              <span className="error-icon">⚠️</span>
              {errors.submit}
            </div>
          )}
        </div>

        <div className="form-actions">
          <button className="cancel-btn" onClick={onClose}>Cancel</button>
          <button
            className="deploy-btn"
            onClick={handleFormSubmit}
            disabled={Object.keys(errors).length > 0}
          >
            {deployment ? 'Save Changes' : 'Deploy'}
          </button>
        </div>
      </div>
    </div>
  );
}

export default Deployments;