import React, { useState, useRef, useEffect } from 'react';
import { API_BASE_URL } from '../../config/apiConfig';

interface DeployListProps {
  setLog: React.Dispatch<React.SetStateAction<string>>;
  token: string;
}

// Define the expected type from your deploy API response.
interface DeployResult {
  success: boolean;
  log: string;
  error?: string;
}

// Backup types
type BackupType = 'database' | 'data' | 'all';

// A list of project identifiers; adjust this list as needed.
const projects: string[] = ['cco', 'another'];

const DeployList: React.FC<DeployListProps> = ({ setLog, token }) => {
  const [status, setStatus] = useState<Record<string, string>>({});
  const [dropdownOpen, setDropdownOpen] = useState<Record<string, boolean>>({});
  const dropdownRefs = useRef<Record<string, HTMLDivElement | null>>({});

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      Object.entries(dropdownRefs.current).forEach(([project, ref]) => {
        if (ref && !ref.contains(event.target as Node)) {
          setDropdownOpen(prev => ({ ...prev, [project]: false }));
        }
      });
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // Handle migration request.
  const handleMigration = async (project: string) => {
    if (!window.confirm(`Are you sure you want to start migration for ${project}?`)) {
      return; // Exit if user cancels
    }

    setStatus((prev) => ({ ...prev, [project]: 'Migrating...' }));
    setLog(''); // Clear the log before starting
    try {
      const response = await fetch(`${API_BASE_URL}/api/migrate.php`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ project }),
      });
      if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
      }
      const data: DeployResult = await response.json();
      setStatus((prev) => ({
        ...prev,
        [project]: data.success ? '✅ Success' : '❌ Failed',
      }));
      setLog(data.log);
    } catch (error: any) {
      setStatus((prev) => ({ ...prev, [project]: '❌ Error' }));
      setLog(error.message);
    }
  };

  // Handle deploy request.
  const handleDeploy = async (project: string) => {
    if (!window.confirm(`Are you sure you want to deploy ${project}?`)) {
      return; // Exit if user cancels
    }
    setStatus((prev) => ({ ...prev, [project]: 'Deploying...' }));
    setLog(''); // Clear the log before starting
    try {
      const response = await fetch(`${API_BASE_URL}/api/deploy.php`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ project }),
      });
      if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
      }
      const data: DeployResult = await response.json();
      setStatus((prev) => ({
        ...prev,
        [project]: data.success ? '✅ Success' : '❌ Failed',
      }));
      setLog(data.log);
    } catch (error: any) {
      setStatus((prev) => ({ ...prev, [project]: '❌ Error' }));
      setLog(error.message);
    }
  };

  // Toggle dropdown for backup options
  const toggleDropdown = (project: string) => {
    setDropdownOpen(prev => ({ 
      ...prev, 
      [project]: !prev[project] 
    }));
  };

  // Handle backup request with type
  const handleBackup = async (project: string, type: BackupType) => {
    if (!window.confirm(`Are you sure you want to back up ${type} for ${project}?`)) {
      return; // Exit if user cancels
    }

    setDropdownOpen(prev => ({ ...prev, [project]: false }));
    setStatus(prev => ({ ...prev, [project]: `Backing up ${type}...` }));
    setLog(''); // Clear the log before starting
    
    try {
      const response = await fetch(`${API_BASE_URL}/api/backup.php`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ project, type }), // Include backup type in the request
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
      }
      
      const data: DeployResult = await response.json();
      setStatus(prev => ({
        ...prev,
        [project]: data.success ? `✅ ${type} Backup Success` : `❌ ${type} Backup Failed`,
      }));
      setLog(data.log);
    } catch (error: any) {
      setStatus(prev => ({ ...prev, [project]: `❌ ${type} Backup Error` }));
      setLog(error.message);
    }
  };

  return (
    <div className="rounded-2xl border border-gray-200 bg-white px-5 pb-5 pt-5 dark:border-gray-800 dark:bg-white/[0.03] sm:px-6 sm:pt-6">
      <div className="flex flex-col gap-5 mb-6 sm:flex-row sm:justify-between">
        <div className="w-full">
          <h3 className="text-lg font-semibold text-gray-800 dark:text-white/90">
            Deploy List
          </h3>
          <p className="mt-1 text-gray-500 text-sm dark:text-gray-400">
            Target you've set for each month
          </p>
          <hr />
        </div>
      </div>
      <div className="max-w-full overflow-x-auto custom-scrollbar">
        {projects.map((project) => (
          <div
            key={project}
            className="flex items-center justify-between border-b border-gray-300 py-2"
          >
            <span className="text-lg font-medium">{project}</span>
            <div className="flex items-center gap-2">
              <span className="text-right pr-10 min-w-[100px]">{status[project]}</span>
              <button
                onClick={() => handleDeploy(project)}
                className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 inline-flex items-center"
              >
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                </svg>
                Deploy
              </button>
              <button
                onClick={() => handleMigration(project)}
                className="bg-teal-600 text-white px-4 py-2 rounded hover:bg-teal-700 inline-flex items-center"
              >
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
                </svg>
                Migration
              </button>
              <div className="relative inline-block text-left" ref={el => dropdownRefs.current[project] = el}>
                <div>
                  <button
                    type="button"
                    onClick={() => toggleDropdown(project)}
                    className="inline-flex items-center justify-center gap-x-1.5 rounded-md bg-purple-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-purple-700"
                    id="backup-menu-button"
                    aria-expanded={dropdownOpen[project] ? "true" : "false"}
                    aria-haspopup="true"
                  >
                    <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 4H6a2 2 0 00-2 2v12a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-2m-4-1v8m0 0l3-3m-3 3L9 8m-5 5h2.586a1 1 0 01.707.293l2.414 2.414a1 1 0 00.707.293h3.172a1 1 0 00.707-.293l2.414-2.414a1 1 0 01.707-.293H20" />
                    </svg>
                    Backup
                    <svg className="ml-1 size-5 text-white" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" data-slot="icon">
                      <path fillRule="evenodd" d="M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z" clipRule="evenodd" />
                    </svg>
                  </button>
                </div>

                {/* Dropdown menu */}
                {dropdownOpen[project] && (
                  <div 
                    className="fixed z-50 mt-2 w-56 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black/5 focus:outline-none" 
                    role="menu" 
                    aria-orientation="vertical" 
                    aria-labelledby="backup-menu-button" 
                    tabIndex={-1}
                    style={{
                      top: `${dropdownRefs.current[project]?.getBoundingClientRect().bottom}px`,
                      left: `${dropdownRefs.current[project]?.getBoundingClientRect().right - 224}px`
                    }}
                  >
                    <div className="py-1" role="none">
                      <button
                        onClick={() => handleBackup(project, 'database')}
                        className="block w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-100 inline-flex items-center"
                        role="menuitem"
                        tabIndex={-1}
                      >
                        <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4" />
                        </svg>
                        Database
                      </button>
                      <button
                        onClick={() => handleBackup(project, 'data')}
                        className="block w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-100 inline-flex items-center"
                        role="menuitem"
                        tabIndex={-1}
                      >
                        <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        Data
                      </button>
                      <button
                        onClick={() => handleBackup(project, 'all')}
                        className="block w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-100 inline-flex items-center"
                        role="menuitem"
                        tabIndex={-1}
                      >
                        <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" />
                        </svg>
                        All
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default DeployList;
