'use client';

import { useState, type ReactNode } from 'react';
import { BookOpen, ChevronDown, Download, ExternalLink, FlaskConical, Globe, Copy } from 'lucide-react';
import toast from 'react-hot-toast';
import { guideToMarkdown, type GatewayGuide, type GuideMode } from '@/lib/payments/setupGuides';

// **bold** and `code` inside guide text.
function renderInline(text: string): ReactNode[] {
  return text.split(/(\*\*[^*]+\*\*|`[^`]+`)/g).map((part, i) => {
    if (part.startsWith('**') && part.endsWith('**')) {
      return (
        <strong key={i} style={{ color: 'var(--color-text)' }}>
          {part.slice(2, -2)}
        </strong>
      );
    }
    if (part.startsWith('`') && part.endsWith('`')) {
      return (
        <code key={i} className="px-1 py-0.5 rounded break-all" style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)' }}>
          {part.slice(1, -1)}
        </code>
      );
    }
    return part;
  });
}

interface PaymentSetupGuideProps {
  guide: GatewayGuide;
  siteName: string;
}

// Collapsible step-by-step setup guide (testing + live) for one gateway,
// with a button to download the same content as a Markdown file.
export function PaymentSetupGuide({ guide, siteName }: PaymentSetupGuideProps) {
  const [open, setOpen] = useState(false);
  const [mode, setMode] = useState<GuideMode>('test');
  const section = guide.sections.find((s) => s.mode === mode) ?? guide.sections[0];

  const download = () => {
    const blob = new Blob([guideToMarkdown(guide, siteName)], { type: 'text/markdown;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${guide.id}-setup-guide.md`;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(url);
  };

  const copy = async (command: string) => {
    try {
      await navigator.clipboard.writeText(command);
      toast.success('Command copied');
    } catch {
      toast.error('Could not copy — select the text instead');
    }
  };

  return (
    <div className="mt-4 rounded-lg" style={{ border: '1px solid var(--color-border)', background: 'var(--color-surface-alt)' }}>
      <div className="flex flex-wrap items-center justify-between gap-2 p-3">
        <button
          type="button"
          onClick={() => setOpen((o) => !o)}
          className="flex items-center gap-2 text-sm font-medium cursor-pointer"
          style={{ color: 'var(--color-text)' }}
          aria-expanded={open}
        >
          <BookOpen size={16} style={{ color: 'var(--color-cta)' }} />
          {guide.name} setup guide — testing &amp; live
          <ChevronDown size={16} className={`transition-transform ${open ? 'rotate-180' : ''}`} />
        </button>
        <button
          type="button"
          onClick={download}
          className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer"
          style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', color: 'var(--color-text)' }}
        >
          <Download size={14} /> Download guide (.md)
        </button>
      </div>

      {open && (
        <div className="px-3 pb-4">
          <div className="flex gap-2 mb-3" role="tablist">
            {guide.sections.map((s) => (
              <button
                key={s.mode}
                type="button"
                role="tab"
                aria-selected={mode === s.mode}
                onClick={() => setMode(s.mode)}
                className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer"
                style={
                  mode === s.mode
                    ? { background: 'var(--color-cta)', color: 'white' }
                    : { background: 'var(--color-surface)', border: '1px solid var(--color-border)', color: 'var(--color-text-secondary)' }
                }
              >
                {s.mode === 'test' ? <FlaskConical size={14} /> : <Globe size={14} />}
                {s.mode === 'test' ? 'Testing (Sandbox / local)' : 'Live (real payments)'}
              </button>
            ))}
          </div>

          <h4 className="text-sm font-medium" style={{ color: 'var(--color-text)' }}>{section.heading}</h4>
          {section.intro && (
            <p className="text-xs mt-1 mb-3" style={{ color: 'var(--color-text-tertiary)' }}>{section.intro}</p>
          )}

          <ol className="space-y-3">
            {section.steps.map((step, i) => (
              <li key={step.title} className="flex gap-3">
                <span
                  className="shrink-0 w-6 h-6 rounded-full flex items-center justify-center text-xs font-semibold"
                  style={{ background: 'var(--color-cta)', color: 'white' }}
                >
                  {i + 1}
                </span>
                <div className="min-w-0 flex-1">
                  <p className="text-sm font-medium" style={{ color: 'var(--color-text)' }}>{step.title}</p>
                  {step.details && (
                    <ul className="mt-1 space-y-1 text-xs list-disc pl-4" style={{ color: 'var(--color-text-secondary)' }}>
                      {step.details.map((d) => (
                        <li key={d}>{renderInline(d)}</li>
                      ))}
                    </ul>
                  )}
                  {step.command && (
                    <div
                      className="mt-2 flex items-start gap-2 p-2 rounded text-xs font-mono"
                      style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', color: 'var(--color-text)' }}
                    >
                      <code className="flex-1 break-all">{step.command}</code>
                      <button type="button" onClick={() => copy(step.command!)} className="cursor-pointer shrink-0" aria-label="Copy command">
                        <Copy size={14} />
                      </button>
                    </div>
                  )}
                  {step.links && (
                    <div className="mt-2 flex flex-wrap gap-2">
                      {step.links.map((l) => (
                        <a
                          key={l.url}
                          href={l.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center gap-1 text-xs font-medium underline-offset-2 hover:underline"
                          style={{ color: 'var(--color-cta)' }}
                        >
                          {l.label} <ExternalLink size={12} />
                        </a>
                      ))}
                    </div>
                  )}
                </div>
              </li>
            ))}
          </ol>

          {guide.notes.length > 0 && (
            <ul className="mt-4 space-y-1 text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
              {guide.notes.map((n) => (
                <li key={n}>• {n}</li>
              ))}
            </ul>
          )}
        </div>
      )}
    </div>
  );
}
