import React, { useState, useCallback, useEffect, useRef } from 'react';
import { useAuth } from '../../auth/AuthProvider';
import WizardConfigProvider from '../../context/WizardConfigContext';
import ObjectiveStep from './steps/ObjectiveStep';
import AudienceStep from './steps/AudienceStep';
import BudgetStep from './steps/BudgetStep';
import ChannelAllocationStep from './steps/ChannelAllocationStep';
import CreativeStep from './steps/CreativeStep';
import ReviewStep from './steps/ReviewStep';
import { createWizard, getWizard, updateStep } from '../../services/wizardApi';

// ═══════════════════════════════════════════════════════════════
// Step order: Objective → Audience → Budget → Channels → Creative → Review
//
// Why budget before channels:
//   Budget constrains which channels are viable. Knowing the budget
//   first lets us disable unaffordable channels, call the forecasting
//   APIs with all inputs (objective + audience + budget) to give
//   data-driven channel recommendations, and surface budget tier
//   guidance (e.g. "your budget supports 1-2 channels").
// ═══════════════════════════════════════════════════════════════

const STEPS = [
  { num: 1, key: 'objective',  label: 'Objective',  icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' },
  { num: 2, key: 'audience',   label: 'Audience',   icon: 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z' },
  { num: 3, key: 'budget',     label: 'Budget',     icon: 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z' },
  { num: 4, key: 'channels',   label: 'Channels',   icon: 'M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.14 0M1.394 9.393c5.857-5.858 15.355-5.858 21.213 0' },
  { num: 5, key: 'creative',   label: 'Creative',   icon: 'M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z' },
  { num: 6, key: 'review',     label: 'Review',     icon: 'M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z' },
];

const LAST_DATA_STEP = 5;

export default function CampaignWizard({ onClose, wizardId: initialWizardId }) {
  const { sessionToken } = useAuth();

  const [currentStep, setCurrentStep] = useState(1);
  const [wizardId, setWizardId] = useState(initialWizardId || null);
  const [visitedSteps, setVisitedSteps] = useState(new Set([1]));
  const [stepData, setStepData] = useState({
    1: {},  // Objective: campaignName, url, objective, businessCategory, analysis
    2: {},  // Audience:  locations[], demographics{}, ageSkew, marketScope
    3: {},  // Budget:    totalBudget, budgetPeriod, startDate, endDate, hasEndDate
    4: {},  // Channels:  selectedChannels[], allocations{}, allocationStrategy
    5: {},  // Creative:  headlines[], descriptions[], images[]
  });
  const saveTimer = useRef(null);
  const wizardIdRef = useRef(wizardId);
  wizardIdRef.current = wizardId;

  // ── Load existing draft ──
  useEffect(() => {
    if (!initialWizardId || !sessionToken) return;
    (async () => {
      const res = await getWizard(initialWizardId, sessionToken);
      if (res.ok && res.data) {
        const wiz = res.data.data || res.data;
        const restored = { 1: {}, 2: {}, 3: {}, 4: {}, 5: {} };
        if (wiz.wizStepData || wiz.stepData) {
          const saved = typeof (wiz.wizStepData || wiz.stepData) === 'string'
            ? JSON.parse(wiz.wizStepData || wiz.stepData)
            : (wiz.wizStepData || wiz.stepData);
          Object.assign(restored, saved);
        }
        if (wiz.wizName || wiz.name) {
          restored[1] = { ...restored[1], campaignName: wiz.wizName || wiz.name };
        }
        if (wiz.wizUrl || wiz.url) {
          restored[1] = { ...restored[1], url: wiz.wizUrl || wiz.url };
        }
        setStepData(restored);
        const resumeStep = parseInt(wiz.wizCurrentStep || wiz.currentStep) || 1;
        setCurrentStep(Math.min(Math.max(resumeStep, 1), STEPS.length));
      }
    })();
  }, [initialWizardId, sessionToken]);

  // ── Auto-save: debounced ──
  const saveToBackend = useCallback(async (step, data, allData) => {
    if (!sessionToken) return;
    try {
      let id = wizardIdRef.current;
      if (!id) {
        const name = allData[1]?.campaignName || 'Untitled Campaign';
        const url = allData[1]?.url || '';
        const createRes = await createWizard(name, url, sessionToken);
        if (createRes.ok) {
          id = createRes.data?.data?.wizardId || createRes.data?.wizardId || createRes.data?.id;
          if (id) { setWizardId(id); wizardIdRef.current = id; }
        }
      }
      if (id) {
        await updateStep(id, step, allData, sessionToken, allData[1]?.campaignName);
      }
    } catch (e) { console.warn('Auto-save failed:', e); }
  }, [sessionToken]);

  const handleStepDataChange = useCallback((step, data) => {
    setStepData(prev => {
      const next = { ...prev, [step]: data };
      if (saveTimer.current) clearTimeout(saveTimer.current);
      saveTimer.current = setTimeout(() => saveToBackend(step, data, next), 1500);
      return next;
    });
  }, [saveToBackend]);

  // Step validation
  const stepComplete = (num) => {
    const d = stepData[num];
    switch (num) {
      case 1: return !!(d?.campaignName && d?.objective);
      case 2: return visitedSteps.has(2) && visitedSteps.has(3);
      case 3: return !!(d?.totalBudget && parseFloat(d.totalBudget) > 0);
      case 4: {
        const hasChannels = (d?.selectedChannels?.length || 0) > 0;
        if (!hasChannels) return false;
        if (d.selectedChannels.length > 1) {
          const totalPct = Object.values(d?.allocations || {}).reduce((s, v) => s + (v || 0), 0);
          return Math.abs(totalPct - 100) < 0.01;
        }
        return true;
      }
      case 5: return !!(d?.headlines?.length > 0 || d?.descriptions?.length > 0);
      default: return false;
    }
  };

  const goToStep = (targetStep) => {
    setVisitedSteps(prev => new Set([...prev, targetStep]));
    setCurrentStep(targetStep);
    if (wizardIdRef.current && sessionToken && targetStep <= LAST_DATA_STEP) {
      updateStep(wizardIdRef.current, targetStep, stepData, sessionToken, stepData[1]?.campaignName).catch(() => {});
    }
  };

  const handleNext = () => goToStep(Math.min(currentStep + 1, STEPS.length));
  const handleBack = () => goToStep(Math.max(currentStep - 1, 1));

  const campaignName = stepData[1]?.campaignName || 'New Campaign';
  const selectedChannelCount = stepData[4]?.selectedChannels?.length || 0;

  return (
    <WizardConfigProvider>
      <div className="wizard-wrapper">
        {/* Header */}
        <div className="wizard-header">
          <div className="wizard-header-left">
            <button className="wizard-back-btn" onClick={onClose} title="Exit wizard">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M18 6L6 18M6 6l12 12" />
              </svg>
            </button>
            <div>
              <h2 className="wizard-title">{campaignName}</h2>
              <span className="wizard-subtitle">
                {selectedChannelCount > 1
                  ? `Multi-channel Campaign · ${selectedChannelCount} channels`
                  : 'Campaign Wizard'}
              </span>
            </div>
          </div>
          <div className="wizard-header-right">
            <span className="status-badge status-active">draft</span>
          </div>
        </div>

        {/* Step Navigation Rail */}
        <div className="wizard-rail">
          {STEPS.map(step => {
            const isActive = currentStep === step.num;
            const isComplete = step.num < STEPS.length && stepComplete(step.num);
            const isPast = step.num < currentStep;
            return (
              <button
                key={step.num}
                className={`wizard-rail-step ${isActive ? 'active' : ''} ${isComplete ? 'complete' : ''} ${isPast ? 'past' : ''}`}
                onClick={() => goToStep(step.num)}
              >
                <div className="rail-step-indicator">
                  {isComplete ? (
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M20 6L9 17l-5-5" /></svg>
                  ) : (
                    <span>{step.num}</span>
                  )}
                </div>
                <span className="rail-step-label">{step.label}</span>
              </button>
            );
          })}
          <div className="wizard-rail-progress" style={{ width: `${((currentStep - 1) / (STEPS.length - 1)) * 100}%` }} />
        </div>

        {/* Step Content */}
        <div className="wizard-body">
          {currentStep === 1 && <ObjectiveStep data={stepData[1]} onChange={(d) => handleStepDataChange(1, d)} />}
          {currentStep === 2 && <AudienceStep data={stepData[2]} onChange={(d) => handleStepDataChange(2, d)} />}
          {currentStep === 3 && <BudgetStep data={stepData[3]} onChange={(d) => handleStepDataChange(3, d)} />}
          {currentStep === 4 && (
            <ChannelAllocationStep
              data={stepData[4]}
              onChange={(d) => handleStepDataChange(4, d)}
              objectiveData={stepData[1]}
              audienceData={stepData[2]}
              budgetData={stepData[3]}
            />
          )}
          {currentStep === 5 && <CreativeStep data={stepData[5]} onChange={(d) => handleStepDataChange(5, d)} businessData={stepData[1]} />}
          {currentStep === 6 && <ReviewStep stepData={stepData} onGoToStep={goToStep} />}
        </div>

        {/* Footer Navigation */}
        {currentStep < STEPS.length && (
          <div className="wizard-footer">
            <button className="btn btn-outline" onClick={handleBack} disabled={currentStep === 1}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M12 19l-7-7 7-7" /></svg>
              Back
            </button>
            <div className="wizard-footer-center">Step {currentStep} of {STEPS.length}</div>
            <button
              className="btn btn-primary"
              onClick={handleNext}
              disabled={currentStep === 4 && selectedChannelCount === 0}
            >
              {currentStep === 5 ? 'Review Campaign' : 'Continue'}
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M12 5l7 7-7 7" /></svg>
            </button>
          </div>
        )}
      </div>
    </WizardConfigProvider>
  );
}
