import React, { useState, useCallback, memo } from 'react';
import { useAuth } from '../../../auth/AuthProvider';
import { useWizardConfig } from '../../../context/WizardConfigContext';
import { analyzeUrl } from '../../../services/wizardApi';
import HelpIcon from '../../../components/HelpIcon';

// ── Component (memoized — only re-renders when data/onChange actually change) ──
const ObjectiveStep = memo(function ObjectiveStep({ data, onChange }) {
  // ── Pull auth + config from context (no more prop-drilling) ──
  const { sessionToken } = useAuth();
  const {
    categories, objectives, loading,
    toDisplayLabel, objectiveDescriptions, objectiveIcons
  } = useWizardConfig();

  const [analyzing, setAnalyzing] = useState(false);
  const [error, setError] = useState(null);

  const state = {
    url: '',
    campaignName: '',
    objective: '',
    businessCategory: '',
    analysis: null,
    ...data
  };

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

  // Auto-default category to 'general' when categories load
  React.useEffect(() => {
    if (!loading && categories.length > 0 && !state.businessCategory) {
      const general = categories.find(c => c.name.toLowerCase() === 'general');
      if (general) {
        update({ businessCategory: general.name });
      }
    }
  }, [loading, categories.length]);

  const handleAnalyze = async () => {
    if (!state.url) return;
    setAnalyzing(true);
    setError(null);

    const res = await analyzeUrl(state.url, sessionToken);
    if (res.ok) {
      const analysis = res.data?.result?.data || res.data?.data || res.data;
      const suggestedName = analysis?.title
        ? `${analysis.title.slice(0, 40)} Campaign`
        : state.campaignName;

      // Try to auto-detect category from analysis
      const inferredCat = mapCategoryFromAnalysis(analysis?.inferredCategory, categories);

      update({
        analysis,
        campaignName: state.campaignName || suggestedName,
        businessCategory: state.businessCategory || inferredCat
      });
    } else {
      setError(res.error || 'Failed to analyze URL');
    }
    setAnalyzing(false);
  };

  return (
    <div className="wizard-step-content">
      <div className="step-intro">
        <div className="step-intro-header">
          <h2>What's your advertising goal?</h2>
          <HelpIcon helpKey="client.wizard.objective" label="About this step" />
        </div>
        <p>Tell us about your business and what you want to achieve. We'll help you reach the right audience across multiple channels.</p>
      </div>

      {/* URL Input */}
      <div className="form-group">
        <label>Website URL</label>
        <div className="url-input-row">
          <input
            className="form-input"
            type="url"
            placeholder="https://yourwebsite.com"
            value={state.url}
            onChange={e => update({ url: e.target.value })}
          />
          <button
            className="btn btn-primary"
            onClick={handleAnalyze}
            disabled={analyzing || !state.url}
          >
            {analyzing
              ? <><span className="btn-spinner" /> Analyzing…</>
              : state.analysis ? 'Re-analyze' : 'Analyze'}
          </button>
        </div>
        {error && <div className="field-error">{error}</div>}
      </div>

      {/* Analysis Results */}
      {state.analysis && (
        <div className="analysis-card">
          <div className="analysis-card-header">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
            <span>Site analyzed successfully</span>
          </div>
          <div className="analysis-card-body">
            <div className="analysis-detail">
              <span className="analysis-label">Title</span>
              <span className="analysis-value">{state.analysis.title || '—'}</span>
            </div>
            {state.analysis.metaDescription && (
              <div className="analysis-detail">
                <span className="analysis-label">Description</span>
                <span className="analysis-value">{state.analysis.metaDescription}</span>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Campaign Name */}
      <div className="form-group">
        <label>Campaign Name</label>
        <input
          className="form-input"
          type="text"
          placeholder="e.g. Summer Sale 2025"
          value={state.campaignName}
          onChange={e => update({ campaignName: e.target.value })}
        />
        <span className="field-hint">A name to identify this initiative in your dashboard</span>
      </div>

      {/* Business Category */}
      <div className="form-group">
        <label>Business Category</label>
        <span className="field-hint" style={{ marginBottom: 8, display: 'block' }}>
          This helps us recommend the best channel mix and budget allocation for your industry.
        </span>
        {loading ? (
          <div className="skeleton" style={{ height: 48, borderRadius: 8 }} />
        ) : (
          <select
            className="form-select form-select-lg"
            value={state.businessCategory}
            onChange={e => update({ businessCategory: e.target.value })}
          >
            <option value="">Select your industry…</option>
            {categories.map(cat => (
              <option key={cat.categoryId || cat.name} value={cat.name}>
                {cat.icon || '📦'} {toDisplayLabel(cat.name)}
              </option>
            ))}
          </select>
        )}
      </div>

      {/* Objective */}
      <div className="form-group">
        <label>Advertising Objective</label>
        {loading ? (
          <div className="loading-placeholder">
            <div className="objective-grid">
              {[1, 2, 3, 4, 5].map(i => (
                <div key={i} className="skeleton" style={{ height: 80, borderRadius: 10 }} />
              ))}
            </div>
          </div>
        ) : (
          <div className="objective-grid">
            {objectives.map(obj => (
              <button
                key={obj.objectiveId || obj.name}
                className={`objective-card ${state.objective === obj.name ? 'selected' : ''}`}
                onClick={() => update({ objective: obj.name })}
                style={obj.color ? { '--objective-accent': obj.color } : undefined}
              >
                <span className="objective-icon">{objectiveIcons[obj.name] || '🎯'}</span>
                <span className="objective-label">{toDisplayLabel(obj.name)}</span>
                {objectiveDescriptions[obj.name] && (
                  <span className="objective-desc">{objectiveDescriptions[obj.name]}</span>
                )}
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
});

export default ObjectiveStep;


/**
 * Map an inferred category string from URL analysis to the closest
 * category name in the loaded list. Falls back to '' if no match.
 */
function mapCategoryFromAnalysis(inferredCategory, loadedCategories) {
  if (!inferredCategory || !loadedCategories?.length) return '';
  const lower = inferredCategory.toLowerCase();

  const patterns = [
    { regex: /restaurant|food|dining|cafe|bar|bakery|pizza/i, match: 'restaurant' },
    { regex: /retail|shop|store|ecommerce|fashion|boutique/i, match: 'retail' },
    { regex: /b2b|saas|consult|agency|enterprise|software/i, match: 'b2b services' },
    { regex: /plumb|electric|clean|landscap|repair|local|hvac/i, match: 'local services' },
    { regex: /health|medical|dental|fitness|wellness|gym|therapy/i, match: 'health' },
  ];

  for (const { regex, match } of patterns) {
    if (regex.test(lower)) {
      const found = loadedCategories.find(c =>
        c.name.toLowerCase().includes(match)
      );
      if (found) return found.name;
    }
  }

  const direct = loadedCategories.find(c =>
    c.name.toLowerCase() === lower ||
    lower.includes(c.name.toLowerCase())
  );
  if (direct) return direct.name;

  const general = loadedCategories.find(c =>
    c.name.toLowerCase() === 'general'
  );
  return general ? general.name : '';
}
