// File: src/pages/Sites/AddSiteSuccess.jsx

import React, { useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router";
import { useAuth } from "../../services/Services";

/**
 * AddSiteSuccess - Success page after creating a WordPress site
 * Shows the API key (ONLY ONCE) with prominent warning to save it
 */
function AddSiteSuccess() {
  const navigate = useNavigate();
  const location = useLocation();
  const { authManager } = useAuth();
  const [copied, setCopied] = useState(false);
  const [copiedToken, setCopiedToken] = useState(false);

  // Get site data from navigation state
  const siteData = location.state?.siteData;

  useEffect(() => {
    // If no site data, redirect back to add site page
    if (!siteData) {
      navigate("/sites/add");
      return;
    }

    // Check authentication
    const checkAuth = () => {
      const isInitialized = authManager.getIsInitialized();
      if (!isInitialized) {
        setTimeout(checkAuth, 50);
        return;
      }

      const isAuth = authManager.isAuthenticated();
      if (!isAuth) {
        navigate("/login");
      }
    };

    checkAuth();
  }, [authManager, navigate, siteData]);

  const handleCopyApiKey = () => {
    navigator.clipboard.writeText(siteData.api_key);
    setCopied(true);
    setTimeout(() => setCopied(false), 3000);
  };

  const handleCopyVerificationToken = () => {
    const txtRecord = `maplepress-verify=${siteData.verification_token}`;
    navigator.clipboard.writeText(txtRecord);
    setCopiedToken(true);
    setTimeout(() => setCopiedToken(false), 3000);
  };

  const handleDone = () => {
    navigate("/dashboard");
  };

  if (!siteData) {
    return null;
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100">
      {/* Navigation Bar */}
      <nav className="bg-white border-b border-gray-200 shadow-sm sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            {/* Logo */}
            <button
              onClick={() => navigate("/dashboard")}
              className="flex items-center gap-2 hover:opacity-80 transition-opacity"
            >
              <span className="text-2xl">🍁</span>
              <h1 className="text-xl font-bold bg-gradient-to-r from-indigo-600 to-blue-600 bg-clip-text text-transparent">
                MaplePress
              </h1>
            </button>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Success Header */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-green-100 rounded-full mb-4">
            <span className="text-3xl">✓</span>
          </div>
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            Site Created Successfully!
          </h1>
          <p className="text-gray-600">
            Your WordPress site has been registered with MaplePress
          </p>
        </div>

        {/* Critical Warning Box */}
        <div className="mb-8 p-6 bg-red-50 border-2 border-red-300 rounded-lg">
          <div className="flex items-start gap-4">
            <span className="text-4xl flex-shrink-0">⚠️</span>
            <div className="flex-1">
              <h2 className="text-xl font-bold text-red-900 mb-2">
                IMPORTANT: Save Your API Key Now!
              </h2>
              <div className="space-y-2 text-red-800">
                <p className="font-semibold">
                  This API key will <span className="underline">ONLY be shown once</span> and cannot be retrieved later.
                </p>
                <p>
                  If you lose this key, you will need to generate a new one, which will invalidate the current key.
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Site Information Card */}
        <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden mb-6">
          <div className="p-8">
            {/* Site Details */}
            <div className="mb-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">Site Details</h3>
              <div className="space-y-3">
                <div>
                  <span className="text-sm text-gray-600">Domain:</span>
                  <p className="font-medium text-gray-900">{siteData.domain}</p>
                </div>
                <div>
                  <span className="text-sm text-gray-600">Site URL:</span>
                  <p className="font-medium text-gray-900">{siteData.site_url}</p>
                </div>
                <div>
                  <span className="text-sm text-gray-600">Status:</span>
                  <p className="font-medium text-yellow-600 capitalize">{siteData.status}</p>
                </div>
              </div>
            </div>

            {/* API Key Section */}
            <div className="mb-6 p-6 bg-yellow-50 border-2 border-yellow-200 rounded-lg">
              <h3 className="text-lg font-bold text-gray-900 mb-4">
                Your API Key
              </h3>
              <div className="bg-white rounded-lg p-4 border border-yellow-300 mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  API Key (copy this now!)
                </label>
                <div className="flex gap-2">
                  <input
                    type="text"
                    value={siteData.api_key}
                    readOnly
                    className="flex-1 px-4 py-3 border border-gray-300 rounded-lg bg-gray-50 font-mono text-sm"
                  />
                  <button
                    onClick={handleCopyApiKey}
                    className={`px-6 py-3 rounded-lg font-medium transition-all
                      ${copied
                        ? "bg-green-600 text-white"
                        : "bg-indigo-600 text-white hover:bg-indigo-700"
                      }`}
                  >
                    {copied ? "✓ Copied!" : "Copy"}
                  </button>
                </div>
              </div>
              <p className="text-sm text-gray-700">
                <strong>Remember:</strong> Store this API key in a secure location like a password manager.
                You'll need it to configure the MaplePress WordPress plugin.
              </p>
            </div>
          </div>
        </div>

        {/* DNS Verification Section */}
        <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden mb-6">
          <div className="p-8">
            <div className="flex items-start gap-4 mb-6">
              <span className="text-4xl flex-shrink-0">🔐</span>
              <div>
                <h3 className="text-lg font-semibold text-gray-900 mb-2">
                  Verify Domain Ownership
                </h3>
                <p className="text-gray-600 text-sm">
                  To activate your site, you need to prove you own the domain by adding a DNS TXT record.
                  This is the same method used by Google Search Console and other major services.
                </p>
              </div>
            </div>

            {/* DNS TXT Record */}
            <div className="mb-6 p-6 bg-blue-50 border-2 border-blue-200 rounded-lg">
              <h4 className="text-md font-bold text-gray-900 mb-3">
                Add this DNS TXT record to {siteData.domain}
              </h4>

              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Host/Name:
                  </label>
                  <div className="bg-white rounded-lg p-3 border border-blue-300 font-mono text-sm">
                    {siteData.domain}
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Type:
                  </label>
                  <div className="bg-white rounded-lg p-3 border border-blue-300 font-mono text-sm">
                    TXT
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Value:
                  </label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={`maplepress-verify=${siteData.verification_token}`}
                      readOnly
                      className="flex-1 px-4 py-3 border border-blue-300 rounded-lg bg-white font-mono text-sm"
                    />
                    <button
                      onClick={handleCopyVerificationToken}
                      className={`px-6 py-3 rounded-lg font-medium transition-all
                        ${copiedToken
                          ? "bg-green-600 text-white"
                          : "bg-blue-600 text-white hover:bg-blue-700"
                        }`}
                    >
                      {copiedToken ? "✓ Copied!" : "Copy"}
                    </button>
                  </div>
                </div>
              </div>

              <div className="mt-6 p-4 bg-blue-100 rounded-lg">
                <h5 className="font-semibold text-gray-900 mb-2 text-sm">
                  📝 Instructions:
                </h5>
                <ol className="text-sm text-gray-700 space-y-1 list-decimal list-inside">
                  <li>Log in to your domain registrar (GoDaddy, Namecheap, Cloudflare, etc.)</li>
                  <li>Find DNS settings or DNS management</li>
                  <li>Add a new TXT record with the values above</li>
                  <li>Wait 5-10 minutes for DNS propagation</li>
                  <li>Click "Verify Domain" in the MaplePress WordPress plugin</li>
                </ol>
                <p className="text-xs text-gray-600 mt-3">
                  <strong>Note:</strong> DNS changes can take up to 48 hours to propagate globally, but usually complete within 10 minutes.
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Next Steps */}
        <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden mb-6">
          <div className="p-8">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Next Steps</h3>
            <ol className="space-y-4">
              <li className="flex items-start gap-3">
                <span className="flex-shrink-0 w-8 h-8 bg-indigo-600 text-white rounded-full
                               flex items-center justify-center text-sm font-bold">
                  1
                </span>
                <div>
                  <h4 className="font-semibold text-gray-900">Add DNS TXT Record</h4>
                  <p className="text-sm text-gray-600 mt-1">
                    Add the DNS TXT record shown above to your domain registrar. This proves you own the domain.
                  </p>
                </div>
              </li>
              <li className="flex items-start gap-3">
                <span className="flex-shrink-0 w-8 h-8 bg-indigo-600 text-white rounded-full
                               flex items-center justify-center text-sm font-bold">
                  2
                </span>
                <div>
                  <h4 className="font-semibold text-gray-900">Install the MaplePress WordPress Plugin</h4>
                  <p className="text-sm text-gray-600 mt-1">
                    Download and install the MaplePress plugin on your WordPress site.
                  </p>
                </div>
              </li>
              <li className="flex items-start gap-3">
                <span className="flex-shrink-0 w-8 h-8 bg-indigo-600 text-white rounded-full
                               flex items-center justify-center text-sm font-bold">
                  3
                </span>
                <div>
                  <h4 className="font-semibold text-gray-900">Configure the Plugin with Your API Key</h4>
                  <p className="text-sm text-gray-600 mt-1">
                    Go to your WordPress admin panel → Settings → MaplePress and enter the API key you saved earlier.
                  </p>
                </div>
              </li>
              <li className="flex items-start gap-3">
                <span className="flex-shrink-0 w-8 h-8 bg-indigo-600 text-white rounded-full
                               flex items-center justify-center text-sm font-bold">
                  4
                </span>
                <div>
                  <h4 className="font-semibold text-gray-900">Verify Your Domain</h4>
                  <p className="text-sm text-gray-600 mt-1">
                    After DNS propagation (5-10 minutes), click "Verify Domain" in the plugin to activate cloud-powered features.
                  </p>
                </div>
              </li>
            </ol>
          </div>
        </div>

        {/* Action Button */}
        <div className="flex justify-center">
          <button
            onClick={handleDone}
            className="px-8 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700
                     transition-all font-medium text-lg shadow-lg"
          >
            Go to Dashboard
          </button>
        </div>
      </main>
    </div>
  );
}

export default AddSiteSuccess;
