import React, { useState } from "react";

export default function DeployWordPress() {
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");
  const [debugInfo, setDebugInfo] = useState(null);

  // Configuration - Replace with your actual values
  const COOLIFY_API_URL = "http://192.168.1.197:8000/api/v1";
  const TOKEN = "zXSR33z74eK26abbKyL9bz4d3PYouTSK8FSjOltv719c52d8";
  const PROJECT_UUID = "wc40gg048gkwg0go80ggog44";
  const SERVER_UUID = "sgswssowscc84o8sc8wockgc";
  const ENVIRONMENT_NAME = "production"; // Changed from 'dev' to 'production' as default

  const createWordPress = async () => {
    setLoading(true);
    setMessage("");
    setDebugInfo(null);

    try {
      // 1. Create MySQL Service - Updated to Coolify's expected format
      const mysqlPayload = {
        name: "wordpress-db",
        type: "mysql",
        projectUuid: PROJECT_UUID,
        serverUuid: SERVER_UUID,
        version: "8.0",
        destination: {  // Coolify often requires this structure
          serverUuid: SERVER_UUID,
          environment: ENVIRONMENT_NAME
        },
        configuration: {
          type: "mysql",
          settings: {  // Changed from environmentVariables to settings
            MYSQL_ROOT_PASSWORD: "example",
            MYSQL_DATABASE: "wordpress",
            MYSQL_USER: "wordpress",
            MYSQL_PASSWORD: "example",
            MYSQL_ALLOW_EMPTY_PASSWORD: "no"
          }
        }
      };

      const mysqlRes = await fetch(`${COOLIFY_API_URL}/services`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${TOKEN}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(mysqlPayload),
      });

      const mysqlData = await mysqlRes.json();
      setDebugInfo({ mysql: { request: mysqlPayload, response: mysqlData } });

      if (!mysqlRes.ok) {
        throw new Error(
          mysqlData.message || 
          mysqlData.error?.message || 
          JSON.stringify(mysqlData.errors) || 
          "MySQL validation failed"
        );
      }

      // 2. Create WordPress Service
      const wpPayload = {
        name: "wordpress",
        type: "wordpress",
        projectUuid: PROJECT_UUID,
        serverUuid: SERVER_UUID,
        version: "latest",
        destination: {
          serverUuid: SERVER_UUID,
          environment: ENVIRONMENT_NAME
        },
        configuration: {
          type: "wordpress",
          settings: {
            WORDPRESS_DB_HOST: "wordpress-db",
            WORDPRESS_DB_USER: "wordpress",
            WORDPRESS_DB_PASSWORD: "example",
            WORDPRESS_DB_NAME: "wordpress",
            WORDPRESS_TABLE_PREFIX: "wp_"
          }
        }
      };

      const wpRes = await fetch(`${COOLIFY_API_URL}/services`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${TOKEN}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(wpPayload),
      });

      const wpData = await wpRes.json();
      setDebugInfo(prev => ({ ...prev, wordpress: { request: wpPayload, response: wpData } }));

      if (!wpRes.ok) {
        throw new Error(
          wpData.message || 
          wpData.error?.message || 
          JSON.stringify(wpData.errors) || 
          "WordPress validation failed"
        );
      }

      setMessage("🎉 WordPress + MySQL deployed successfully!");
    } catch (err) {
      setMessage(`❌ Deployment failed: ${err.message}`);
      console.error("Deployment error:", err, debugInfo);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-6 max-w-md mx-auto bg-white rounded-xl shadow-md">
      <h2 className="text-2xl font-bold mb-4">Deploy WordPress</h2>
      
      <button
        onClick={createWordPress}
        disabled={loading}
        className={`w-full py-2 px-4 rounded-md text-white font-medium ${
          loading ? "bg-gray-400 cursor-not-allowed" : "bg-blue-600 hover:bg-blue-700"
        }`}
      >
        {loading ? (
          <span className="flex items-center justify-center">
            <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            Deploying...
          </span>
        ) : "Deploy WordPress"}
      </button>

      {message && (
        <div className={`mt-4 p-3 rounded-md ${
          message.includes("❌") ? "bg-red-50 text-red-700" : "bg-green-50 text-green-700"
        }`}>
          {message}
        </div>
      )}

      {debugInfo && (
        <div className="mt-4 space-y-4">
          <details className="bg-gray-50 rounded-md p-2">
            <summary className="font-medium cursor-pointer">Debug Details</summary>
            <div className="mt-2 bg-white p-2 rounded border border-gray-200 overflow-auto max-h-60">
              <pre>{JSON.stringify(debugInfo, null, 2)}</pre>
            </div>
          </details>
          <div className="text-sm text-gray-600">
            <p className="font-medium">Troubleshooting:</p>
            <ul className="list-disc pl-5 space-y-1 mt-1">
              <li>Verify <code>PROJECT_UUID</code> and <code>SERVER_UUID</code> are correct</li>
              <li>Check if environment <code>{ENVIRONMENT_NAME}</code> exists</li>
              <li>Ensure your Coolify version supports this API format</li>
            </ul>
          </div>
        </div>
      )}
    </div>
  );
}


// [{"uuid":"sgswssowscc84o8sc8wockgc","description":"This is the server where Coolify is running on. Don't delete this!","name":"localhost","ip":"host.docker.internal","is_coolify_host":true,"is_reachable":true,"is_usable":true,"port":22,"proxy":{"redirect_enabled":true},"settings":{"id":1,"concurrent_builds":2,"delete_unused_networks":false,"delete_unused_volumes":false,"docker_cleanup_frequency":"0 0 * * *","docker_cleanup_threshold":80,"dynamic_timeout":3600,"force_disabled":false,"force_docker_cleanup":true,"generate_exact_labels":false,"is_build_server":false,"is_cloudflare_tunnel":false,"is_jump_server":false,"is_logdrain_axiom_enabled":false,"is_logdrain_custom_enabled":false,"is_logdrain_highlight_enabled":false,"is_logdrain_newrelic_enabled":false,"is_metrics_enabled":false,"is_reachable":true,"is_sentinel_debug_enabled":false,"is_sentinel_enabled":false,"is_swarm_manager":false,"is_swarm_worker":false,"is_usable":true,"logdrain_axiom_api_key":null,"logdrain_axiom_dataset_name":null,"logdrain_custom_config":null,"logdrain_custom_config_parser":null,"logdrain_highlight_project_id":null,"logdrain_newrelic_base_uri":null,"logdrain_newrelic_license_key":null,"sentinel_custom_url":"http:\/\/host.docker.internal:8000","sentinel_metrics_history_days":7,"sentinel_metrics_refresh_rate_seconds":10,"sentinel_push_interval_seconds":60,"sentinel_token":"eyJpdiI6IllwMlBsOUtXODdUR0ZIbWtZenJRWFE9PSIsInZhbHVlIjoiZFUxcE9zSXFXdkVrN0tDUGdSbHpGVTE3cHVEeFlBM1hFWk56S05NVWVmVmxHV0tBQ2kra25uRnVzRzNHaFpBSGVTaGZLMGpqdS9nMU85MXhmS3VYMVE9PSIsIm1hYyI6ImY3ODQyNGI2OTVlMmRiMzFmNzJjZjRlYjNkNDIxOGVmZTAxOWMyNjY0ZTYxODE5MDIwY2FhMGUwYjU4ODMyN2MiLCJ0YWciOiIifQ==","server_disk_usage_check_frequency":"0 23 * * *","server_disk_usage_notification_threshold":80,"server_id":0,"server_timezone":"UTC","wildcard_domain":null,"created_at":"2025-04-03T17:12:45.000000Z","updated_at":"2025-04-03T17:16:25.000000Z"},"user":"root"}]