import React from 'react';
import { BaseDeleteModal } from '../../ui';
import { RecipeResponse } from '../../../api/types/recipes';
import { useTranslation } from 'react-i18next';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { useRecipeDeletionSummary } from '../../../api/hooks/recipes';

interface DeleteRecipeModalProps {
  isOpen: boolean;
  onClose: () => void;
  recipe: RecipeResponse | null;
  onSoftDelete: (recipeId: string) => Promise<void>;
  onHardDelete: (recipeId: string) => Promise<void>;
  isLoading?: boolean;
}

/**
 * Modal for recipe deletion with soft/hard delete options
 * - Soft delete: Archive recipe (reversible)
 * - Hard delete: Permanent deletion with dependency checking
 */
export const DeleteRecipeModal: React.FC<DeleteRecipeModalProps> = ({
  isOpen,
  onClose,
  recipe,
  onSoftDelete,
  onHardDelete,
  isLoading = false,
}) => {
  const { t } = useTranslation(['recipes', 'common']);
  const currentTenant = useCurrentTenant();

  // Fetch deletion summary for dependency checking
  const { data: deletionSummary, isLoading: summaryLoading } = useRecipeDeletionSummary(
    currentTenant?.id || '',
    recipe?.id || '',
    {
      enabled: isOpen && !!recipe,
    }
  );

  if (!recipe) return null;

  // Build dependency check warnings
  const dependencyWarnings: string[] = [];
  if (deletionSummary) {
    if (deletionSummary.production_batches_count > 0) {
      dependencyWarnings.push(
        t('recipes:delete.batches_affected',
          { count: deletionSummary.production_batches_count },
          `${deletionSummary.production_batches_count} lotes de producción afectados`
        )
      );
    }
    if (deletionSummary.affected_orders_count > 0) {
      dependencyWarnings.push(
        t('recipes:delete.orders_affected',
          { count: deletionSummary.affected_orders_count },
          `${deletionSummary.affected_orders_count} pedidos afectados`
        )
      );
    }
    if (deletionSummary.warnings && deletionSummary.warnings.length > 0) {
      dependencyWarnings.push(...deletionSummary.warnings);
    }
  }

  // Build hard delete warning items
  const hardDeleteItems = [
    t('recipes:delete.hard_warning_1', 'La receta y toda su información'),
    t('recipes:delete.hard_warning_2', 'Todos los ingredientes asociados'),
  ];

  if (deletionSummary) {
    if (deletionSummary.production_batches_count > 0) {
      hardDeleteItems.push(
        t('recipes:delete.batches_affected',
          { count: deletionSummary.production_batches_count },
          `${deletionSummary.production_batches_count} lotes de producción`
        )
      );
    }
    if (deletionSummary.affected_orders_count > 0) {
      hardDeleteItems.push(
        t('recipes:delete.orders_affected',
          { count: deletionSummary.affected_orders_count },
          `${deletionSummary.affected_orders_count} pedidos afectados`
        )
      );
    }
  }

  return (
    <BaseDeleteModal
      isOpen={isOpen}
      onClose={onClose}
      entity={recipe}
      onSoftDelete={onSoftDelete}
      onHardDelete={onHardDelete}
      isLoading={isLoading}
      title={t('recipes:delete.title', 'Eliminar Receta')}
      getEntityId={(rec) => rec.id}
      getEntityDisplay={(rec) => ({
        primaryText: rec.name,
        secondaryText: `${t('recipes:delete.recipe_code', 'Código')}: ${rec.recipe_code || 'N/A'} • ${t('recipes:delete.recipe_category', 'Categoría')}: ${rec.category}`,
      })}
      softDeleteOption={{
        title: t('recipes:delete.soft_delete', 'Archivar (Recomendado)'),
        description: t('recipes:delete.soft_explanation', 'La receta se marca como archivada pero conserva todo su historial. Ideal para recetas fuera de uso temporal.'),
        benefits: t('recipes:delete.soft_benefits', '✓ Reversible • ✓ Conserva historial • ✓ Conserva datos'),
      }}
      hardDeleteOption={{
        title: t('recipes:delete.hard_delete', 'Eliminar Permanentemente'),
        description: t('recipes:delete.hard_explanation', 'Elimina completamente la receta y todos sus datos asociados. Use solo para datos erróneos o pruebas.'),
        benefits: t('recipes:delete.hard_risks', '⚠️ No reversible • ⚠️ Elimina historial • ⚠️ Elimina todos los datos'),
        enabled: true,
      }}
      softDeleteWarning={{
        title: t('recipes:delete.soft_info_title', 'ℹ️ Esta acción archivará la receta:'),
        items: [
          t('recipes:delete.soft_info_1', 'La receta cambiará a estado ARCHIVADO'),
          t('recipes:delete.soft_info_2', 'No aparecerá en listas activas'),
          t('recipes:delete.soft_info_3', 'Se conserva todo el historial y datos'),
          t('recipes:delete.soft_info_4', 'Se puede reactivar posteriormente'),
        ],
      }}
      hardDeleteWarning={{
        title: t('recipes:delete.hard_warning_title', '⚠️ Esta acción eliminará permanentemente:'),
        items: hardDeleteItems,
        footer: t('recipes:delete.irreversible', 'Esta acción NO se puede deshacer'),
      }}
      dependencyCheck={{
        isLoading: summaryLoading,
        canDelete: deletionSummary?.can_delete !== false,
        warnings: dependencyWarnings,
      }}
      requireConfirmText={true}
      confirmText="ELIMINAR"
      showSuccessScreen={true}
      successTitle={t('recipes:delete.success_soft_title', 'Receta Archivada')}
      getSuccessMessage={(rec, mode) =>
        mode === 'hard'
          ? t('recipes:delete.recipe_deleted', { name: rec.name })
          : t('recipes:delete.recipe_archived', { name: rec.name })
      }
      autoCloseDelay={1500}
    />
  );
};
