import React from 'react';
import { useTranslation } from 'react-i18next';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { Wrench } from 'lucide-react';

const EquipmentDetailsStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const { t } = useTranslation('wizards');
  const data = dataRef?.current || {};

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

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <Wrench 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('equipment.equipmentDetails')}</h3>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">{t('equipment.fields.type')} *</label>
          <select
            value={data.type || 'oven'}
            onChange={(e) => handleFieldChange('type', 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="oven">{t('equipment.types.oven')}</option>
            <option value="mixer">{t('equipment.types.mixer')}</option>
            <option value="proofer">{t('equipment.types.proofer')}</option>
            <option value="refrigerator">{t('equipment.types.refrigerator')}</option>
            <option value="other">{t('equipment.types.other')}</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">{t('equipment.fields.brand')}</label>
          <input
            type="text"
            value={data.brand || ''}
            onChange={(e) => handleFieldChange('brand', e.target.value)}
            placeholder={t('equipment.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>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">{t('equipment.fields.location')}</label>
          <input
            type="text"
            value={data.location || ''}
            onChange={(e) => handleFieldChange('location', e.target.value)}
            placeholder={t('equipment.fields.locationPlaceholder')}
            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">{t('equipment.fields.purchaseDate')}</label>
          <input
            type="date"
            value={data.purchaseDate || ''}
            onChange={(e) => handleFieldChange('purchaseDate', 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)]"
          />
        </div>
      </div>
    </div>
  );
};

export const EquipmentWizardSteps = (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: 'equipment-details',
      title: 'wizards:equipment.steps.equipmentDetails',
      description: 'wizards:equipment.steps.equipmentDetailsDescription',
      component: EquipmentDetailsStep,
      validate: async () => {
        const { useTenant } = await import('../../../../stores/tenant.store');
        const { equipmentService } = await import('../../../../api/services/equipment');
        const { showToast } = await import('../../../../utils/toast');
        const i18next = (await import('i18next')).default;

        const data = dataRef.current;
        const { currentTenant } = useTenant.getState();

        if (!currentTenant?.id) {
          showToast.error(i18next.t('wizards:equipment.messages.errorGettingTenant'));
          return false;
        }

        try {
          const equipmentCreateData: any = {
            name: `${data.type || 'oven'} - ${data.brand || i18next.t('wizards:equipment.messages.noBrand')}`,
            type: data.type || 'oven',
            model: data.brand || '',
            serialNumber: data.model || '',
            location: data.location || '',
            status: data.status || 'active',
            installDate: data.purchaseDate || new Date().toISOString().split('T')[0],
            lastMaintenance: new Date().toISOString().split('T')[0],
            nextMaintenance: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
            maintenanceInterval: 30,
            is_active: true
          };

          await equipmentService.createEquipment(currentTenant.id, equipmentCreateData);
          showToast.success(i18next.t('wizards:equipment.messages.successCreate'));
          return true;
        } catch (err: any) {
          console.error('Error creating equipment:', err);
          const errorMessage = err.response?.data?.detail || i18next.t('wizards:equipment.messages.errorCreate');
          showToast.error(errorMessage);
          return false;
        }
      },
    },
  ];
};
