import { ExternalLink } from 'lucide-react';

import { useState } from 'react';

import DownloadPluginButton from '@/Components/Connections/DownloadPluginButton';
import { trackEvent } from '@/lib/analytics';
import { WP_INSTALL_STARTED } from '@/lib/event-catalog';
import { cn } from '@/lib/utils';

interface PluginInstallHelperProps {
  siteId: string;
  /**
   * Optional WordPress URL — used to deep-link to the WP plugin installer
   * page so the user lands one click away from upload-and-activate.
   */
  domain?: string;
}

/**
 * Collapsible "Need to install the plugin first?" helper that lives below
 * the WP URL input. Closed by default; opening it fires `WP_INSTALL_STARTED`
 * so we can measure whether users actually hit the install path or just
 * skipped to entering an already-installed site URL.
 */
export function PluginInstallHelper({ siteId, domain }: PluginInstallHelperProps) {
  const [open, setOpen] = useState(false);
  const wpAdminUploadUrl = domain
    ? `${domain.replace(/\/$/, '')}/wp-admin/plugin-install.php?tab=upload`
    : null;

  const handleToggle = () => {
    const next = !open;
    setOpen(next);
    if (next) {
      trackEvent(WP_INSTALL_STARTED, { site_id: String(siteId) });
    }
  };

  return (
    <div className="mt-3 rounded-md border border-border/60 bg-muted/30">
      <button
        type="button"
        onClick={handleToggle}
        aria-expanded={open}
        aria-controls="plugin-install-steps"
        className="flex w-full items-center justify-between px-3 py-2 text-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-md transition-colors"
      >
        <span>Need to install the plugin first?</span>
        <span
          aria-hidden="true"
          className={cn(
            'text-xs transition-transform motion-reduce:transition-none duration-200',
            open ? 'rotate-180' : '',
          )}
        >
          ▾
        </span>
      </button>

      {open && (
        <div
          id="plugin-install-steps"
          className="border-t border-border/60 px-3 pb-3 pt-2 space-y-3 animate-in slide-in-from-top-1 fade-in-0 duration-150"
        >
          <ol className="space-y-1.5 text-sm text-muted-foreground list-decimal list-inside">
            <li>Download the plugin zip using the button below.</li>
            <li>
              {wpAdminUploadUrl ? (
                <>
                  <a
                    href={wpAdminUploadUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1 text-primary underline underline-offset-2 hover:text-primary/80"
                  >
                    Open WP Plugin Installer
                    <ExternalLink className="size-3" aria-hidden="true" />
                  </a>{' '}
                  (or go to Plugins → Add New → Upload Plugin).
                </>
              ) : (
                'In your WordPress admin, go to Plugins → Add New → Upload Plugin.'
              )}
            </li>
            <li>Choose the downloaded zip file and click Install Now.</li>
            <li>Activate the plugin.</li>
            {/* 2026-05-28: was "Return here and enter your WordPress URL to
                connect" — stale instruction from when there was a URL input
                field (dropped 2026-05-16). The current flow shows a setup
                key to paste into the plugin instead. */}
            <li>Return here and click <span className="font-medium">Show setup key</span> to get the key to paste into the plugin.</li>
          </ol>
          <DownloadPluginButton size="md" label="Download plugin" />
        </div>
      )}
    </div>
  );
}
