import React, { useState, useCallback, memo } from 'react';
import { useAuth } from '../../../auth/AuthProvider';
import { createDraft, generateAssets, getImages } from '../../../services/wizardApi';
import HelpIcon from '../../../components/HelpIcon';

const MAX_HEADLINE = 30;
const MAX_DESC = 90;

function AssetEditor({ items, maxLen, type, onUpdate }) {
  const [editIdx, setEditIdx] = useState(null);
  const [editText, setEditText] = useState('');

  const startEdit = (idx) => {
    setEditIdx(idx);
    setEditText(items[idx]?.text || '');
  };

  const saveEdit = () => {
    if (editIdx === null) return;
    const updated = [...items];
    updated[editIdx] = { ...updated[editIdx], text: editText, charCount: editText.length };
    onUpdate(updated);
    setEditIdx(null);
  };

  const removeItem = (idx) => {
    onUpdate(items.filter((_, i) => i !== idx));
  };

  const addItem = () => {
    onUpdate([...items, { text: '', charCount: 0 }]);
    setEditIdx(items.length);
    setEditText('');
  };

  return (
    <div className="asset-editor">
      {items.map((item, idx) => (
        <div key={idx} className={`asset-row ${editIdx === idx ? 'editing' : ''}`}>
          {editIdx === idx ? (
            <div className="asset-edit-row">
              <input
                className="form-input"
                value={editText}
                maxLength={maxLen}
                onChange={e => setEditText(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && saveEdit()}
                autoFocus
              />
              <span className={`char-counter ${editText.length > maxLen ? 'over' : ''}`}>
                {editText.length}/{maxLen}
              </span>
              <button className="btn btn-sm btn-primary" onClick={saveEdit}>Save</button>
              <button className="btn btn-sm btn-outline" onClick={() => setEditIdx(null)}>Cancel</button>
            </div>
          ) : (
            <>
              <span className="asset-text">{item.text || <em className="text-muted">Empty {type}</em>}</span>
              <span className="char-counter">{item.charCount || item.text?.length || 0}/{maxLen}</span>
              <button className="asset-action" onClick={() => startEdit(idx)} title="Edit">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" /><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" /></svg>
              </button>
              <button className="asset-action danger" onClick={() => removeItem(idx)} title="Remove">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12" /></svg>
              </button>
            </>
          )}
        </div>
      ))}
      <button className="btn btn-sm btn-outline add-asset-btn" onClick={addItem}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14" /></svg>
        Add {type}
      </button>
    </div>
  );
}

const CreativeStep = memo(function CreativeStep({ data, onChange, businessData }) {
  // ── Auth from context (no more prop) ──
  const { sessionToken } = useAuth();

  const [generating, setGenerating] = useState(false);
  const [genPhase, setGenPhase] = useState('');
  const [error, setError] = useState(null);

  const state = {
    headlines: [],
    descriptions: [],
    images: [],
    analysis: businessData?.analysis || null,
    source: null,
    imageSource: null,
    ...data
  };

  const update = useCallback((patch) => {
    onChange({ ...state, ...patch });
  }, [state, onChange]);

  // Auto-generate if we have a URL but no assets yet
  const hasAssets = state.headlines.length > 0 || state.images.length > 0;
  const url = businessData?.url;

  const handleGenerate = async () => {
    if (!url && !state.analysis) return;
    setGenerating(true);
    setError(null);

    try {
      if (url) {
        // Full pipeline: URL → draft with images
        setGenPhase('Analyzing website and generating creative…');
        const res = await createDraft(url, sessionToken);
        if (res.ok) {
          const draft = res.data?.result?.data || res.data?.data || res.data;
          update({
            headlines: draft?.headlines || [],
            descriptions: draft?.descriptions || [],
            images: draft?.images || [],
            analysis: draft?.analysis || state.analysis,
            source: draft?.source || 'generated',
            imageSource: draft?.imageSource || 'generated'
          });
        } else {
          setError(res.error || 'Failed to generate creative');
        }
      } else if (state.analysis) {
        // Generate from existing analysis
        setGenPhase('Generating ad copy…');
        const copyRes = await generateAssets(state.analysis, sessionToken);
        if (copyRes.ok) {
          const copyData = copyRes.data?.result?.data || copyRes.data?.data || copyRes.data;
          update({
            headlines: copyData?.headlines || [],
            descriptions: copyData?.descriptions || [],
          });
        }
        setGenPhase('Finding images…');
        const imgRes = await getImages(state.analysis, sessionToken);
        if (imgRes.ok) {
          const imgData = imgRes.data?.result?.data || imgRes.data?.data || imgRes.data;
          update({ images: imgData?.images || [] });
        }
      }
    } catch (e) {
      setError(e.message || 'Generation failed');
    }

    setGenPhase('');
    setGenerating(false);
  };

  return (
    <div className="wizard-step-content">
      <div className="step-intro">
        <div className="step-intro-header">
          <h2>Create your ad</h2>
          <HelpIcon helpKey="client.wizard.creative" label="About this step" />
        </div>
        <p>Generate headlines, descriptions, and images for your campaign — or write your own.</p>
      </div>

      {/* Generate Button - Enhanced */}
      {url && (
        <div className={`generate-bar ${hasAssets ? 'has-assets' : 'empty'}`}>
          <div className="generate-bar-content">
            <div className="generate-bar-icon">
              {generating ? (
                <span className="btn-spinner" style={{ width: 24, height: 24 }} />
              ) : hasAssets ? (
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 4v6h6M23 20v-6h-6" /><path d="M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15" /></svg>
              ) : (
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" /></svg>
              )}
            </div>
            <div className="generate-bar-text">
              <strong>{generating ? genPhase || 'Generating…' : hasAssets ? 'Regenerate creative' : 'Generate from your website'}</strong>
              {!generating && !hasAssets && (
                <span>AI will analyze your site and create ad copy + find matching images</span>
              )}
              {!generating && hasAssets && (
                <span>Create a fresh set of headlines, descriptions, and images</span>
              )}
            </div>
            <button
              className="btn btn-primary"
              onClick={handleGenerate}
              disabled={generating}
            >
              {generating ? 'Working…' : hasAssets ? 'Regenerate' : 'Generate'}
            </button>
          </div>
        </div>
      )}

      {error && <div className="error-box">{error}</div>}

      {/* Headlines */}
      <div className="creative-section">
        <div className="creative-section-header">
          <h3>Headlines</h3>
          <span className="asset-count">{state.headlines.length} / 15 max</span>
        </div>
        <p className="creative-section-hint">Short, punchy text shown at the top of your ad. Max {MAX_HEADLINE} characters each.</p>
        <AssetEditor
          items={state.headlines}
          maxLen={MAX_HEADLINE}
          type="headline"
          onUpdate={(h) => update({ headlines: h })}
        />
      </div>

      {/* Descriptions */}
      <div className="creative-section">
        <div className="creative-section-header">
          <h3>Descriptions</h3>
          <span className="asset-count">{state.descriptions.length} / 4 max</span>
        </div>
        <p className="creative-section-hint">Longer text that appears below the headline. Max {MAX_DESC} characters each.</p>
        <AssetEditor
          items={state.descriptions}
          maxLen={MAX_DESC}
          type="description"
          onUpdate={(d) => update({ descriptions: d })}
        />
      </div>

      {/* Images */}
      <div className="creative-section">
        <div className="creative-section-header">
          <h3>Images</h3>
          <span className="asset-count">{state.images.length} image{state.images.length !== 1 ? 's' : ''}</span>
        </div>
        {state.images.length > 0 ? (
          <div className="image-grid">
            {state.images.map((img, idx) => (
              <div key={img.imageId || idx} className="image-thumb">
                <img
                  src={img.url}
                  alt={img.altText || `Image ${idx + 1}`}
                  loading="lazy"
                  onError={e => { e.target.style.display = 'none'; }}
                />
                <div className="image-thumb-meta">
                  <span className="orientation-tag">{img.orientation}</span>
                  {img.width && <span className="dim-tag">{img.width}×{img.height}</span>}
                </div>
                <button
                  className="image-remove"
                  onClick={() => update({ images: state.images.filter((_, i) => i !== idx) })}
                  title="Remove image"
                >
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12" /></svg>
                </button>
              </div>
            ))}
          </div>
        ) : (
          <div className="empty-images">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="2" /><circle cx="8.5" cy="8.5" r="1.5" /><path d="M21 15l-5-5L5 21" /></svg>
            <span>{url ? 'Click "Generate" above to find images for your ad' : 'No images added yet'}</span>
          </div>
        )}
      </div>

      {/* Ad Preview */}
      {state.headlines.length > 0 && (
        <div className="creative-section">
          <div className="creative-section-header">
            <h3>Ad Preview</h3>
            <span className="asset-count" style={{ fontStyle: 'italic' }}>Approximate appearance</span>
          </div>
          <div className="ad-preview-card">
            <div className="ad-preview-label">Ad · {businessData?.url ? new URL(businessData.url).hostname : 'yoursite.com'}</div>
            <div className="ad-preview-headline">{state.headlines[0]?.text || 'Your Headline'}</div>
            <div className="ad-preview-desc">{state.descriptions[0]?.text || 'Your description will appear here.'}</div>
          </div>
        </div>
      )}
    </div>
  );
});

export default CreativeStep;
