import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { AdvancedOptionsSection } from '../../../ui/AdvancedOptionsSection';
import Tooltip from '../../../ui/Tooltip/Tooltip';
import { Info, Package, ShoppingBag } from 'lucide-react';
import { useTenantCurrency } from '../../../../hooks/useTenantCurrency';

// STEP 1: Product Type Selection with advanced fields
const ProductTypeStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  // New architecture: access data from dataRef.current
  const data = dataRef?.current || {};
  const { t } = useTranslation('wizards');

  const handleFieldChange = (field: string, value: any) => {
    onDataChange?.({ ...data, [field]: value });
  };

  const handleTypeSelect = (type: string) => {
    onDataChange?.({ ...data, productType: type });
  };

  return (
    <div className="space-y-6">
      {/* Product Type Selection */}
      <div>
        <label className="block text-sm font-medium text-[var(--text-secondary)] mb-3">
          {t('inventory.fields.productType')} *
        </label>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Ingredient Card */}
          <button
            type="button"
            onClick={() => handleTypeSelect('ingredient')}
            className={`p-6 border-2 rounded-lg transition-all text-left ${
              data.productType === 'ingredient'
                ? 'border-[var(--color-primary)] bg-[var(--color-primary)]/5 shadow-md'
                : 'border-[var(--border-secondary)] hover:border-[var(--color-primary)]/50'
            }`}
          >
            <div className="flex items-start gap-4">
              <div
                className={`p-3 rounded-lg ${
                  data.productType === 'ingredient'
                    ? 'bg-[var(--color-primary)] text-white'
                    : 'bg-[var(--bg-secondary)] text-[var(--text-tertiary)]'
                }`}
              >
                <Package className="w-6 h-6" />
              </div>
              <div className="flex-1">
                <h3 className="font-semibold text-[var(--text-primary)] mb-1">
                  {t('inventory.productTypes.ingredient')}
                </h3>
                <p className="text-sm text-[var(--text-secondary)]">
                  {t('inventory.typeDescriptions.ingredient', 'Raw materials and ingredients used in recipes')}
                </p>
              </div>
            </div>
          </button>

          {/* Finished Product Card */}
          <button
            type="button"
            onClick={() => handleTypeSelect('finished_product')}
            className={`p-6 border-2 rounded-lg transition-all text-left ${
              data.productType === 'finished_product'
                ? 'border-[var(--color-primary)] bg-[var(--color-primary)]/5 shadow-md'
                : 'border-[var(--border-secondary)] hover:border-[var(--color-primary)]/50'
            }`}
          >
            <div className="flex items-start gap-4">
              <div
                className={`p-3 rounded-lg ${
                  data.productType === 'finished_product'
                    ? 'bg-[var(--color-primary)] text-white'
                    : 'bg-[var(--bg-secondary)] text-[var(--text-tertiary)]'
                }`}
              >
                <ShoppingBag className="w-6 h-6" />
              </div>
              <div className="flex-1">
                <h3 className="font-semibold text-[var(--text-primary)] mb-1">
                  {t('inventory.productTypes.finished_product')}
                </h3>
                <p className="text-sm text-[var(--text-secondary)]">
                  {t('inventory.typeDescriptions.finished_product', 'Final products ready for sale or consumption')}
                </p>
              </div>
            </div>
          </button>
        </div>
      </div>

      {/* Advanced Fields Section */}
      <AdvancedOptionsSection
        title={t('inventory.sections.additionalInformation')}
        description={t('inventory.sections.additionalInformationDescription', 'Optional product identifiers')}
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* SKU */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('inventory.fields.sku')}
              <Tooltip content={t('inventory.fields.skuTooltip')}>
                <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
              </Tooltip>
            </label>
            <input
              type="text"
              value={data.sku || ''}
              onChange={(e) => handleFieldChange('sku', e.target.value)}
              placeholder={t('inventory.fields.skuPlaceholder')}
              className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            />
          </div>

          {/* Barcode */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('inventory.fields.barcode')}
            </label>
            <input
              type="text"
              value={data.barcode || ''}
              onChange={(e) => handleFieldChange('barcode', e.target.value)}
              placeholder={t('inventory.fields.barcodePlaceholder')}
              className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            />
          </div>

          {/* Brand */}
          <div className="md:col-span-2">
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('inventory.fields.brand')}
            </label>
            <input
              type="text"
              value={data.brand || ''}
              onChange={(e) => handleFieldChange('brand', e.target.value)}
              placeholder={t('inventory.fields.brandPlaceholder')}
              className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            />
          </div>
        </div>
      </AdvancedOptionsSection>
    </div>
  );
};

// STEP 2: Basic Information with advanced fields
const BasicInfoStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const data = dataRef?.current || {};
  const { t } = useTranslation('wizards');

  const handleFieldChange = (field: string, value: any) => {
    onDataChange?.({ ...data, [field]: value });
  };

  return (
    <div className="space-y-6">
      {/* Required Fields */}
      <div>
        <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
          {t('inventory.fields.name')} *
        </label>
        <input
          type="text"
          value={data.name || ''}
          onChange={(e) => handleFieldChange('name', e.target.value)}
          placeholder={t('inventory.fields.namePlaceholder')}
          className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
          {data.productType === 'ingredient'
            ? t('inventory.fields.ingredientCategory')
            : t('inventory.fields.productCategory')}{' '}
          *
        </label>
        <select
          value={
            data.productType === 'ingredient'
              ? data.ingredientCategory || ''
              : data.productCategory || ''
          }
          onChange={(e) =>
            handleFieldChange(
              data.productType === 'ingredient' ? 'ingredientCategory' : 'productCategory',
              e.target.value
            )
          }
          className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
        >
          {data.productType === 'ingredient' ? (
            <>
              <option value="">{t('inventory.ingredientCategories.select')}</option>
              <option value="flour">{t('inventory.ingredientCategories.flour')}</option>
              <option value="yeast">{t('inventory.ingredientCategories.yeast')}</option>
              <option value="dairy">{t('inventory.ingredientCategories.dairy')}</option>
              <option value="eggs">{t('inventory.ingredientCategories.eggs')}</option>
              <option value="sugar">{t('inventory.ingredientCategories.sugar')}</option>
              <option value="fats">{t('inventory.ingredientCategories.fats')}</option>
              <option value="salt">{t('inventory.ingredientCategories.salt')}</option>
              <option value="spices">{t('inventory.ingredientCategories.spices')}</option>
              <option value="additives">{t('inventory.ingredientCategories.additives')}</option>
              <option value="packaging">{t('inventory.ingredientCategories.packaging')}</option>
              <option value="cleaning">{t('inventory.ingredientCategories.cleaning')}</option>
              <option value="other">{t('inventory.ingredientCategories.other')}</option>
            </>
          ) : (
            <>
              <option value="">{t('inventory.productCategories.select')}</option>
              <option value="bread">{t('inventory.productCategories.bread')}</option>
              <option value="croissants">{t('inventory.productCategories.croissants')}</option>
              <option value="pastries">{t('inventory.productCategories.pastries')}</option>
              <option value="cakes">{t('inventory.productCategories.cakes')}</option>
              <option value="cookies">{t('inventory.productCategories.cookies')}</option>
              <option value="muffins">{t('inventory.productCategories.muffins')}</option>
              <option value="sandwiches">{t('inventory.productCategories.sandwiches')}</option>
              <option value="seasonal">{t('inventory.productCategories.seasonal')}</option>
              <option value="beverages">{t('inventory.productCategories.beverages')}</option>
              <option value="other_products">{t('inventory.productCategories.other_products')}</option>
            </>
          )}
        </select>
      </div>

      {/* Advanced Fields Section */}
      <AdvancedOptionsSection
        title={t('inventory.sections.additionalDetails')}
        description={t('inventory.sections.additionalDetailsDescription', 'Optional product details')}
      >
        <div className="space-y-4">
          {/* Description */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('inventory.fields.description')}
            </label>
            <textarea
              value={data.description || ''}
              onChange={(e) => handleFieldChange('description', e.target.value)}
              placeholder={t('inventory.fields.descriptionPlaceholder')}
              rows={3}
              className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            />
          </div>

          {/* Package Size */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('inventory.fields.packageSize')}
            </label>
            <input
              type="text"
              value={data.packageSize || ''}
              onChange={(e) => handleFieldChange('packageSize', e.target.value)}
              placeholder={t('inventory.fields.packageSizePlaceholder')}
              className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            />
          </div>

          {/* Is Perishable */}
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={data.isPerishable ?? true}
              onChange={(e) => handleFieldChange('isPerishable', e.target.checked)}
              className="rounded border-[var(--border-secondary)] text-[var(--color-primary)] focus:ring-[var(--color-primary)]"
            />
            <label className="text-sm text-[var(--text-secondary)]">
              {t('inventory.fields.isPerishable')}
            </label>
          </div>

          {/* Shelf Life Days */}
          {(data.isPerishable ?? true) && (
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('inventory.fields.shelfLifeDays')}
              </label>
              <input
                type="number"
                value={data.shelfLifeDays || ''}
                onChange={(e) => handleFieldChange('shelfLifeDays', e.target.value)}
                placeholder="365"
                min="0"
                className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
              />
            </div>
          )}

          {/* Allergen Info */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('inventory.fields.allergenInfo')}
              <Tooltip content={t('tooltips.allergenInfo')}>
                <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
              </Tooltip>
            </label>
            <input
              type="text"
              value={data.allergenInfo || ''}
              onChange={(e) => handleFieldChange('allergenInfo', e.target.value)}
              placeholder={t('inventory.fields.allergenInfoPlaceholder')}
              className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            />
          </div>
        </div>
      </AdvancedOptionsSection>
    </div>
  );
};

// STEP 3: Initial Stock/Lots Configuration
const StockConfigStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const data = dataRef?.current || {};
  const { t } = useTranslation('wizards');
  const { currencySymbol } = useTenantCurrency();
  const [lots, setLots] = useState<any[]>(data.initialLots || []);

  const handleFieldChange = (field: string, value: any) => {
    onDataChange?.({ ...data, [field]: value });
  };

  const handleAddLot = () => {
    const newLot = {
      id: Date.now(),
      quantity: '',
      unitCost: '',
      expirationDate: '',
      lotNumber: `LOT-${Date.now()}`,
      location: '',
    };
    const updatedLots = [...lots, newLot];
    setLots(updatedLots);
    onDataChange?.({ ...data, initialLots: updatedLots });
  };

  const handleRemoveLot = (lotId: number) => {
    const updatedLots = lots.filter(lot => lot.id !== lotId);
    setLots(updatedLots);
    onDataChange?.({ ...data, initialLots: updatedLots });
  };

  const handleLotChange = (lotId: number, field: string, value: any) => {
    const updatedLots = lots.map(lot =>
      lot.id === lotId ? { ...lot, [field]: value } : lot
    );
    setLots(updatedLots);
    onDataChange?.({ ...data, initialLots: updatedLots });
  };

  const totalQuantity = lots.reduce((sum, lot) => sum + (parseFloat(lot.quantity) || 0), 0);
  const totalValue = lots.reduce((sum, lot) => {
    const qty = parseFloat(lot.quantity) || 0;
    const cost = parseFloat(lot.unitCost) || 0;
    return sum + (qty * cost);
  }, 0);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <Package className="w-12 h-12 mx-auto mb-3 text-[var(--color-primary)]" />
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
          {t('inventory.steps.initialStock', 'Stock Inicial')}
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          {t('inventory.initialStockDescription', 'Agrega uno o más lotes para registrar el inventario inicial')}
        </p>
      </div>

      {/* Product Summary */}
      <div className="bg-gradient-to-br from-[var(--color-primary)]/5 to-[var(--color-primary)]/10 border border-[var(--color-primary)]/20 rounded-lg p-4">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
          <div>
            <span className="text-[var(--text-tertiary)] block mb-1">{t('inventory.stockConfig.product')}</span>
            <span className="font-medium text-[var(--text-primary)]">{data.name || 'N/A'}</span>
          </div>
          <div>
            <span className="text-[var(--text-tertiary)] block mb-1">{t('inventory.fields.unitOfMeasure')}</span>
            <span className="font-medium text-[var(--text-primary)]">{data.unitOfMeasure || 'N/A'}</span>
          </div>
          <div>
            <span className="text-[var(--text-tertiary)] block mb-1">{t('inventory.stockConfig.totalQuantity')}</span>
            <span className="font-medium text-[var(--color-primary)]">{totalQuantity.toFixed(2)}</span>
          </div>
          <div>
            <span className="text-[var(--text-tertiary)] block mb-1">{t('inventory.stockConfig.totalValue')}</span>
            <span className="font-medium text-green-600">{currencySymbol}{totalValue.toFixed(2)}</span>
          </div>
        </div>
      </div>

      {/* Unit of Measure - Required (moved from previous step conceptually but kept here) */}
      {!data.unitOfMeasure && (
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('inventory.fields.unitOfMeasure')} *
          </label>
          <select
            value={data.unitOfMeasure || ''}
            onChange={(e) => handleFieldChange('unitOfMeasure', e.target.value)}
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
          >
            <option value="">{t('inventory.units.select')}</option>
            <option value="kg">{t('inventory.units.kg')}</option>
            <option value="g">{t('inventory.units.g')}</option>
            <option value="l">{t('inventory.units.l')}</option>
            <option value="ml">{t('inventory.units.ml')}</option>
            <option value="units">{t('inventory.units.units')}</option>
            <option value="dozen">{t('inventory.units.dozen')}</option>
            <option value="lb">{t('inventory.units.lb')}</option>
            <option value="oz">{t('inventory.units.oz')}</option>
          </select>
        </div>
      )}

      {/* Lots List */}
      {lots.length > 0 && (
        <div className="space-y-4">
          <h4 className="text-sm font-semibold text-[var(--text-primary)] flex items-center gap-2">
            <ShoppingBag className="w-4 h-4" />
            {t('inventory.stockConfig.lotsRegistered')} ({lots.length})
          </h4>
          {lots.map((lot, index) => (
            <div
              key={lot.id}
              className="border border-[var(--border-secondary)] rounded-lg p-4 bg-[var(--bg-secondary)]/30 space-y-3"
            >
              <div className="flex items-center justify-between mb-3">
                <span className="text-sm font-semibold text-[var(--text-primary)]">
                  {t('inventory.stockConfig.lot')} #{index + 1}
                </span>
                <button
                  onClick={() => handleRemoveLot(lot.id)}
                  className="text-red-500 hover:text-red-700 transition-colors p-1"
                >
                  <span className="text-xs">{t('inventory.stockConfig.remove')}</span>
                </button>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                {/* Quantity */}
                <div>
                  <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                    {t('inventory.stockConfig.quantity')} *
                  </label>
                  <input
                    type="number"
                    value={lot.quantity}
                    onChange={(e) => handleLotChange(lot.id, 'quantity', e.target.value)}
                    placeholder="100"
                    step="0.01"
                    min="0"
                    className="w-full px-2 py-1.5 text-sm border border-[var(--border-secondary)] rounded focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
                  />
                </div>

                {/* Unit Cost */}
                <div>
                  <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                    {t('inventory.stockConfig.unitCost')} ({currencySymbol})
                  </label>
                  <input
                    type="number"
                    value={lot.unitCost}
                    onChange={(e) => handleLotChange(lot.id, 'unitCost', e.target.value)}
                    placeholder="0.00"
                    step="0.01"
                    min="0"
                    className="w-full px-2 py-1.5 text-sm border border-[var(--border-secondary)] rounded focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
                  />
                </div>

                {/* Lot Number */}
                <div>
                  <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                    {t('inventory.stockConfig.lotNumber')}
                  </label>
                  <input
                    type="text"
                    value={lot.lotNumber}
                    onChange={(e) => handleLotChange(lot.id, 'lotNumber', e.target.value)}
                    placeholder="LOT-001"
                    className="w-full px-2 py-1.5 text-sm border border-[var(--border-secondary)] rounded focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
                  />
                </div>

                {/* Expiration Date */}
                <div>
                  <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                    {t('inventory.stockConfig.expirationDate')}
                  </label>
                  <input
                    type="date"
                    value={lot.expirationDate}
                    onChange={(e) => handleLotChange(lot.id, 'expirationDate', e.target.value)}
                    className="w-full px-2 py-1.5 text-sm border border-[var(--border-secondary)] rounded focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
                  />
                </div>

                {/* Location */}
                <div className="md:col-span-2">
                  <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                    {t('inventory.stockConfig.location')}
                  </label>
                  <input
                    type="text"
                    value={lot.location}
                    onChange={(e) => handleLotChange(lot.id, 'location', e.target.value)}
                    placeholder="Ej: Almacén A, Estante 3"
                    className="w-full px-2 py-1.5 text-sm border border-[var(--border-secondary)] rounded focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
                  />
                </div>
              </div>

              {/* Lot Total */}
              {lot.quantity && lot.unitCost && (
                <div className="text-xs text-[var(--text-tertiary)] pt-2 border-t border-[var(--border-secondary)]">
                  {t('inventory.stockConfig.lotValue')} <span className="font-semibold text-green-600">
                    {currencySymbol}{(parseFloat(lot.quantity) * parseFloat(lot.unitCost)).toFixed(2)}
                  </span>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Add Lot Button */}
      <button
        onClick={handleAddLot}
        className="w-full py-3 border-2 border-dashed border-[var(--color-primary)] text-[var(--color-primary)] rounded-lg hover:bg-[var(--color-primary)]/5 transition-colors font-medium inline-flex items-center justify-center gap-2"
      >
        <Package className="w-5 h-5" />
        {lots.length === 0 ? t('inventory.stockConfig.addInitialLot') : t('inventory.stockConfig.addAnotherLot')}
      </button>

      {/* Skip Option */}
      {lots.length === 0 && (
        <p className="text-xs text-center text-[var(--text-tertiary)] italic">
          {t('inventory.stockConfig.skipMessage')}
        </p>
      )}
    </div>
  );
};

export const InventoryWizardSteps = (
  dataRef: React.MutableRefObject<Record<string, any>>,
  setData: (data: Record<string, any>) => void
): WizardStep[] => {
  // New architecture: return direct component references instead of arrow functions
  // dataRef and onDataChange are now passed through WizardModal props
  return [
    {
      id: 'product-type',
      title: 'inventory.steps.productType',
      component: ProductTypeStep,
      validate: () => {
        return !!dataRef.current.productType;
      },
    },
    {
      id: 'basic-info',
      title: 'inventory.steps.basicInfo',
      component: BasicInfoStep,
      validate: () => {
        const category =
          dataRef.current.productType === 'ingredient' ? dataRef.current.ingredientCategory : dataRef.current.productCategory;
        return !!(dataRef.current.name && dataRef.current.name.trim().length >= 2 && category);
      },
    },
    {
      id: 'stock-config',
      title: 'inventory.steps.stockConfig',
      component: StockConfigStep,
      validate: () => {
        // Step is optional - user can skip if not adding initial lots
        // Only validate that if lots are added, they have required fields
        const lots = dataRef.current.initialLots || [];
        if (lots.length === 0) {
          return true; // No lots, can proceed
        }
        // If lots exist, validate they have quantity and unit cost
        return lots.every((lot: any) => {
          const hasQuantity = lot.quantity && parseFloat(lot.quantity) > 0;
          const hasUnitCost = lot.unitCost && parseFloat(lot.unitCost) >= 0;
          return hasQuantity && hasUnitCost;
        });
      },
    },
  ];
};
