// components/GiteaWidget/GiteaWidget.jsx
import React, { useState, useEffect } from 'react';
import useGiteaCommits from '../../hooks/useGiteaCommits';
import GiteaCommitItem from "./GiteaCommitItem";
import { FaCodeBranch, FaSync, FaExclamationTriangle, FaServer, FaCog } from 'react-icons/fa';
import '../../styles/GiteaWidget.css';

// Get environment variables from import.meta.env
const ENV = {
  GITEA_API_URL: import.meta.env.VITE_GITEA_API_URL,
  DEFAULT_REPO: import.meta.env.VITE_DEFAULT_REPO,
  GITEA_TOKEN: import.meta.env.VITE_GITEA_TOKEN,
  COMMIT_LIMIT: parseInt(import.meta.env.VITE_COMMIT_LIMIT) || 5,
  DEFAULT_BRANCH: import.meta.env.VITE_DEFAULT_BRANCH,
  SHOW_CONFIG: import.meta.env.VITE_SHOW_CONFIG !== 'false',
  MODE: import.meta.env.MODE, // 'development', 'production', etc.
  DEV: import.meta.env.DEV,
  PROD: import.meta.env.PROD
};

const GiteaWidget = ({ 
  // Use environment variables as defaults
  defaultGiteaUrl = ENV.GITEA_API_URL || 'https://gitea.example.com',
  defaultRepo = ENV.DEFAULT_REPO || 'owner/repo',
  token = ENV.GITEA_TOKEN || null,
  limit = ENV.COMMIT_LIMIT || 5,
  branch = ENV.DEFAULT_BRANCH || 'main',
  title = 'Recent Commits',
  showConfig = ENV.SHOW_CONFIG
}) => {
  const [giteaUrl, setGiteaUrl] = useState(defaultGiteaUrl);
  const [repo, setRepo] = useState(defaultRepo);
  const [inputGiteaUrl, setInputGiteaUrl] = useState(defaultGiteaUrl);
  const [inputRepo, setInputRepo] = useState(defaultRepo);
  const [showAdvanced, setShowAdvanced] = useState(false);
  
  // Log environment variables in development
  useEffect(() => {
    if (ENV.DEV) {
      console.log('Vite Environment Variables:', {
        GITEA_API_URL: ENV.GITEA_API_URL,
        DEFAULT_REPO: ENV.DEFAULT_REPO,
        hasToken: !!ENV.GITEA_TOKEN,
        MODE: ENV.MODE,
        allEnv: import.meta.env
      });
    }
  }, []);

  const { commits, loading, error } = useGiteaCommits(
    giteaUrl, 
    repo, 
    token, 
    limit, 
    branch
  );

  const handleSubmit = (e) => {
    e.preventDefault();
    
    // Validate URL
    let url = inputGiteaUrl?.trim();
    if (url && !url.startsWith('http')) {
      url = `https://${url}`;
    }
    
    // Remove trailing slash if present
    url = url?.replace(/\/$/, '') || defaultGiteaUrl;
    
    setGiteaUrl(url);
    
    // Validate repo format
    if (inputRepo.includes('/')) {
      setRepo(inputRepo);
    } else {
      alert('Repository must be in format "owner/repo"');
    }
  };

  // Reset to environment defaults
  const resetToDefaults = () => {
    setGiteaUrl(defaultGiteaUrl);
    setRepo(defaultRepo);
    setInputGiteaUrl(defaultGiteaUrl);
    setInputRepo(defaultRepo);
  };

  return (
    <div className="gitea-widget">
      <div className="widget-header">
        <FaServer className="gitea-icon" />
        <h3>{title}</h3>
        <span className="env-badge">
          {ENV.MODE === 'development' ? 'DEV' : ENV.MODE}
        </span>
        
        {showConfig && (
          <div className="header-controls">
            <button 
              className="advanced-toggle"
              onClick={() => setShowAdvanced(!showAdvanced)}
              title={showAdvanced ? 'Hide configuration' : 'Show configuration'}
            >
              {showAdvanced ? 'Simple' : 'Configure'}
            </button>
            <button 
              className="reset-btn"
              onClick={resetToDefaults}
              title="Reset to default configuration"
            >
              <FaCog />
            </button>
          </div>
        )}
      </div>

      {/* Configuration form */}
      {showConfig && showAdvanced && (
        <form onSubmit={handleSubmit} className="config-form">
          <div className="form-group">
            <label>
              <FaServer /> Gitea Instance URL
              <span className="env-indicator">
                {inputGiteaUrl === defaultGiteaUrl ? '(from .env)' : '(custom)'}
              </span>
            </label>
            <input
              type="text"
              value={inputGiteaUrl}
              onChange={(e) => setInputGiteaUrl(e.target.value)}
              placeholder={defaultGiteaUrl}
              className="url-input"
            />
            <small className="help-text">
              Default from .env: <code>{defaultGiteaUrl}</code>
            </small>
          </div>
          
          <div className="form-group">
            <label>
              <FaCodeBranch /> Repository
              <span className="env-indicator">
                {inputRepo === defaultRepo ? '(from .env)' : '(custom)'}
              </span>
            </label>
            <input
              type="text"
              value={inputRepo}
              onChange={(e) => setInputRepo(e.target.value)}
              placeholder={defaultRepo}
              className="repo-input"
            />
            <small className="help-text">
              Format: owner/repo | Default from .env: <code>{defaultRepo}</code>
            </small>
          </div>
          
          <div className="form-actions">
            <button type="submit" className="refresh-btn">
              <FaSync /> Load Commits
            </button>
            <button type="button" className="cancel-btn" onClick={() => setShowAdvanced(false)}>
              Cancel
            </button>
          </div>
        </form>
      )}

      {/* Current configuration display */}
      <div className="current-config">
        <div className="config-info">
          <span className="config-item">
            <FaServer /> <strong>Instance:</strong> 
            <code>{giteaUrl === defaultGiteaUrl ? 'Default' : 'Custom'}</code>
          </span>
          <span className="config-item">
            <FaCodeBranch /> <strong>Repo:</strong> 
            <code>{repo}</code>
          </span>
          <span className="config-item">
            <strong>Branch:</strong> <code>{branch}</code>
          </span>
          <span className="config-item">
            <strong>Showing:</strong> <code>{limit} commits</code>
          </span>
          {ENV.DEV && (
            <span className="config-item">
              <strong>Mode:</strong> <code className="mode-dev">{ENV.MODE}</code>
            </span>
          )}
        </div>
      </div>

      {/* Widget body */}
      <div className="widget-body">
        {loading ? (
          <div className="loading">
            <div className="spinner"></div>
            Loading commits from {repo}...
          </div>
        ) : error ? (
          <div className="error">
            <FaExclamationTriangle />
            <div className="error-details">
              <p>Failed to load commits</p>
              <small>{error}</small>
              {ENV.DEV && (
                <div className="debug-info">
                  <p>Debug info:</p>
                  <ul>
                    <li>URL: {giteaUrl}</li>
                    <li>Repo: {repo}</li>
                    <li>Has Token: {token ? 'Yes' : 'No'}</li>
                    <li>Mode: {ENV.MODE}</li>
                  </ul>
                </div>
              )}
            </div>
          </div>
        ) : (
          <div className="commits-list">
            {commits.length > 0 ? (
              commits.map((commit) => (
                <GiteaCommitItem 
                  key={commit.sha} 
                  commit={commit}
                  giteaUrl={giteaUrl}
                  repo={repo}
                />
              ))
            ) : (
              <div className="no-commits">
                No commits found in the {branch} branch
              </div>
            )}
          </div>
        )}
      </div>
      
      <div className="widget-footer">
        <a 
          href={`${giteaUrl}/${repo}`}
          target="_blank"
          rel="noopener noreferrer"
          className="view-all"
        >
          View on Gitea →
        </a>
        <span className="commit-count">
          {commits.length} commits shown
          {ENV.DEV && ` (${ENV.MODE})`}
        </span>
      </div>
    </div>
  );
};

// Add default props using environment variables
GiteaWidget.defaultProps = {
  defaultGiteaUrl: ENV.GITEA_API_URL || 'https://gitea.example.com',
  defaultRepo: ENV.DEFAULT_REPO || 'owner/repo',
  token: ENV.GITEA_TOKEN || null,
  limit: ENV.COMMIT_LIMIT || 5,
  branch: ENV.DEFAULT_BRANCH || 'main',
  title: 'Recent Commits',
  showConfig: ENV.SHOW_CONFIG
};

export default GiteaWidget;