'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import Button from '@/components/ui/Button';

interface MigrationStatus {
  needsMigration: boolean;
  domain: string | null;
  currentMethod: 'managed' | 'self_managed' | null;
  currentStatus: string | null;
  migrated: boolean;
  migratedAt: string | null;
  cnameDomain: string | null;
  cnameConfigured: boolean;
  instructions: {
    managed: string[] | null;
    selfManaged: string[] | null;
  } | null;
}

type WizardStep =
  | 'loading'
  | 'intro'
  | 'instructions'
  | 'verify'
  | 'migrating'
  | 'complete'
  | 'error';

interface DomainMigrationWizardProps {
  isAuthenticated: boolean;
}

export function DomainMigrationWizard({ isAuthenticated }: DomainMigrationWizardProps) {
  const router = useRouter();
  const [step, setStep] = useState<WizardStep>('loading');
  const [status, setStatus] = useState<MigrationStatus | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [checking, setChecking] = useState(false);
  const [copiedCname, setCopiedCname] = useState(false);

  const fetchMigrationStatus = useCallback(async () => {
    try {
      const response = await fetch('/api/dealer/custom-domain/migrate');
      const data = await response.json();

      if (data.success) {
        setStatus(data.data);

        if (!data.data.needsMigration) {
          if (data.data.migrated) {
            setStep('complete');
          } else {
            // No custom domain or already certbot-managed
            router.push('/dashboard/settings/domains');
          }
        } else {
          setStep('intro');
        }
      } else {
        setError(data.error || 'Failed to load migration status');
        setStep('error');
      }
    } catch {
      setError('Failed to load migration status');
      setStep('error');
    }
  }, [router]);

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

  function handleCopyCname() {
    if (status?.cnameDomain) {
      navigator.clipboard.writeText(status.cnameDomain);
      setCopiedCname(true);
      setTimeout(() => setCopiedCname(false), 2000);
    }
  }

  async function handleCheckDns() {
    setChecking(true);
    setError(null);

    try {
      const response = await fetch('/api/dealer/custom-domain/migrate');
      const data = await response.json();

      if (data.success) {
        setStatus(data.data);

        if (data.data.cnameConfigured) {
          // CNAME is good, proceed with migration
          setStep('migrating');
          await performMigration();
        } else {
          setError(
            'CNAME record not detected yet. DNS changes can take a few minutes to several hours to propagate. Please wait and try again.'
          );
        }
      } else {
        setError(data.error || 'Failed to check DNS');
      }
    } catch {
      setError('Failed to check DNS configuration');
    } finally {
      setChecking(false);
    }
  }

  async function performMigration() {
    try {
      const response = await fetch('/api/dealer/custom-domain/migrate', {
        method: 'POST',
      });

      const data = await response.json();

      if (data.success) {
        setStep('complete');
      } else {
        setError(data.error || 'Migration failed');
        setStep('instructions');
      }
    } catch {
      setError('Migration failed. Please try again.');
      setStep('instructions');
    }
  }

  const instructions =
    status?.currentMethod === 'managed'
      ? status.instructions?.managed
      : status?.instructions?.selfManaged;

  if (step === 'loading') {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-cyan-500"></div>
      </div>
    );
  }

  if (step === 'error' && !status) {
    return (
      <div className="p-6 bg-red-900/50 border border-red-500 rounded-lg">
        <h3 className="text-lg font-semibold text-red-300 mb-2">Error</h3>
        <p className="text-gray-300 mb-4">{error}</p>
        <Button variant="secondary" onClick={() => router.push('/dashboard/settings/domains')}>
          Back to Domain Settings
        </Button>
      </div>
    );
  }

  if (step === 'intro') {
    return (
      <div className="space-y-6">
        <div className="p-6 bg-slate-700/50 rounded-lg">
          <h2 className="text-xl font-semibold mb-4">Migrate Your Custom Domain</h2>

          <div className="mb-6">
            <h3 className="font-medium mb-2 text-cyan-400">What&apos;s changing?</h3>
            <p className="text-gray-300 mb-4">
              We&apos;ve upgraded our custom domain system to use a simpler, more reliable
              CNAME-based setup. Your current domain{' '}
              <span className="text-cyan-300 font-medium">{status?.domain}</span> uses the old{' '}
              {status?.currentMethod === 'managed' ? 'nameserver' : 'A record'} configuration.
            </p>
          </div>

          <div className="mb-6">
            <h3 className="font-medium mb-2 text-cyan-400">Benefits of migrating:</h3>
            <ul className="list-disc pl-6 text-gray-300 space-y-1">
              <li>Simpler DNS setup - just one CNAME record</li>
              <li>Automatic SSL certificate provisioning</li>
              <li>Better reliability and faster SSL renewals</li>
              <li>Consistent experience across all domains</li>
            </ul>
          </div>

          <div className="mb-6 p-4 bg-amber-900/30 border border-amber-700 rounded-lg">
            <h3 className="font-medium mb-2 text-amber-300">Before you start:</h3>
            <p className="text-sm text-gray-300">
              You&apos;ll need access to your domain registrar (where you purchased your domain) to
              update DNS settings. The migration process typically takes 5-10 minutes, but DNS
              propagation can take up to 48 hours.
            </p>
          </div>

          <div className="flex gap-4">
            <Button variant="primary" onClick={() => setStep('instructions')}>
              Start Migration
            </Button>
            <Button variant="secondary" onClick={() => router.push('/dashboard/settings/domains')}>
              Cancel
            </Button>
          </div>
        </div>
      </div>
    );
  }

  if (step === 'instructions') {
    return (
      <div className="space-y-6">
        <div className="p-6 bg-slate-700/50 rounded-lg">
          <h2 className="text-xl font-semibold mb-4">Step 1: Update Your DNS Settings</h2>

          {error && (
            <div className="mb-4 p-4 bg-red-900/50 border border-red-500 rounded-lg text-red-200">
              {error}
            </div>
          )}

          <div className="mb-6">
            <h3 className="font-medium mb-3 text-cyan-400">
              {status?.currentMethod === 'managed'
                ? 'Switch from Managed DNS to CNAME'
                : 'Switch from A Record to CNAME'}
            </h3>

            <ol className="list-decimal pl-6 space-y-3 text-gray-300">
              {instructions?.map((instruction, index) => (
                <li key={index}>{instruction}</li>
              ))}
            </ol>
          </div>

          {status?.cnameDomain && (
            <div className="mb-6 p-4 bg-slate-600 rounded-lg">
              <h4 className="font-medium mb-3">CNAME Record Details</h4>
              <div className="grid grid-cols-3 gap-2 text-xs mb-2 text-gray-400">
                <span>Type</span>
                <span>Name/Host</span>
                <span>Value/Target</span>
              </div>
              <div className="grid grid-cols-3 gap-2 items-center">
                <span className="text-cyan-300">CNAME</span>
                <span className="text-cyan-300">
                  {status.domain?.startsWith('www.') ? 'www' : '@'}
                </span>
                <div className="flex items-center gap-2">
                  <code className="text-cyan-300">{status.cnameDomain}</code>
                  <button
                    onClick={handleCopyCname}
                    className="px-2 py-1 text-xs bg-slate-500 hover:bg-slate-400 rounded transition-colors"
                  >
                    {copiedCname ? 'Copied!' : 'Copy'}
                  </button>
                </div>
              </div>
            </div>
          )}

          {status?.currentMethod === 'managed' && (
            <div className="mb-6 p-4 bg-blue-900/30 border border-blue-700 rounded-lg">
              <h4 className="font-medium mb-2 text-blue-300">
                Finding your registrar&apos;s default nameservers
              </h4>
              <p className="text-sm text-gray-300">
                When you remove our managed nameservers, you&apos;ll need to restore your
                registrar&apos;s defaults. Contact your registrar&apos;s support or check their help
                documentation for the correct nameservers to use.
              </p>
            </div>
          )}

          <div className="p-4 bg-amber-900/30 border border-amber-700 rounded-lg mb-6">
            <h4 className="font-medium mb-2 text-amber-300">Note about root domains</h4>
            <p className="text-sm text-gray-300">
              If you&apos;re using a root domain (e.g., example.com without www), some registrars
              don&apos;t support CNAME records at the root. In this case, you may need to use
              www.example.com instead, or check if your registrar supports ALIAS/ANAME records.
            </p>
          </div>

          <div className="flex gap-4">
            <Button variant="primary" onClick={handleCheckDns} disabled={checking}>
              {checking ? 'Checking DNS...' : "I've Updated My DNS - Check & Migrate"}
            </Button>
            <Button variant="secondary" onClick={() => setStep('intro')}>
              Back
            </Button>
          </div>
        </div>
      </div>
    );
  }

  if (step === 'migrating') {
    return (
      <div className="space-y-6">
        <div className="p-6 bg-slate-700/50 rounded-lg text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-cyan-500 mx-auto mb-4"></div>
          <h2 className="text-xl font-semibold mb-2">Migrating Your Domain</h2>
          <p className="text-gray-300">
            Please wait while we migrate your domain to certbot-managed certificates...
          </p>
        </div>
      </div>
    );
  }

  if (step === 'complete') {
    return (
      <div className="space-y-6">
        <div className="p-6 bg-green-900/30 border border-green-700 rounded-lg">
          <div className="text-center mb-6">
            <div className="w-16 h-16 bg-green-600 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg
                className="w-8 h-8 text-white"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M5 13l4 4L19 7"
                />
              </svg>
            </div>
            <h2 className="text-xl font-semibold text-green-300 mb-2">Migration Complete!</h2>
            <p className="text-gray-300">
              Your domain <span className="text-cyan-300 font-medium">{status?.domain}</span> has
              been successfully migrated to certbot-managed certificates.
            </p>
          </div>

          <div className="mb-6 p-4 bg-slate-700 rounded-lg">
            <h3 className="font-medium mb-2">What&apos;s next?</h3>
            <ul className="list-disc pl-6 text-gray-300 space-y-1">
              <li>SSL certificates are being automatically provisioned</li>
              <li>Your domain should be fully active within a few minutes</li>
              <li>No further action is required on your part</li>
            </ul>
          </div>

          <div className="text-center">
            <Button variant="primary" onClick={() => router.push('/dashboard/settings/domains')}>
              Return to Domain Settings
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return null;
}
