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?: () => 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?.();
    }
  };

  return (
    <div className="max-w-6xl mx-auto p-4 md:p-6 space-y-6 md:space-y-8">
      {/* Header */}
      <div className="text-center space-y-3 md:space-y-4">
        <h1 className="text-2xl md:text-3xl font-bold text-[var(--text-primary)] px-2">
          {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-2xl mx-auto px-4">
          {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-6">
        {bakeryTypes.map((type) => {
          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)}
              className={`
                relative cursor-pointer transition-all duration-300 overflow-hidden
                border-2 rounded-lg text-left w-full
                bg-[var(--bg-secondary)]
                ${isSelected
                  ? 'border-[var(--color-primary)] shadow-lg ring-2 ring-[var(--color-primary)]/50 scale-[1.02]'
                  : 'border-[var(--border-color)] hover:border-[var(--color-primary)]/50 hover:shadow-md'
                }
                ${isHovered && !isSelected ? 'shadow-sm' : ''}
              `}
            >
              {/* Selection Indicator */}
              {isSelected && (
                <div className="absolute top-4 right-4 z-10">
                  <div className="w-8 h-8 bg-[var(--color-primary)] rounded-full flex items-center justify-center shadow-lg">
                    <Check className="w-5 h-5 text-white" strokeWidth={3} />
                  </div>
                </div>
              )}

              {/* Accent Background */}
              <div className={`absolute inset-0 bg-[var(--color-primary)]/5 transition-opacity ${isSelected ? 'opacity-100' : 'opacity-0'}`} />

              {/* Content */}
              <div className="relative p-4 md:p-6 space-y-3 md:space-y-4">
                {/* Icon & Title */}
                <div className="space-y-2 md:space-y-3">
                  <div className="text-4xl md:text-5xl">{type.icon}</div>
                  <h3 className="text-lg md:text-xl font-bold text-[var(--text-primary)]">
                    {type.name}
                  </h3>
                  <p className="text-sm text-[var(--text-secondary)] leading-relaxed">
                    {type.description}
                  </p>
                </div>

                {/* Features */}
                <div className="space-y-2 pt-2">
                  <h4 className="text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wide">
                    {t('onboarding:bakery_type.features_label', 'Características')}
                  </h4>
                  <ul className="space-y-1.5">
                    {type.features.map((feature, index) => (
                      <li
                        key={index}
                        className="text-sm text-[var(--text-primary)] flex items-start gap-2"
                      >
                        <span className="text-[var(--color-primary)] mt-0.5 flex-shrink-0">✓</span>
                        <span>{feature}</span>
                      </li>
                    ))}
                  </ul>
                </div>

                {/* Examples */}
                <div className="space-y-2 pt-2 border-t border-[var(--border-color)]">
                  <h4 className="text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wide">
                    {t('onboarding:bakery_type.examples_label', 'Ejemplos')}
                  </h4>
                  <div className="flex flex-wrap gap-2">
                    {type.examples.map((example, index) => (
                      <span
                        key={index}
                        className="text-xs px-2 py-1 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-full text-[var(--text-secondary)]"
                      >
                        {example}
                      </span>
                    ))}
                  </div>
                </div>
              </div>
            </button>
          );
        })}
      </div>

      {/* Additional Info */}
      {selectedType && (
        <div className="bg-[var(--color-primary)]/10 border border-[var(--color-primary)]/20 rounded-lg p-4 md:p-6">
          <div className="flex items-start gap-3">
            <div className="text-2xl md:text-3xl flex-shrink-0">
              {bakeryTypes.find(t => t.id === selectedType)?.icon}
            </div>
            <div className="space-y-2">
              <h4 className="font-semibold text-[var(--text-primary)]">
                {t('onboarding:bakery_type.selected_info_title', 'Perfecto para tu panadería')}
              </h4>
              <p className="text-sm text-[var(--text-secondary)]">
                {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-4">
        <p className="text-sm 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 className="flex justify-center pt-2">
          <Button
            onClick={handleContinue}
            disabled={!selectedType}
            size="lg"
            className="w-full sm:w-auto sm:min-w-[200px]"
          >
            {t('onboarding:bakery_type.continue_button', 'Continuar')}
          </Button>
        </div>
      </div>
    </div>
  );
};

export default BakeryTypeSelectionStep;
