import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { shire } from '@/api/shireClient';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import StepProgress from '@/components/create-product/StepProgress';
import Step1Basics from '@/components/create-product/Step1Basics';
import Step2Marketing from '@/components/create-product/Step2Marketing';
import Step3Pricing from '@/components/create-product/Step3Pricing';
import Step4Review from '@/components/create-product/Step4Review';

const SHIRE_CONTEXT = `You are the marketing brain for "Shire 3D" — a small Australian 3D printing business run by a passionate maker. 
Shire 3D sells handcrafted, paintable 3D printed items: fantasy masks, cosplay props, home decor, jewelry, and collectibles.
Tone: creative, warm, slightly whimsical, never corporate. Australian spelling. Prices in AUD.`;

async function generateAllMarketing(name, category, price) {
  const prompt = `${SHIRE_CONTEXT}

Generate marketing copy for a 3D printed product called: "${name}"
Category: ${category || '3D prints'}
Price: AUD $${price || 'TBD'}

Return a JSON object with EXACTLY these keys:
- tagline: short punchy one-liner (max 12 words)
- etsy_title: SEO-optimised Etsy title (max 140 chars, keyword-rich)
- etsy_description: full Etsy listing description (~300 words) with hook opener, bullet features, materials/dimensions placeholder, Australian shipping info, care instructions
- etsy_tags: exactly 13 comma-separated Etsy tags (max 20 chars each, no #)
- square_description: punchy Square description (~80 words, direct and engaging)
- ebay_title: eBay listing title (max 80 chars, keyword-rich)
- ebay_description: eBay listing description with condition (New), features, what's included, Australian postage note, friendly closer`;

  const result = await shire.integrations.Core.InvokeLLM({
    prompt,
    response_json_schema: {
      type: 'object',
      properties: {
        tagline: { type: 'string' },
        etsy_title: { type: 'string' },
        etsy_description: { type: 'string' },
        etsy_tags: { type: 'string' },
        square_description: { type: 'string' },
        ebay_title: { type: 'string' },
        ebay_description: { type: 'string' },
      },
    },
  });
  return result;
}

const STEP_LABELS = ['The Basics', 'AI Marketing Genius', 'Pricing & Marketplaces', 'Review & Save'];

export default function CreateProduct() {
  const navigate = useNavigate();
  const [step, setStep] = useState(1);
  const [data, setData] = useState({
    images: [],
    quantity: 1,
  });

  const handleAIGenerate = async (name, category, price) => {
    const marketing = await generateAllMarketing(name, category, price);
    setData(prev => ({
      ...prev,
      ...marketing,
      // Pre-fill marketplace prices from base price
      etsy_price: prev.etsy_price || prev.price,
      square_price: prev.square_price || prev.price,
      ebay_price: prev.ebay_price || prev.price,
    }));
    // Auto-advance to step 2
    setStep(2);
  };

  const canNext = () => {
    if (step === 1) return !!data.title;
    return true;
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="sticky top-0 z-20 bg-white border-b border-gray-100 shadow-sm">
        <div className="max-w-2xl mx-auto px-4 py-4">
          <div className="flex items-center gap-3 mb-4">
            <button
              onClick={() => navigate('/products')}
              className="text-gray-500 hover:text-gray-800 transition-colors"
            >
              <ChevronLeft size={20} />
            </button>
            <div>
              <h1 className="text-base font-bold text-gray-900">Create New Product</h1>
              <p className="text-xs text-gray-400">Step {step} of 4 — {STEP_LABELS[step - 1]}</p>
            </div>
          </div>
          <StepProgress current={step} />
        </div>
      </div>

      {/* Content */}
      <div className="max-w-2xl mx-auto px-4 py-6">
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          {step === 1 && (
            <Step1Basics
              data={data}
              onChange={setData}
              onAIGenerate={handleAIGenerate}
            />
          )}
          {step === 2 && (
            <Step2Marketing
              data={data}
              onChange={setData}
              productName={data.title}
              category={data.category}
            />
          )}
          {step === 3 && (
            <Step3Pricing
              data={data}
              onChange={d => setData(prev => ({
                ...prev,
                ...d,
                etsy_price: d.etsy_price ?? prev.price,
                square_price: d.square_price ?? prev.price,
                ebay_price: d.ebay_price ?? prev.price,
              }))}
            />
          )}
          {step === 4 && (
            <Step4Review data={data} />
          )}
        </div>

        {/* Nav buttons */}
        <div className="flex gap-3 mt-4">
          {step > 1 && (
            <button
              onClick={() => setStep(s => s - 1)}
              className="flex items-center gap-1.5 px-5 py-2.5 rounded-xl border border-gray-200 text-sm font-semibold text-gray-700 hover:bg-gray-50 transition-all"
            >
              <ChevronLeft size={16} /> Back
            </button>
          )}
          {step < 4 && (
            <button
              onClick={() => setStep(s => s + 1)}
              disabled={!canNext()}
              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: '#f97316' }}
            >
              Next <ChevronRight size={16} />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}