import { useState } from 'react';
import { X, ChevronLeft, ChevronRight, Check, ExternalLink } from 'lucide-react';
import { shire } from '@/api/shireClient';
import { toast } from 'sonner';
import { useNavigate } from 'react-router-dom';

const CATEGORIES = [
  'Miniatures', 'Terrain & Scenery', 'Dice & Gaming', 'Home & Decor',
  'Functional Prints', 'Cosplay & Props', 'Animals & Nature', 'Other',
];

const slugify = (str) => (str || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');

const inputClass = 'w-full px-3 py-2.5 text-sm rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 text-white transition-all';
const inputStyle = { background: '#0d0d1a', border: '1px solid rgba(107,47,179,0.3)' };

const Field = ({ label, children, hint }) => (
  <div>
    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'rgba(200,180,255,0.8)' }}>{label}</label>
    {children}
    {hint && <p className="text-xs mt-1" style={{ color: 'rgba(200,180,255,0.4)' }}>{hint}</p>}
  </div>
);

const STEP_LABELS = ['Details', 'Pricing', 'Links', 'Review'];

function StepDots({ current }) {
  return (
    <div className="flex items-center justify-center gap-3 py-4">
      {STEP_LABELS.map((label, i) => {
        const step = i + 1;
        const done = step < current;
        const active = step === current;
        return (
          <div key={label} className="flex flex-col items-center gap-1">
            <div className="w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition-all"
              style={{
                background: active ? 'linear-gradient(135deg, #7c3aed, #a855f7)' : done ? 'rgba(124,58,237,0.3)' : 'rgba(255,255,255,0.05)',
                border: active ? '2px solid #a855f7' : done ? '2px solid rgba(124,58,237,0.4)' : '2px solid rgba(255,255,255,0.1)',
                color: active ? 'white' : done ? '#c084fc' : 'rgba(255,255,255,0.3)',
                boxShadow: active ? '0 0 16px rgba(168,85,247,0.5)' : 'none',
              }}>
              {done ? <Check size={12} /> : step}
            </div>
            <span className="text-xs hidden sm:block" style={{ color: active ? '#c084fc' : 'rgba(200,180,255,0.3)' }}>{label}</span>
          </div>
        );
      })}
    </div>
  );
}

function Step1({ form, setForm }) {
  return (
    <div className="space-y-4">
      <Field label="Product Title *">
        <input type="text" value={form.title} onChange={e => {
          const title = e.target.value;
          setForm(p => ({ ...p, title, slug: slugify(title) }));
        }} placeholder="e.g. Dragon Skull Mask" className={inputClass} style={inputStyle} />
      </Field>
      <Field label="Category">
        <select value={form.category} onChange={e => setForm(p => ({ ...p, category: e.target.value }))}
          className={inputClass} style={inputStyle}>
          <option value="">Select category…</option>
          {CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
        </select>
      </Field>
      <Field label="Description">
        <textarea value={form.description} onChange={e => setForm(p => ({ ...p, description: e.target.value }))}
          rows={4} placeholder="Describe the product…" className={inputClass} style={{ ...inputStyle, resize: 'none' }} />
      </Field>
      <Field label="Tags" hint="Comma-separated, e.g. dragon, mask, cosplay, 3d print">
        <input type="text" value={form.tags} onChange={e => setForm(p => ({ ...p, tags: e.target.value }))}
          placeholder="dragon, fantasy, paintable" className={inputClass} style={inputStyle} />
      </Field>
      <Field label="Internal Notes">
        <textarea value={form.notes} onChange={e => setForm(p => ({ ...p, notes: e.target.value }))}
          rows={2} className={inputClass} style={{ ...inputStyle, resize: 'none' }} />
      </Field>
    </div>
  );
}

function Step2({ form, setForm, results }) {
  return (
    <div className="space-y-4">
      {/* Cost summary */}
      <div className="grid grid-cols-2 gap-3">
        <div className="rounded-xl p-3 text-center" style={{ background: 'rgba(107,47,179,0.1)', border: '1px solid rgba(107,47,179,0.2)' }}>
          <p className="text-xs mb-0.5" style={{ color: 'rgba(200,180,255,0.5)' }}>Total Cost</p>
          <p className="text-lg font-black" style={{ color: '#c084fc' }}>${(results.totalCost || 0).toFixed(2)}</p>
        </div>
        <div className="rounded-xl p-3 text-center" style={{ background: 'rgba(107,47,179,0.1)', border: '1px solid rgba(107,47,179,0.2)' }}>
          <p className="text-xs mb-0.5" style={{ color: 'rgba(200,180,255,0.5)' }}>Unit Cost</p>
          <p className="text-lg font-black" style={{ color: '#c084fc' }}>${(results.unitCost || 0).toFixed(2)}</p>
        </div>
      </div>

      <p className="text-xs px-3 py-2 rounded-lg" style={{ background: 'rgba(245,158,11,0.1)', color: 'rgba(251,191,36,0.8)', border: '1px solid rgba(245,158,11,0.2)' }}>
        💡 Prices pre-filled from your cost calculator. Adjust per marketplace as needed.
      </p>

      {[
        { label: 'Consumer Price (AUD)', key: 'price' },
        { label: 'Etsy Price (AUD)', key: 'etsy_price' },
        { label: 'Square Price (AUD)', key: 'square_price' },
        { label: 'eBay Price (AUD)', key: 'ebay_price' },
      ].map(({ label, key }) => (
        <Field key={key} label={label}>
          <div className="relative">
            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm" style={{ color: 'rgba(200,180,255,0.5)' }}>$</span>
            <input type="number" step="0.01" value={form[key]} onChange={e => setForm(p => ({ ...p, [key]: e.target.value }))}
              className={inputClass} style={{ ...inputStyle, paddingLeft: '1.75rem' }} />
          </div>
        </Field>
      ))}
    </div>
  );
}

function Step3({ form, setForm }) {
  return (
    <div className="space-y-4">
      {[
        { label: '🛍 Etsy Listing URL', key: 'etsy_url', placeholder: 'https://shire3d.etsy.com/listing/XXXXXXX' },
        { label: '🟩 Square Product URL', key: 'square_url', placeholder: 'https://squareup.com/...' },
        { label: '🔵 eBay Listing URL', key: 'ebay_url', placeholder: 'https://ebay.com.au/itm/...' },
        { label: '🖼️ Product Image URL', key: 'image_url', placeholder: 'https://...' },
      ].map(({ label, key, placeholder }) => (
        <Field key={key} label={label}>
          <input type="url" value={form[key]} onChange={e => setForm(p => ({ ...p, [key]: e.target.value }))}
            placeholder={placeholder} className={inputClass} style={inputStyle} />
        </Field>
      ))}
      <Field label="URL Slug" hint="Auto-generated from title — edit if needed">
        <input type="text" value={form.slug} onChange={e => setForm(p => ({ ...p, slug: e.target.value }))}
          className={inputClass} style={inputStyle} />
      </Field>
    </div>
  );
}

function Step4({ form }) {
  const fmt = (n) => n ? `$${Number(n).toFixed(2)}` : '—';
  return (
    <div className="space-y-4">
      {form.image_url && (
        <img src={form.image_url} alt={form.title} className="w-full h-40 object-cover rounded-xl" />
      )}
      <div className="rounded-xl p-4 space-y-3" style={{ background: 'rgba(107,47,179,0.08)', border: '1px solid rgba(107,47,179,0.2)' }}>
        {form.category && <p className="text-xs font-bold uppercase tracking-widest" style={{ color: '#a78bfa' }}>{form.category}</p>}
        <h3 className="text-xl font-black text-white">{form.title || '(no title)'}</h3>
        {form.description && <p className="text-sm line-clamp-3" style={{ color: 'rgba(200,180,255,0.7)' }}>{form.description}</p>}

        <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 pt-1">
          {[
            { label: 'Consumer', val: form.price },
            { label: 'Etsy', val: form.etsy_price },
            { label: 'Square', val: form.square_price },
            { label: 'eBay', val: form.ebay_price },
          ].map(({ label, val }) => (
            <div key={label} className="text-center rounded-lg py-2" style={{ background: 'rgba(255,255,255,0.04)' }}>
              <p className="text-xs mb-0.5" style={{ color: 'rgba(200,180,255,0.5)' }}>{label}</p>
              <p className="font-bold text-white text-sm">{fmt(val)}</p>
            </div>
          ))}
        </div>

        {(form.etsy_url || form.square_url || form.ebay_url) && (
          <div className="flex flex-wrap gap-2 pt-1">
            {form.etsy_url && <a href={form.etsy_url} target="_blank" rel="noreferrer" className="text-xs text-orange-400 hover:underline flex items-center gap-1">Etsy <ExternalLink size={10} /></a>}
            {form.square_url && <a href={form.square_url} target="_blank" rel="noreferrer" className="text-xs text-green-400 hover:underline flex items-center gap-1">Square <ExternalLink size={10} /></a>}
            {form.ebay_url && <a href={form.ebay_url} target="_blank" rel="noreferrer" className="text-xs text-blue-400 hover:underline flex items-center gap-1">eBay <ExternalLink size={10} /></a>}
          </div>
        )}
        {form.tags && <p className="text-xs" style={{ color: 'rgba(200,180,255,0.4)' }}>🏷 {form.tags}</p>}
      </div>
    </div>
  );
}

function SuccessView({ title, onReset, onView }) {
  return (
    <div className="py-8 text-center space-y-5">
      <div className="text-6xl mb-2">🎉</div>
      <div>
        <h3 className="text-xl font-black text-white mb-2">Product Created!</h3>
        <p className="text-sm" style={{ color: 'rgba(200,180,255,0.7)' }}>
          <span className="font-semibold text-purple-300">"{title}"</span> has been added to your database.
        </p>
      </div>
      <div className="flex gap-3 justify-center">
        <button onClick={onReset}
          className="px-5 py-2.5 rounded-xl text-sm font-semibold border transition-all hover:bg-white/5"
          style={{ color: 'rgba(200,180,255,0.7)', borderColor: 'rgba(107,47,179,0.3)' }}>
          Create Another
        </button>
        <button onClick={onView}
          className="px-5 py-2.5 rounded-xl text-white text-sm font-bold transition-all hover:opacity-90"
          style={{ background: 'linear-gradient(135deg, #7c3aed, #f97316)' }}>
          View Products →
        </button>
      </div>
    </div>
  );
}

export default function CreateProductWizard({ results, productName, onClose }) {
  const navigate = useNavigate();
  const cp = Math.round((results.consumerPrice || 0) * 100) / 100;

  const initialForm = {
    title: productName || '',
    category: '',
    description: '',
    tags: '',
    notes: '',
    price: cp,
    etsy_price: cp,
    square_price: cp,
    ebay_price: cp,
    etsy_url: '',
    square_url: '',
    ebay_url: '',
    image_url: '',
    slug: slugify(productName || ''),
  };

  const [step, setStep] = useState(1);
  const [form, setForm] = useState(initialForm);
  const [saving, setSaving] = useState(false);
  const [success, setSuccess] = useState(false);

  const handleCreate = async () => {
    setSaving(true);
    await shire.entities.Product.create({
      title: form.title,
      category: form.category,
      price: Number(form.price) || 0,
      etsy_price: Number(form.etsy_price) || 0,
      square_price: Number(form.square_price) || 0,
      ebay_price: Number(form.ebay_price) || 0,
      etsy_url: form.etsy_url,
      square_url: form.square_url,
      ebay_url: form.ebay_url,
      image_url: form.image_url,
      notes: form.notes,
      tags: form.tags,
      slug: form.slug,
    });
    setSaving(false);
    setSuccess(true);
    toast.success(`✅ ${form.title} added to database!`);
  };

  const handleReset = () => {
    setForm(initialForm);
    setStep(1);
    setSuccess(false);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={{ background: 'rgba(0,0,0,0.8)', backdropFilter: 'blur(6px)' }}>
      <div className="w-full max-w-2xl rounded-2xl flex flex-col max-h-[95vh]" style={{
        background: '#1a1a2e',
        border: '1px solid rgba(107,47,179,0.5)',
        boxShadow: '0 0 80px rgba(107,47,179,0.3)',
      }}>
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 flex-shrink-0" style={{ borderBottom: '1px solid rgba(107,47,179,0.2)' }}>
          <h2 className="font-bold text-white text-lg">✨ Create New Product</h2>
          <button onClick={onClose} className="transition-colors" style={{ color: 'rgba(200,180,255,0.5)' }}>
            <X size={20} />
          </button>
        </div>

        {!success && <StepDots current={step} />}

        {/* Body */}
        <div className="flex-1 overflow-y-auto px-6 pb-2">
          {success ? (
            <SuccessView title={form.title} onReset={handleReset} onView={() => { onClose(); navigate('/products'); }} />
          ) : (
            <>
              <div className="mb-2">
                <h3 className="text-sm font-bold text-white mb-0.5">
                  {['Product Details', 'Pricing', 'Marketplace Links', 'Review & Create'][step - 1]}
                </h3>
                <div className="h-px" style={{ background: 'rgba(107,47,179,0.15)' }} />
              </div>
              <div className="py-4">
                {step === 1 && <Step1 form={form} setForm={setForm} />}
                {step === 2 && <Step2 form={form} setForm={setForm} results={results} />}
                {step === 3 && <Step3 form={form} setForm={setForm} />}
                {step === 4 && <Step4 form={form} />}
              </div>
            </>
          )}
        </div>

        {/* Footer nav */}
        {!success && (
          <div className="px-6 py-4 flex gap-3 flex-shrink-0" style={{ borderTop: '1px solid rgba(107,47,179,0.2)' }}>
            {step > 1 ? (
              <button onClick={() => setStep(s => s - 1)}
                className="flex items-center gap-1.5 px-4 py-2.5 rounded-xl text-sm font-semibold border transition-all hover:bg-white/5"
                style={{ color: 'rgba(200,180,255,0.7)', borderColor: 'rgba(107,47,179,0.3)' }}>
                <ChevronLeft size={15} /> Back
              </button>
            ) : (
              <button onClick={onClose}
                className="flex items-center gap-1.5 px-4 py-2.5 rounded-xl text-sm font-semibold border transition-all hover:bg-white/5"
                style={{ color: 'rgba(200,180,255,0.7)', borderColor: 'rgba(107,47,179,0.3)' }}>
                Cancel
              </button>
            )}
            {step < 4 && (
              <button onClick={() => setStep(s => s + 1)} disabled={step === 1 && !form.title}
                className="flex-1 flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-white text-sm font-bold transition-all disabled:opacity-40"
                style={{ background: 'linear-gradient(135deg, #7c3aed, #a855f7)' }}>
                Next <ChevronRight size={15} />
              </button>
            )}
            {step === 4 && (
              <button onClick={handleCreate} disabled={saving || !form.title}
                className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl text-white text-sm font-bold transition-all disabled:opacity-40"
                style={{ background: 'linear-gradient(135deg, #7c3aed, #f97316)', boxShadow: '0 0 20px rgba(124,58,237,0.4)' }}>
                {saving
                  ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  : '🚀 Create Product'}
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
