/**
 * Create Product Wizard
 * Multi-step wizard for creating new marketplace products
 */

import React, { useState, useCallback } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import {
  ArrowLeft,
  ArrowRight,
  Check,
  Loader2,
  AlertCircle,
  Image,
  DollarSign,
  FileText,
  Settings,
  Eye,
  X,
  Plus,
  Upload,
} from 'lucide-react';

// ============================================================================
// Types
// ============================================================================

type ProductType = 'signals' | 'courses' | 'advisory';
type PricingPeriod = 'monthly' | 'quarterly' | 'yearly' | 'lifetime';

interface ProductFormData {
  type: ProductType;
  name: string;
  description: string;
  shortDescription: string;
  tags: string[];
  thumbnailUrl: string;
  pricing: PricingOption[];
  hasFreeTrial: boolean;
  freeTrialDays: number;
  // Signal-specific
  riskLevel?: 'low' | 'medium' | 'high';
  symbolsCovered?: string[];
  // Course-specific
  difficultyLevel?: 'beginner' | 'intermediate' | 'advanced';
  // Advisory-specific
  specializations?: string[];
  sessionDuration?: number;
}

interface PricingOption {
  id: string;
  period: PricingPeriod;
  price: number;
  originalPrice?: number;
  isPopular: boolean;
}

interface WizardStep {
  id: number;
  title: string;
  icon: React.ReactNode;
}

// ============================================================================
// Constants
// ============================================================================

const WIZARD_STEPS: WizardStep[] = [
  { id: 1, title: 'Product Type', icon: <Settings className="w-5 h-5" /> },
  { id: 2, title: 'Details', icon: <FileText className="w-5 h-5" /> },
  { id: 3, title: 'Pricing', icon: <DollarSign className="w-5 h-5" /> },
  { id: 4, title: 'Preview', icon: <Eye className="w-5 h-5" /> },
];

const PRODUCT_TYPES: { type: ProductType; title: string; description: string; icon: string }[] = [
  {
    type: 'signals',
    title: 'Signal Pack',
    description: 'Share your trading signals with subscribers',
    icon: '📊',
  },
  {
    type: 'courses',
    title: 'Course',
    description: 'Create educational content and lessons',
    icon: '📚',
  },
  {
    type: 'advisory',
    title: 'Advisory Service',
    description: 'Offer 1-on-1 consultations and coaching',
    icon: '👨‍💼',
  },
];

const INITIAL_PRICING: PricingOption[] = [
  { id: '1', period: 'monthly', price: 29.99, isPopular: false },
  { id: '2', period: 'quarterly', price: 79.99, originalPrice: 89.97, isPopular: true },
  { id: '3', period: 'yearly', price: 249.99, originalPrice: 359.88, isPopular: false },
];

// ============================================================================
// Step Components
// ============================================================================

// Step 1: Product Type Selection
interface TypeStepProps {
  selectedType: ProductType | null;
  onSelect: (type: ProductType) => void;
}

const TypeStep: React.FC<TypeStepProps> = ({ selectedType, onSelect }) => (
  <div className="space-y-6">
    <div className="text-center mb-8">
      <h2 className="text-2xl font-bold text-white mb-2">What would you like to create?</h2>
      <p className="text-gray-400">Choose the type of product you want to sell</p>
    </div>

    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
      {PRODUCT_TYPES.map((product) => (
        <button
          key={product.type}
          onClick={() => onSelect(product.type)}
          className={`p-6 rounded-xl border-2 text-left transition-all ${
            selectedType === product.type
              ? 'border-blue-500 bg-blue-500/10'
              : 'border-gray-700 hover:border-gray-600 bg-gray-800'
          }`}
        >
          <div className="text-4xl mb-4">{product.icon}</div>
          <h3 className="text-lg font-semibold text-white mb-2">{product.title}</h3>
          <p className="text-sm text-gray-400">{product.description}</p>
          {selectedType === product.type && (
            <div className="mt-4 flex items-center gap-2 text-blue-400 text-sm">
              <Check className="w-4 h-4" />
              Selected
            </div>
          )}
        </button>
      ))}
    </div>
  </div>
);

// Step 2: Product Details
interface DetailsStepProps {
  data: ProductFormData;
  onChange: (field: keyof ProductFormData, value: unknown) => void;
}

const DetailsStep: React.FC<DetailsStepProps> = ({ data, onChange }) => {
  const [newTag, setNewTag] = useState('');

  const handleAddTag = () => {
    if (newTag.trim() && !data.tags.includes(newTag.trim())) {
      onChange('tags', [...data.tags, newTag.trim()]);
      setNewTag('');
    }
  };

  const handleRemoveTag = (tag: string) => {
    onChange('tags', data.tags.filter((t) => t !== tag));
  };

  return (
    <div className="space-y-6">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-white mb-2">Product Details</h2>
        <p className="text-gray-400">Provide information about your product</p>
      </div>

      <div className="max-w-2xl mx-auto space-y-6">
        {/* Product Name */}
        <div>
          <label className="block text-sm font-medium text-gray-400 mb-2">
            Product Name <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            value={data.name}
            onChange={(e) => onChange('name', e.target.value)}
            placeholder="e.g., Pro Trading Signals"
            className="w-full px-4 py-3 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none"
          />
        </div>

        {/* Short Description */}
        <div>
          <label className="block text-sm font-medium text-gray-400 mb-2">
            Short Description <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            value={data.shortDescription}
            onChange={(e) => onChange('shortDescription', e.target.value)}
            placeholder="Brief summary (max 150 characters)"
            maxLength={150}
            className="w-full px-4 py-3 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none"
          />
          <p className="text-xs text-gray-500 mt-1">
            {data.shortDescription.length}/150 characters
          </p>
        </div>

        {/* Full Description */}
        <div>
          <label className="block text-sm font-medium text-gray-400 mb-2">
            Full Description <span className="text-red-400">*</span>
          </label>
          <textarea
            value={data.description}
            onChange={(e) => onChange('description', e.target.value)}
            placeholder="Detailed description of your product..."
            rows={6}
            className="w-full px-4 py-3 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none resize-none"
          />
        </div>

        {/* Thumbnail */}
        <div>
          <label className="block text-sm font-medium text-gray-400 mb-2">
            Thumbnail Image
          </label>
          <div className="border-2 border-dashed border-gray-700 rounded-lg p-8 text-center hover:border-gray-600 transition-colors cursor-pointer">
            {data.thumbnailUrl ? (
              <div className="relative inline-block">
                <img
                  src={data.thumbnailUrl}
                  alt="Thumbnail"
                  className="w-32 h-32 object-cover rounded-lg"
                />
                <button
                  onClick={() => onChange('thumbnailUrl', '')}
                  className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 rounded-full flex items-center justify-center"
                >
                  <X className="w-4 h-4 text-white" />
                </button>
              </div>
            ) : (
              <>
                <Upload className="w-10 h-10 text-gray-500 mx-auto mb-3" />
                <p className="text-gray-400 text-sm">
                  Drag and drop or click to upload
                </p>
                <p className="text-gray-500 text-xs mt-1">
                  PNG, JPG up to 2MB (recommended: 800x600)
                </p>
              </>
            )}
          </div>
        </div>

        {/* Tags */}
        <div>
          <label className="block text-sm font-medium text-gray-400 mb-2">Tags</label>
          <div className="flex flex-wrap gap-2 mb-3">
            {data.tags.map((tag) => (
              <span
                key={tag}
                className="px-3 py-1 bg-gray-700 text-gray-300 rounded-full text-sm flex items-center gap-1"
              >
                {tag}
                <button
                  onClick={() => handleRemoveTag(tag)}
                  className="hover:text-white"
                >
                  <X className="w-3 h-3" />
                </button>
              </span>
            ))}
          </div>
          <div className="flex gap-2">
            <input
              type="text"
              value={newTag}
              onChange={(e) => setNewTag(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleAddTag()}
              placeholder="Add a tag..."
              className="flex-1 px-4 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none"
            />
            <button
              onClick={handleAddTag}
              className="px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors"
            >
              <Plus className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Type-specific fields */}
        {data.type === 'signals' && (
          <div>
            <label className="block text-sm font-medium text-gray-400 mb-2">
              Risk Level
            </label>
            <div className="flex gap-3">
              {(['low', 'medium', 'high'] as const).map((level) => (
                <button
                  key={level}
                  onClick={() => onChange('riskLevel', level)}
                  className={`px-4 py-2 rounded-lg capitalize transition-colors ${
                    data.riskLevel === level
                      ? level === 'low'
                        ? 'bg-green-500/20 text-green-400 border border-green-500/50'
                        : level === 'medium'
                        ? 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/50'
                        : 'bg-red-500/20 text-red-400 border border-red-500/50'
                      : 'bg-gray-900 text-gray-400 border border-gray-700 hover:border-gray-600'
                  }`}
                >
                  {level} Risk
                </button>
              ))}
            </div>
          </div>
        )}

        {data.type === 'courses' && (
          <div>
            <label className="block text-sm font-medium text-gray-400 mb-2">
              Difficulty Level
            </label>
            <div className="flex gap-3">
              {(['beginner', 'intermediate', 'advanced'] as const).map((level) => (
                <button
                  key={level}
                  onClick={() => onChange('difficultyLevel', level)}
                  className={`px-4 py-2 rounded-lg capitalize transition-colors ${
                    data.difficultyLevel === level
                      ? 'bg-blue-500/20 text-blue-400 border border-blue-500/50'
                      : 'bg-gray-900 text-gray-400 border border-gray-700 hover:border-gray-600'
                  }`}
                >
                  {level}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Step 3: Pricing Configuration
interface PricingStepProps {
  data: ProductFormData;
  onChange: (field: keyof ProductFormData, value: unknown) => void;
}

const PricingStep: React.FC<PricingStepProps> = ({ data, onChange }) => {
  const updatePricing = (id: string, field: keyof PricingOption, value: unknown) => {
    const updated = data.pricing.map((p) =>
      p.id === id ? { ...p, [field]: value } : p
    );
    onChange('pricing', updated);
  };

  const setPopular = (id: string) => {
    const updated = data.pricing.map((p) => ({
      ...p,
      isPopular: p.id === id,
    }));
    onChange('pricing', updated);
  };

  return (
    <div className="space-y-6">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-white mb-2">Set Your Pricing</h2>
        <p className="text-gray-400">Configure subscription plans for your product</p>
      </div>

      <div className="max-w-2xl mx-auto space-y-6">
        {/* Pricing Tiers */}
        <div className="space-y-4">
          {data.pricing.map((pricing) => (
            <div
              key={pricing.id}
              className={`p-4 rounded-lg border ${
                pricing.isPopular
                  ? 'border-blue-500/50 bg-blue-500/10'
                  : 'border-gray-700 bg-gray-800'
              }`}
            >
              <div className="flex items-center justify-between mb-4">
                <span className="font-medium text-white capitalize">{pricing.period}</span>
                <button
                  onClick={() => setPopular(pricing.id)}
                  className={`px-3 py-1 rounded-full text-xs transition-colors ${
                    pricing.isPopular
                      ? 'bg-blue-500 text-white'
                      : 'bg-gray-700 text-gray-400 hover:text-white'
                  }`}
                >
                  {pricing.isPopular ? 'Popular' : 'Set as Popular'}
                </button>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs text-gray-500 mb-1">Price (USD)</label>
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">
                      $
                    </span>
                    <input
                      type="number"
                      value={pricing.price}
                      onChange={(e) =>
                        updatePricing(pricing.id, 'price', parseFloat(e.target.value) || 0)
                      }
                      min="0"
                      step="0.01"
                      className="w-full pl-8 pr-4 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white focus:border-blue-500 focus:outline-none"
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-xs text-gray-500 mb-1">
                    Original Price (optional)
                  </label>
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">
                      $
                    </span>
                    <input
                      type="number"
                      value={pricing.originalPrice || ''}
                      onChange={(e) =>
                        updatePricing(
                          pricing.id,
                          'originalPrice',
                          e.target.value ? parseFloat(e.target.value) : undefined
                        )
                      }
                      min="0"
                      step="0.01"
                      placeholder="Show savings"
                      className="w-full pl-8 pr-4 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-600 focus:border-blue-500 focus:outline-none"
                    />
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Free Trial */}
        <div className="p-4 rounded-lg border border-gray-700 bg-gray-800">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="font-medium text-white">Free Trial</h3>
              <p className="text-sm text-gray-400">
                Let customers try before they buy
              </p>
            </div>
            <button
              onClick={() => onChange('hasFreeTrial', !data.hasFreeTrial)}
              className={`w-12 h-6 rounded-full transition-colors ${
                data.hasFreeTrial ? 'bg-blue-600' : 'bg-gray-700'
              }`}
            >
              <div
                className={`w-5 h-5 rounded-full bg-white shadow transform transition-transform ${
                  data.hasFreeTrial ? 'translate-x-6' : 'translate-x-0.5'
                }`}
              />
            </button>
          </div>

          {data.hasFreeTrial && (
            <div>
              <label className="block text-xs text-gray-500 mb-1">Trial Period</label>
              <div className="flex items-center gap-2">
                <input
                  type="number"
                  value={data.freeTrialDays}
                  onChange={(e) =>
                    onChange('freeTrialDays', parseInt(e.target.value) || 0)
                  }
                  min="1"
                  max="30"
                  className="w-24 px-4 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white focus:border-blue-500 focus:outline-none"
                />
                <span className="text-gray-400">days</span>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// Step 4: Preview
interface PreviewStepProps {
  data: ProductFormData;
}

const PreviewStep: React.FC<PreviewStepProps> = ({ data }) => {
  const typeInfo = PRODUCT_TYPES.find((t) => t.type === data.type);

  return (
    <div className="space-y-6">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-white mb-2">Preview Your Product</h2>
        <p className="text-gray-400">Review how your product will appear in the marketplace</p>
      </div>

      <div className="max-w-xl mx-auto">
        {/* Product Card Preview */}
        <div className="bg-gray-800 rounded-xl border border-gray-700 overflow-hidden">
          {/* Thumbnail */}
          <div className="h-40 bg-gradient-to-br from-blue-600/20 to-purple-600/20 flex items-center justify-center">
            {data.thumbnailUrl ? (
              <img
                src={data.thumbnailUrl}
                alt={data.name}
                className="w-full h-full object-cover"
              />
            ) : (
              <span className="text-6xl">{typeInfo?.icon}</span>
            )}
          </div>

          {/* Content */}
          <div className="p-4">
            <h3 className="text-lg font-semibold text-white mb-2">
              {data.name || 'Product Name'}
            </h3>
            <p className="text-sm text-gray-400 mb-4 line-clamp-2">
              {data.shortDescription || 'Short description will appear here...'}
            </p>

            {/* Tags */}
            {data.tags.length > 0 && (
              <div className="flex flex-wrap gap-1 mb-4">
                {data.tags.slice(0, 3).map((tag) => (
                  <span
                    key={tag}
                    className="px-2 py-0.5 bg-gray-700 text-gray-300 text-xs rounded"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            )}

            {/* Price */}
            <div className="flex items-center justify-between pt-3 border-t border-gray-700">
              <div>
                <span className="text-xl font-bold text-white">
                  ${data.pricing.find((p) => p.period === 'monthly')?.price || 0}
                </span>
                <span className="text-gray-400 text-sm">/mo</span>
              </div>
              {data.hasFreeTrial && (
                <span className="px-2 py-1 bg-green-500/20 text-green-400 text-xs rounded-full">
                  {data.freeTrialDays} days free
                </span>
              )}
            </div>
          </div>
        </div>

        {/* Summary */}
        <div className="mt-6 p-4 bg-gray-900 rounded-lg">
          <h4 className="font-medium text-white mb-3">Product Summary</h4>
          <dl className="space-y-2 text-sm">
            <div className="flex justify-between">
              <dt className="text-gray-400">Type</dt>
              <dd className="text-white capitalize">{data.type}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-gray-400">Pricing Tiers</dt>
              <dd className="text-white">{data.pricing.length}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-gray-400">Free Trial</dt>
              <dd className="text-white">
                {data.hasFreeTrial ? `${data.freeTrialDays} days` : 'No'}
              </dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-gray-400">Tags</dt>
              <dd className="text-white">{data.tags.length}</dd>
            </div>
          </dl>
        </div>
      </div>
    </div>
  );
};

// ============================================================================
// Main Component
// ============================================================================

export default function CreateProductWizard() {
  const navigate = useNavigate();
  const [currentStep, setCurrentStep] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [formData, setFormData] = useState<ProductFormData>({
    type: 'signals',
    name: '',
    description: '',
    shortDescription: '',
    tags: [],
    thumbnailUrl: '',
    pricing: INITIAL_PRICING,
    hasFreeTrial: false,
    freeTrialDays: 7,
    riskLevel: 'medium',
    difficultyLevel: 'beginner',
    specializations: [],
    sessionDuration: 60,
  });

  // Update form field
  const handleChange = useCallback(
    (field: keyof ProductFormData, value: unknown) => {
      setFormData((prev) => ({ ...prev, [field]: value }));
    },
    []
  );

  // Validate current step
  const validateStep = useCallback(() => {
    switch (currentStep) {
      case 1:
        return !!formData.type;
      case 2:
        return !!(formData.name && formData.shortDescription && formData.description);
      case 3:
        return formData.pricing.every((p) => p.price > 0);
      default:
        return true;
    }
  }, [currentStep, formData]);

  // Navigate steps
  const handleNext = () => {
    if (validateStep() && currentStep < 4) {
      setCurrentStep(currentStep + 1);
    }
  };

  const handlePrevious = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  // Submit product
  const handleSubmit = async () => {
    setIsSubmitting(true);
    setError(null);

    try {
      // Simulated API call - replace with actual service
      await new Promise((resolve) => setTimeout(resolve, 2000));
      navigate('/marketplace/seller');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create product');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      {/* Back Link */}
      <Link
        to="/marketplace/seller"
        className="inline-flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
      >
        <ArrowLeft className="w-4 h-4" />
        Back to Dashboard
      </Link>

      {/* Progress Steps */}
      <div className="flex items-center justify-between">
        {WIZARD_STEPS.map((step, index) => (
          <React.Fragment key={step.id}>
            <div
              className={`flex items-center gap-3 cursor-pointer ${
                step.id <= currentStep ? 'opacity-100' : 'opacity-50'
              }`}
              onClick={() => step.id < currentStep && setCurrentStep(step.id)}
            >
              <div
                className={`w-10 h-10 rounded-full flex items-center justify-center transition-colors ${
                  currentStep >= step.id
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-700 text-gray-400'
                }`}
              >
                {currentStep > step.id ? <Check className="w-5 h-5" /> : step.icon}
              </div>
              <span className="hidden sm:block font-medium text-white">{step.title}</span>
            </div>
            {index < WIZARD_STEPS.length - 1 && (
              <div
                className={`flex-1 h-1 mx-4 rounded ${
                  currentStep > step.id ? 'bg-blue-600' : 'bg-gray-700'
                }`}
              />
            )}
          </React.Fragment>
        ))}
      </div>

      {/* Step Content */}
      <div className="bg-gray-800 rounded-xl border border-gray-700 p-8">
        {error && (
          <div className="mb-6 flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm">
            <AlertCircle className="w-4 h-4 flex-shrink-0" />
            {error}
          </div>
        )}

        {currentStep === 1 && (
          <TypeStep
            selectedType={formData.type}
            onSelect={(type) => handleChange('type', type)}
          />
        )}

        {currentStep === 2 && <DetailsStep data={formData} onChange={handleChange} />}

        {currentStep === 3 && <PricingStep data={formData} onChange={handleChange} />}

        {currentStep === 4 && <PreviewStep data={formData} />}

        {/* Navigation Buttons */}
        <div className="mt-8 pt-6 border-t border-gray-700 flex items-center justify-between">
          <button
            onClick={handlePrevious}
            disabled={currentStep === 1}
            className="px-6 py-2.5 text-gray-400 hover:text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
          >
            <ArrowLeft className="w-5 h-5" />
            Back
          </button>

          {currentStep < 4 ? (
            <button
              onClick={handleNext}
              disabled={!validateStep()}
              className="px-6 py-2.5 bg-blue-600 hover:bg-blue-500 text-white font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              Continue
              <ArrowRight className="w-5 h-5" />
            </button>
          ) : (
            <button
              onClick={handleSubmit}
              disabled={isSubmitting}
              className="px-6 py-2.5 bg-green-600 hover:bg-green-500 text-white font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  Creating...
                </>
              ) : (
                <>
                  <Check className="w-5 h-5" />
                  Create Product
                </>
              )}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
