import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check } from 'lucide-react';
import Button from '../../../ui/Button/Button';
import Card from '../../../ui/Card/Card';

export interface BakeryTypeSelectionStepProps {
  onUpdate?: (data: { bakeryType: string }) => void;
  onComplete?: (data?: { bakeryType: string }) => void;
  initialData?: {
    bakeryType?: string;
  };
}

interface BakeryType {
  id: 'production' | 'retail' | 'mixed';
  icon: string;
  name: string;
  description: string;
  features: string[];
  examples: string[];
  color: string;
  gradient: string;
}

export const BakeryTypeSelectionStep: React.FC<BakeryTypeSelectionStepProps> = ({
  onUpdate,
  onComplete,
  initialData,
}) => {
  const { t } = useTranslation();
  const [selectedType, setSelectedType] = useState<string | null>(
    initialData?.bakeryType || null
  );
  const [hoveredType, setHoveredType] = useState<string | null>(null);

  const bakeryTypes: BakeryType[] = [
    {
      id: 'production',
      icon: '🥖',
      name: t('onboarding:bakery_type.production.name', 'Panadería de Producción'),
      description: t(
        'onboarding:bakery_type.production.description',
        'Producimos desde cero usando ingredientes básicos'
      ),
      features: [
        t('onboarding:bakery_type.production.feature1', 'Gestión completa de recetas'),
        t('onboarding:bakery_type.production.feature2', 'Control de ingredientes y costos'),
        t('onboarding:bakery_type.production.feature3', 'Planificación de producción'),
        t('onboarding:bakery_type.production.feature4', 'Control de calidad de materia prima'),
      ],
      examples: [
        t('onboarding:bakery_type.production.example1', 'Pan artesanal'),
        t('onboarding:bakery_type.production.example2', 'Bollería'),
        t('onboarding:bakery_type.production.example3', 'Repostería'),
        t('onboarding:bakery_type.production.example4', 'Pastelería'),
      ],
      color: 'from-amber-500 to-orange-600',
      gradient: 'bg-gradient-to-br from-amber-50 to-orange-50',
    },
    {
      id: 'retail',
      icon: '🏪',
      name: t('onboarding:bakery_type.retail.name', 'Panadería de Venta (Retail)'),
      description: t(
        'onboarding:bakery_type.retail.description',
        'Horneamos y vendemos productos pre-elaborados'
      ),
      features: [
        t('onboarding:bakery_type.retail.feature1', 'Control de productos terminados'),
        t('onboarding:bakery_type.retail.feature2', 'Gestión de horneado simple'),
        t('onboarding:bakery_type.retail.feature3', 'Control de inventario de punto de venta'),
        t('onboarding:bakery_type.retail.feature4', 'Seguimiento de ventas y mermas'),
      ],
      examples: [
        t('onboarding:bakery_type.retail.example1', 'Pan pre-horneado'),
        t('onboarding:bakery_type.retail.example2', 'Productos congelados para terminar'),
        t('onboarding:bakery_type.retail.example3', 'Bollería lista para venta'),
        t('onboarding:bakery_type.retail.example4', 'Pasteles y tortas de proveedores'),
      ],
      color: 'from-blue-500 to-indigo-600',
      gradient: 'bg-gradient-to-br from-blue-50 to-indigo-50',
    },
    {
      id: 'mixed',
      icon: '🏭',
      name: t('onboarding:bakery_type.mixed.name', 'Panadería Mixta'),
      description: t(
        'onboarding:bakery_type.mixed.description',
        'Combinamos producción propia con productos terminados'
      ),
      features: [
        t('onboarding:bakery_type.mixed.feature1', 'Recetas propias y productos externos'),
        t('onboarding:bakery_type.mixed.feature2', 'Flexibilidad total en gestión'),
        t('onboarding:bakery_type.mixed.feature3', 'Control completo de costos'),
        t('onboarding:bakery_type.mixed.feature4', 'Máxima adaptabilidad'),
      ],
      examples: [
        t('onboarding:bakery_type.mixed.example1', 'Pan propio + bollería de proveedor'),
        t('onboarding:bakery_type.mixed.example2', 'Pasteles propios + pre-horneados'),
        t('onboarding:bakery_type.mixed.example3', 'Productos artesanales + industriales'),
        t('onboarding:bakery_type.mixed.example4', 'Combinación según temporada'),
      ],
      color: 'from-purple-500 to-pink-600',
      gradient: 'bg-gradient-to-br from-purple-50 to-pink-50',
    },
  ];

  const handleSelectType = (typeId: string) => {
    setSelectedType(typeId);
    onUpdate?.({ bakeryType: typeId });
  };

  const handleContinue = () => {
    if (selectedType) {
      onComplete?.({ bakeryType: selectedType });
    }
  };

  return (
    <div className="max-w-6xl mx-auto p-3 md:p-6 space-y-8 md:space-y-10">
      {/* Header */}
      <div className="text-center space-y-4 md:space-y-5 animate-fade-in">
        <div className="inline-block">
          <div className="text-5xl md:text-6xl mb-3 animate-bounce-subtle">🏪</div>
        </div>
        <h1 className="text-3xl md:text-4xl font-bold text-[var(--text-primary)] px-2 leading-tight">
          {t('onboarding:bakery_type.title', '¿Qué tipo de panadería tienes?')}
        </h1>
        <p className="text-base md:text-lg text-[var(--text-secondary)] max-w-3xl mx-auto px-4 leading-relaxed">
          {t(
            'onboarding:bakery_type.subtitle',
            'Esto nos ayudará a personalizar la experiencia y mostrarte solo las funciones que necesitas'
          )}
        </p>
      </div>

      {/* Bakery Type Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-5 md:gap-6 animate-stagger-in">
        {bakeryTypes.map((type, index) => {
          const isSelected = selectedType === type.id;
          const isHovered = hoveredType === type.id;

          return (
            <button
              key={type.id}
              type="button"
              onClick={() => handleSelectType(type.id)}
              onMouseEnter={() => setHoveredType(type.id)}
              onMouseLeave={() => setHoveredType(null)}
              style={{ animationDelay: `${index * 100}ms` }}
              className={`
                relative cursor-pointer transition-all duration-300 overflow-hidden
                border-2 rounded-2xl text-left w-full group
                bg-[var(--bg-secondary)]
                transform-gpu
                ${isSelected
                  ? 'border-[var(--color-primary)] shadow-2xl ring-4 ring-[var(--color-primary)]/30 scale-[1.03] -translate-y-1'
                  : 'border-[var(--border-color)] hover:border-[var(--color-primary)]/60 hover:shadow-xl hover:scale-[1.02] hover:-translate-y-0.5'
                }
                ${isHovered && !isSelected ? 'shadow-lg' : ''}
              `}
            >
              {/* Selection Indicator */}
              {isSelected && (
                <div className="absolute top-4 right-4 z-10 animate-scale-in">
                  <div className="w-10 h-10 bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary)]/80 rounded-full flex items-center justify-center shadow-xl animate-pulse-slow">
                    <Check className="w-6 h-6 text-white" strokeWidth={3} />
                  </div>
                </div>
              )}

              {/* Accent Background with gradient */}
              <div className={`absolute inset-0 bg-gradient-to-br from-[var(--color-primary)]/8 to-[var(--color-primary)]/3 transition-opacity duration-300 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-50'}`} />

              {/* Hover shimmer effect */}
              <div className={`absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent -translate-x-full transition-transform duration-1000 ${isHovered ? 'translate-x-full' : ''}`} />

              {/* Content */}
              <div className="relative p-5 md:p-7 space-y-4 md:space-y-5">
                {/* Icon & Title */}
                <div className="space-y-3 md:space-y-4">
                  <div className="text-5xl md:text-6xl transform transition-transform duration-300 group-hover:scale-110">
                    {type.icon}
                  </div>
                  <h3 className="text-xl md:text-2xl font-bold text-[var(--text-primary)] leading-tight">
                    {type.name}
                  </h3>
                  <p className="text-sm md:text-base text-[var(--text-secondary)] leading-relaxed">
                    {type.description}
                  </p>
                </div>

                {/* Features */}
                <div className="space-y-3 pt-3">
                  <h4 className="text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider flex items-center gap-2">
                    <span className="w-1 h-4 bg-[var(--color-primary)] rounded-full"></span>
                    {t('onboarding:bakery_type.features_label', 'Características')}
                  </h4>
                  <ul className="space-y-2.5">
                    {type.features.map((feature, featureIndex) => (
                      <li
                        key={featureIndex}
                        className="text-sm md:text-base text-[var(--text-primary)] flex items-start gap-2.5 group/feature"
                      >
                        <span className="text-[var(--color-primary)] mt-0.5 flex-shrink-0 font-bold text-lg group-hover/feature:scale-125 transition-transform">✓</span>
                        <span className="leading-snug">{feature}</span>
                      </li>
                    ))}
                  </ul>
                </div>

                {/* Examples */}
                <div className="space-y-3 pt-4 border-t-2 border-[var(--border-color)]/50">
                  <h4 className="text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider flex items-center gap-2">
                    <span className="w-1 h-4 bg-[var(--color-primary)] rounded-full"></span>
                    {t('onboarding:bakery_type.examples_label', 'Ejemplos')}
                  </h4>
                  <div className="flex flex-wrap gap-2">
                    {type.examples.map((example, exampleIndex) => (
                      <span
                        key={exampleIndex}
                        className="text-xs md:text-sm px-3 py-1.5 bg-[var(--bg-primary)] border-2 border-[var(--border-color)] rounded-full text-[var(--text-secondary)] hover:border-[var(--color-primary)] hover:text-[var(--color-primary)] transition-all duration-200 cursor-default"
                      >
                        {example}
                      </span>
                    ))}
                  </div>
                </div>
              </div>
            </button>
          );
        })}
      </div>

      {/* Additional Info */}
      {selectedType && (
        <div className="bg-gradient-to-br from-[var(--color-primary)]/10 to-[var(--color-primary)]/5 border-2 border-[var(--color-primary)]/30 rounded-2xl p-5 md:p-7 animate-slide-up shadow-lg">
          <div className="flex items-start gap-4 md:gap-5">
            <div className="text-4xl md:text-5xl flex-shrink-0 animate-bounce-subtle">
              {bakeryTypes.find(t => t.id === selectedType)?.icon}
            </div>
            <div className="space-y-3 flex-1">
              <h4 className="text-lg md:text-xl font-bold text-[var(--text-primary)] flex items-center gap-2">
                <span className="text-2xl">✨</span>
                {t('onboarding:bakery_type.selected_info_title', 'Perfecto para tu panadería')}
              </h4>
              <p className="text-sm md:text-base text-[var(--text-secondary)] leading-relaxed">
                {selectedType === 'production' &&
                  t(
                    'onboarding:bakery_type.production.selected_info',
                    'Configuraremos un sistema completo de gestión de recetas, ingredientes y producción adaptado a tu flujo de trabajo.'
                  )}
                {selectedType === 'retail' &&
                  t(
                    'onboarding:bakery_type.retail.selected_info',
                    'Configuraremos un sistema simple enfocado en control de inventario, horneado y ventas sin la complejidad de recetas.'
                  )}
                {selectedType === 'mixed' &&
                  t(
                    'onboarding:bakery_type.mixed.selected_info',
                    'Configuraremos un sistema flexible que te permite gestionar tanto producción propia como productos externos según tus necesidades.'
                  )}
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Help Text & Continue Button */}
      <div className="text-center space-y-5 pt-2">
        <div className="inline-flex items-center gap-2 px-4 py-2 bg-[var(--bg-secondary)] rounded-full border border-[var(--border-color)]">
          <span className="text-xl">💡</span>
          <p className="text-sm md:text-base text-[var(--text-secondary)]">
            {t(
              'onboarding:bakery_type.help_text',
              'No te preocupes, siempre puedes cambiar esto más tarde en la configuración'
            )}
          </p>
        </div>

        <div className="flex justify-center pt-2">
          <Button
            onClick={handleContinue}
            disabled={!selectedType}
            size="lg"
            className={`w-full sm:w-auto sm:min-w-[250px] text-base md:text-lg font-semibold transform transition-all duration-300 ${
              selectedType ? 'hover:scale-105 shadow-lg' : ''
            }`}
          >
            {t('onboarding:bakery_type.continue_button', 'Continuar')} →
          </Button>
        </div>
      </div>
    </div>
  );
};

export default BakeryTypeSelectionStep;
