import { useState, useEffect, useRef } from 'react';
import UpdateProductModal from './UpdateProductModal';
import CreateProductWizard from './CreateProductWizard';

const fmt = (n) => `$${(n || 0).toFixed(2)}`;
const fmtPct = (n) => `${(n || 0).toFixed(1)}%`;

const BREAKDOWN_ITEMS = [
  { key: 'materialCost', label: 'Material', emoji: '🧵', color: '#7c3aed' },
  { key: 'powerCost', label: 'Power', emoji: '⚡', color: '#a855f7' },
  { key: 'packagingTotal', label: 'Packaging', emoji: '📦', color: '#c084fc' },
  { key: 'fixedOverhead', label: 'Fixed Overhead', emoji: '🏭', color: '#e879f9' },
  { key: 'amortization', label: 'Machine Wear', emoji: '🔧', color: '#f0abfc' },
  { key: 'failureBuffer', label: 'Failure Buffer', emoji: '⚠️', color: '#fb7185' },
];

function AnimatedNumber({ value, prefix = '$', decimals = 2 }) {
  const [displayed, setDisplayed] = useState(value);
  const rafRef = useRef();
  const startRef = useRef({ from: value, to: value, t: 0 });

  useEffect(() => {
    const from = displayed;
    const to = value;
    const duration = 400;
    const start = performance.now();
    const animate = (now) => {
      const elapsed = now - start;
      const progress = Math.min(elapsed / duration, 1);
      const ease = 1 - Math.pow(1 - progress, 3);
      setDisplayed(from + (to - from) * ease);
      if (progress < 1) rafRef.current = requestAnimationFrame(animate);
    };
    rafRef.current = requestAnimationFrame(animate);
    return () => cancelAnimationFrame(rafRef.current);
  }, [value]);

  return <span>{prefix}{displayed.toFixed(decimals)}</span>;
}

function BreakdownBar({ results }) {
  const total = results.totalCost || 1;
  return (
    <div className="space-y-2.5">
      {BREAKDOWN_ITEMS.map(({ key, label, emoji, color }) => {
        const val = results[key] || 0;
        const pct = Math.max(0, Math.min(100, (val / total) * 100));
        return (
          <div key={key}>
            <div className="flex items-center justify-between mb-1">
              <span className="text-xs" style={{ color: 'rgba(200,180,255,0.7)' }}>{emoji} {label}</span>
              <span className="text-xs font-mono font-semibold text-white">{fmt(val)}</span>
            </div>
            <div className="h-1.5 rounded-full overflow-hidden" style={{ background: 'rgba(255,255,255,0.05)' }}>
              <div
                className="h-full rounded-full transition-all duration-500 ease-out"
                style={{ width: `${pct}%`, background: color, boxShadow: `0 0 6px ${color}` }}
              />
            </div>
          </div>
        );
      })}
    </div>
  );
}

function PriceCard({ title, price, grossProfit, liquidProfit, margin, accent, dim }) {
  return (
    <div className="rounded-xl p-4 flex-1" style={{
      background: dim ? '#131325' : 'linear-gradient(135deg, #2e1065 0%, #1a0a2e 100%)',
      border: `1px solid ${accent}55`,
      boxShadow: `0 0 24px ${accent}22`,
    }}>
      <p className="text-xs font-bold uppercase tracking-widest mb-3" style={{ color: accent }}>{title}</p>
      <p className="text-2xl font-black text-white mb-3">
        <AnimatedNumber value={price} />
      </p>
      <div className="space-y-1.5 text-xs">
        <div className="flex justify-between">
          <span style={{ color: 'rgba(200,180,255,0.6)' }}>Gross Profit</span>
          <span className={`font-semibold ${grossProfit >= 0 ? 'text-green-400' : 'text-red-400'}`}>{fmt(grossProfit)}</span>
        </div>
        <div className="flex justify-between">
          <span style={{ color: 'rgba(200,180,255,0.6)' }}>Liquid Profit</span>
          <span className={`font-semibold ${liquidProfit >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>{fmt(liquidProfit)}</span>
        </div>
        <div className="flex justify-between">
          <span style={{ color: 'rgba(200,180,255,0.6)' }}>Margin</span>
          <span className="font-semibold text-purple-300">{fmtPct(margin)}</span>
        </div>
      </div>
    </div>
  );
}

export default function ResultsPanel({ results, data, onSave }) {
  const [showUpdateModal, setShowUpdateModal] = useState(false);
  const [showCreateWizard, setShowCreateWizard] = useState(false);

  const cardStyle = {
    background: '#1a1a2e',
    border: '1px solid rgba(107,47,179,0.4)',
    boxShadow: '0 0 20px rgba(107,47,179,0.15)',
  };

  return (
    <div className="space-y-4 xl:sticky xl:top-4 xl:max-h-[calc(100vh-6rem)] xl:overflow-y-auto">
      {/* Hero total */}
      <div className="rounded-2xl p-6 text-center" style={{
        background: 'linear-gradient(135deg, #1e0a3c 0%, #0d0d1a 100%)',
        border: '1px solid rgba(124,58,237,0.6)',
        boxShadow: '0 0 40px rgba(124,58,237,0.25), inset 0 0 40px rgba(124,58,237,0.05)',
      }}>
        <p className="text-xs font-bold uppercase tracking-[0.3em] mb-2" style={{ color: 'rgba(200,180,255,0.6)' }}>
          Total Unit Cost
        </p>
        <p className="text-5xl font-black mb-1" style={{
          color: '#c084fc',
          textShadow: '0 0 30px rgba(192,132,252,0.6)',
        }}>
          <AnimatedNumber value={results.unitCost} />
        </p>
        <p className="text-xs" style={{ color: 'rgba(200,180,255,0.4)' }}>
          per unit · total job: {fmt(results.totalCost)}
        </p>
      </div>

      {/* Breakdown */}
      <div className="rounded-2xl p-5" style={cardStyle}>
        <div className="flex items-center gap-2 mb-4">
          <div className="w-1 h-5 rounded-full" style={{ background: 'linear-gradient(to bottom, #7c3aed, #f97316)' }} />
          <span className="text-sm font-bold text-white">Cost Breakdown</span>
        </div>
        <BreakdownBar results={results} />
      </div>

      {/* Pricing cards */}
      <div className="rounded-2xl p-5" style={cardStyle}>
        <div className="flex items-center gap-2 mb-4">
          <div className="w-1 h-5 rounded-full" style={{ background: 'linear-gradient(to bottom, #7c3aed, #f97316)' }} />
          <span className="text-sm font-bold text-white">Suggested Pricing</span>
        </div>
        <div className="flex gap-3">
          <PriceCard
            title="Consumer"
            price={results.consumerPrice}
            grossProfit={results.grossProfitConsumer}
            liquidProfit={results.liquidProfitConsumer}
            margin={results.profitMarginConsumer}
            accent="#a855f7"
          />
          <PriceCard
            title="Reseller"
            price={results.resellerPrice}
            grossProfit={results.grossProfitReseller}
            liquidProfit={results.liquidProfitReseller}
            margin={results.profitMarginReseller}
            accent="#6366f1"
            dim
          />
        </div>
      </div>

      {/* Action buttons */}
      <div className="space-y-2">
        {/* Save calculation */}
        <button
          onClick={onSave}
          className="w-full py-2.5 rounded-xl text-sm font-semibold flex items-center justify-center gap-2 transition-all hover:opacity-90"
          style={{ background: 'rgba(107,47,179,0.15)', border: '1px solid rgba(107,47,179,0.3)', color: '#c084fc' }}
        >
          💾 Save Calculation
        </button>

        {/* Product actions */}
        <div className="flex gap-2">
          <button
            onClick={() => setShowUpdateModal(true)}
            className="flex-1 py-2.5 rounded-xl text-sm font-semibold flex items-center justify-center gap-1.5 transition-all hover:bg-white/5"
            style={{ border: '1px solid rgba(107,47,179,0.4)', color: '#c084fc' }}
          >
            📦 Update Existing
          </button>
          <button
            onClick={() => setShowCreateWizard(true)}
            className="flex-1 py-2.5 rounded-xl text-white text-sm font-bold flex items-center justify-center gap-1.5 transition-all hover:opacity-90 active:scale-95"
            style={{ background: 'linear-gradient(135deg, #7c3aed, #f97316)', boxShadow: '0 0 20px rgba(124,58,237,0.4)' }}
          >
            ✨ Create New
          </button>
        </div>
      </div>

      {showUpdateModal && (
        <UpdateProductModal results={results} onClose={() => setShowUpdateModal(false)} />
      )}
      {showCreateWizard && (
        <CreateProductWizard
          results={results}
          productName={data.productName}
          onClose={() => setShowCreateWizard(false)}
        />
      )}
    </div>
  );
}