import React, { useCallback, memo } from 'react';
import HelpIcon from '../../../components/HelpIcon';

const today = () => new Date().toISOString().split('T')[0];
const inDays = (n) => {
  const d = new Date();
  d.setDate(d.getDate() + n);
  return d.toISOString().split('T')[0];
};

const BudgetStep = memo(function BudgetStep({ data, onChange }) {

  const state = {
    totalBudget: '',
    budgetPeriod: 'monthly',
    startDate: today(),
    endDate: inDays(30),
    hasEndDate: true,
    ...data
  };

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

  const totalBudget = parseFloat(state.totalBudget) || 0;
  const dailyBudget = state.budgetPeriod === 'daily' ? totalBudget : totalBudget / 30;
  const days = state.hasEndDate && state.startDate && state.endDate
    ? Math.max(1, Math.ceil((new Date(state.endDate) - new Date(state.startDate)) / 86400000))
    : 30;

  const presetBudgets = state.budgetPeriod === 'daily'
    ? [25, 50, 100, 250]
    : [500, 1000, 2500, 5000];

  // Budget tier description
  const getBudgetTier = () => {
    const monthly = state.budgetPeriod === 'daily' ? totalBudget * 30 : totalBudget;
    if (monthly <= 0) return null;
    if (monthly < 500) return { label: 'Starter', desc: 'Best suited for a single channel', color: '#94A3B8', channels: 1 };
    if (monthly < 1500) return { label: 'Growth', desc: 'Enough for 1–2 channels', color: '#3B82F6', channels: 2 };
    if (monthly < 3000) return { label: 'Accelerate', desc: 'Supports 2–3 channels effectively', color: '#8B5CF6', channels: 3 };
    return { label: 'Scale', desc: 'Full multi-channel coverage', color: '#10B981', channels: 3 };
  };

  const tier = getBudgetTier();

  return (
    <div className="wizard-step-content">
      <div className="step-intro">
        <div className="step-intro-header">
          <h2>What's your advertising budget?</h2>
          <HelpIcon helpKey="client.wizard.budget" label="About this step" />
        </div>
        <p>
          Set your total budget and schedule. We'll use this to recommend the best
          channel mix and show you estimated performance in the next step.
        </p>
      </div>

      {/* Budget Period Toggle */}
      <div className="form-group">
        <label>Budget Period</label>
        <div className="period-toggle">
          <button
            className={`toggle-btn ${state.budgetPeriod === 'monthly' ? 'active' : ''}`}
            onClick={() => update({ budgetPeriod: 'monthly' })}
          >Monthly</button>
          <button
            className={`toggle-btn ${state.budgetPeriod === 'daily' ? 'active' : ''}`}
            onClick={() => update({ budgetPeriod: 'daily' })}
          >Daily</button>
        </div>
      </div>

      {/* Budget Input */}
      <div className="form-group">
        <label>Budget Amount</label>
        <div className="budget-input-row">
          <span className="budget-prefix">$</span>
          <input
            className="form-input budget-input"
            type="number"
            min="1"
            step="1"
            placeholder={state.budgetPeriod === 'daily' ? '50' : '1500'}
            value={state.totalBudget}
            onChange={e => update({ totalBudget: e.target.value })}
          />
          <span className="budget-suffix">/ {state.budgetPeriod === 'daily' ? 'day' : 'month'}</span>
        </div>
        <div className="budget-presets">
          {presetBudgets.map(amt => (
            <button
              key={amt}
              className={`preset-chip ${parseFloat(state.totalBudget) === amt ? 'active' : ''}`}
              onClick={() => update({ totalBudget: String(amt) })}
            >
              ${amt.toLocaleString()}
            </button>
          ))}
        </div>
      </div>

      {/* Estimated spend summary */}
      {totalBudget > 0 && (
        <div className="estimate-banner">
          <div className="estimate-row">
            <span>
              {state.budgetPeriod === 'daily'
                ? `~$${(totalBudget * 30).toLocaleString()} / month`
                : `~$${dailyBudget.toFixed(2)} / day`}
            </span>
            {state.hasEndDate && (
              <strong>
                ${(dailyBudget * days).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} estimated total ({days} days)
              </strong>
            )}
          </div>
        </div>
      )}

      {/* Budget tier indicator */}
      {tier && (
        <div className="budget-tier-card" style={{ '--tier-color': tier.color }}>
          <div className="budget-tier-header">
            <span className="budget-tier-label" style={{ color: tier.color }}>{tier.label}</span>
            <span className="budget-tier-channels">
              {tier.channels === 1 ? '1 channel recommended' : `Up to ${tier.channels} channels`}
            </span>
          </div>
          <div className="budget-tier-desc">{tier.desc}</div>
          <div className="budget-tier-bar">
            {['Starter', 'Growth', 'Accelerate', 'Scale'].map((t, i) => (
              <div
                key={t}
                className={`tier-segment ${t === tier.label ? 'active' : ''}`}
                style={t === tier.label ? { background: tier.color } : undefined}
              />
            ))}
          </div>
        </div>
      )}

      {/* Date Range / Schedule */}
      <div className="form-group">
        <label>Schedule</label>
        <div className="form-row">
          <div className="form-group" style={{ marginBottom: 0 }}>
            <label className="field-sub-label">Start Date</label>
            <input
              className="form-input"
              type="date"
              value={state.startDate}
              min={today()}
              onChange={e => update({ startDate: e.target.value })}
            />
          </div>
          <div className="form-group" style={{ marginBottom: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <label className="field-sub-label">End Date</label>
              <label className="toggle-label">
                <input
                  type="checkbox"
                  checked={state.hasEndDate}
                  onChange={e => update({ hasEndDate: e.target.checked })}
                />
                <span className="toggle-text">{state.hasEndDate ? 'Set' : 'No end date'}</span>
              </label>
            </div>
            <input
              className="form-input"
              type="date"
              value={state.endDate}
              min={state.startDate || today()}
              disabled={!state.hasEndDate}
              onChange={e => update({ endDate: e.target.value })}
            />
          </div>
        </div>
      </div>
    </div>
  );
});

export default BudgetStep;
