import React, { useState, useEffect } from 'react';
import { Package, DollarSign, Calendar, Info, Plus, Edit, Trash2, CheckCircle, X, Save, ChevronDown, ChevronUp, AlertTriangle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { EditViewModal } from '../../ui/EditViewModal/EditViewModal';
import { SupplierResponse, SupplierPriceListResponse, SupplierPriceListUpdate } from '../../../api/types/suppliers';
import { formatters } from '../../ui/Stats/StatsPresets';
import { statusColors } from '../../../styles/colors';
import { Button } from '../../ui/Button';
import { useIngredients } from '../../../api/hooks/inventory';

interface SupplierPriceListViewModalProps {
  isOpen: boolean;
  onClose: () => void;
  supplier: SupplierResponse;
  priceLists: SupplierPriceListResponse[];
  loading?: boolean;
  tenantId: string;
  onAddPrice?: () => void;
  onEditPrice?: (priceId: string, updateData: SupplierPriceListUpdate) => Promise<void>;
  onDeletePrice?: (priceId: string) => Promise<void>;
  // Wait-for-refetch support
  waitForRefetch?: boolean;
  isRefetching?: boolean;
  onSaveComplete?: () => Promise<void>;
}

/**
 * SupplierPriceListViewModal - Card-based price list management modal
 * Follows the same UI/UX pattern as BatchModal for inventory stock management
 */
export const SupplierPriceListViewModal: React.FC<SupplierPriceListViewModalProps> = ({
  isOpen,
  onClose,
  supplier,
  priceLists = [],
  loading = false,
  tenantId,
  onAddPrice,
  onEditPrice,
  onDeletePrice,
  waitForRefetch,
  isRefetching,
  onSaveComplete
}) => {
  const { t } = useTranslation(['suppliers', 'common']);
  const [editingPrice, setEditingPrice] = useState<string | null>(null);
  const [editData, setEditData] = useState<SupplierPriceListUpdate>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isWaitingForRefetch, setIsWaitingForRefetch] = useState(false);

  // Collapsible state - start with all price entries collapsed for better UX
  const [collapsedPrices, setCollapsedPrices] = useState<Set<string>>(new Set());

  // Initialize all prices as collapsed when prices change or modal opens
  useEffect(() => {
    if (isOpen && priceLists.length > 0) {
      setCollapsedPrices(new Set(priceLists.map(p => p.id)));
    }
  }, [isOpen, priceLists]);

  // Fetch ingredients for product name display
  const { data: ingredientsData } = useIngredients(
    tenantId,
    {},
    { enabled: !!tenantId && isOpen }
  );
  const ingredients = ingredientsData || [];

  // Helper to get product name by ID
  const getProductName = (productId: string): string => {
    const product = ingredients.find(ing => ing.id === productId);
    return product?.name || 'Producto desconocido';
  };

  // Toggle price entry collapse state
  const togglePriceCollapse = (priceId: string) => {
    setCollapsedPrices(prev => {
      const next = new Set(prev);
      if (next.has(priceId)) {
        next.delete(priceId);
      } else {
        next.add(priceId);
      }
      return next;
    });
  };

  // Get price status based on validity dates and active state
  const getPriceStatus = (price: SupplierPriceListResponse) => {
    if (!price.is_active) {
      return {
        label: 'Inactivo',
        color: statusColors.cancelled.primary,
        icon: X,
        isCritical: false
      };
    }

    const today = new Date();
    const effectiveDate = price.effective_date ? new Date(price.effective_date) : null;
    const expiryDate = price.expiry_date ? new Date(price.expiry_date) : null;

    // Check if not yet effective
    if (effectiveDate && effectiveDate > today) {
      return {
        label: 'Programado',
        color: statusColors.inProgress.primary,
        icon: Calendar,
        isCritical: false
      };
    }

    // Check if expired
    if (expiryDate && expiryDate < today) {
      return {
        label: 'Vencido',
        color: statusColors.expired.primary,
        icon: AlertTriangle,
        isCritical: true
      };
    }

    // Check if expiring soon (within 30 days)
    if (expiryDate) {
      const daysUntilExpiry = Math.ceil((expiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
      if (daysUntilExpiry <= 30) {
        return {
          label: 'Próximo a Vencer',
          color: statusColors.pending.primary,
          icon: AlertTriangle,
          isCritical: false
        };
      }
    }

    return {
      label: 'Activo',
      color: statusColors.completed.primary,
      icon: CheckCircle,
      isCritical: false
    };
  };

  const handleEditStart = (price: SupplierPriceListResponse) => {
    setEditingPrice(price.id);
    // Auto-expand when editing
    setCollapsedPrices(prev => {
      const next = new Set(prev);
      next.delete(price.id);
      return next;
    });
    setEditData({
      unit_price: price.unit_price,
      unit_of_measure: price.unit_of_measure,
      minimum_order_quantity: price.minimum_order_quantity,
      effective_date: price.effective_date?.split('T')[0],
      expiry_date: price.expiry_date?.split('T')[0] || undefined,
      is_active: price.is_active,
      brand: price.brand || undefined,
      packaging_size: price.packaging_size || undefined,
      origin_country: price.origin_country || undefined,
      shelf_life_days: price.shelf_life_days || undefined,
      storage_requirements: price.storage_requirements || undefined
    });
  };

  const handleEditCancel = () => {
    setEditingPrice(null);
    setEditData({});
  };

  const handleEditSave = async (priceId: string) => {
    if (!onEditPrice) return;

    // CRITICAL: Capture editData IMMEDIATELY before any async operations
    const dataToSave = { ...editData };

    // Validate we have data to save
    if (Object.keys(dataToSave).length === 0) {
      console.error('SupplierPriceListViewModal: No edit data to save for price', priceId);
      return;
    }

    console.log('SupplierPriceListViewModal: Saving price data:', dataToSave);

    setIsSubmitting(true);
    try {
      // Execute the update mutation
      await onEditPrice(priceId, dataToSave);

      // If waitForRefetch is enabled, wait for data to refresh
      if (waitForRefetch && onSaveComplete) {
        setIsWaitingForRefetch(true);

        // Trigger the refetch
        await onSaveComplete();

        // Wait for isRefetching to become false (with timeout)
        const startTime = Date.now();
        const refetchTimeout = 3000;

        await new Promise<void>((resolve) => {
          const interval = setInterval(() => {
            const elapsed = Date.now() - startTime;

            if (elapsed >= refetchTimeout) {
              clearInterval(interval);
              console.warn('Refetch timeout reached for price update');
              resolve();
              return;
            }

            if (!isRefetching) {
              clearInterval(interval);
              resolve();
            }
          }, 100);
        });

        setIsWaitingForRefetch(false);
      }

      // Clear editing state after save (and optional refetch) completes
      setEditingPrice(null);
      setEditData({});
    } catch (error) {
      console.error('Error updating price:', error);
    } finally {
      setIsSubmitting(false);
      setIsWaitingForRefetch(false);
    }
  };

  const handleDelete = async (priceId: string) => {
    if (!onDeletePrice) return;

    const confirmed = window.confirm('¿Está seguro que desea eliminar este precio? Esta acción no se puede deshacer.');
    if (!confirmed) return;

    setIsSubmitting(true);
    try {
      await onDeletePrice(priceId);
    } catch (error) {
      console.error('Error deleting price:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const statusConfig = {
    color: statusColors.inProgress.primary,
    text: `${priceLists.length} precios`,
    icon: DollarSign
  };

  // Create card-based price list
  const priceCards = priceLists.length > 0 ? (
    <div className="space-y-4">
      {priceLists.map((price) => {
        const status = getPriceStatus(price);
        const StatusIcon = status.icon;
        const isEditing = editingPrice === price.id;
        const productName = getProductName(price.inventory_product_id);

        return (
          <div
            key={price.id}
            className="bg-[var(--surface-secondary)] rounded-lg border border-[var(--border-primary)] overflow-hidden"
            style={{
              borderColor: status.isCritical ? `${status.color}40` : undefined,
              backgroundColor: status.isCritical ? `${status.color}05` : undefined
            }}
          >
            {/* Header */}
            <div className="p-4 border-b border-[var(--border-secondary)]">
              <div className="flex items-center justify-between gap-3">
                {/* Left side: clickable area for collapse/expand */}
                <button
                  onClick={() => !isEditing && togglePriceCollapse(price.id)}
                  disabled={isEditing}
                  className="flex items-center gap-3 flex-1 min-w-0 cursor-pointer hover:opacity-80 transition-opacity disabled:cursor-default disabled:hover:opacity-100"
                  aria-expanded={!collapsedPrices.has(price.id)}
                  aria-label={`${collapsedPrices.has(price.id) ? 'Expandir' : 'Colapsar'} precio de ${productName}`}
                >
                  <div
                    className="flex-shrink-0 p-2 rounded-lg"
                    style={{ backgroundColor: `${status.color}15` }}
                  >
                    <StatusIcon
                      className="w-5 h-5"
                      style={{ color: status.color }}
                    />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="font-semibold text-[var(--text-primary)]">
                      {productName}
                    </h3>
                    <div
                      className="text-sm font-medium"
                      style={{ color: status.color }}
                    >
                      {status.label}
                    </div>
                    {/* Inline summary when collapsed */}
                    {collapsedPrices.has(price.id) && (
                      <div className="text-xs text-[var(--text-secondary)] mt-1">
                        {formatters.currency(price.unit_price)} / {price.unit_of_measure}
                        {price.expiry_date && (
                          <> • Vence: {new Date(price.expiry_date).toLocaleDateString('es-ES')}</>
                        )}
                      </div>
                    )}
                  </div>
                </button>

                {/* Right side: action buttons */}
                <div className="flex items-center gap-2 flex-shrink-0">
                  {/* Collapse/Expand chevron */}
                  {!isEditing && (
                    <button
                      onClick={() => togglePriceCollapse(price.id)}
                      className="p-2 rounded-md hover:bg-[var(--surface-tertiary)] transition-colors"
                      aria-label={collapsedPrices.has(price.id) ? 'Expandir' : 'Colapsar'}
                    >
                      {collapsedPrices.has(price.id) ? (
                        <ChevronDown className="w-5 h-5 text-[var(--text-secondary)]" />
                      ) : (
                        <ChevronUp className="w-5 h-5 text-[var(--text-secondary)]" />
                      )}
                    </button>
                  )}

                  {!isEditing && (
                    <>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleEditStart(price)}
                        disabled={isSubmitting}
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDelete(price.id)}
                        disabled={isSubmitting}
                        className="text-red-600 border-red-300 hover:bg-red-50"
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </>
                  )}

                  {isEditing && (
                    <>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={handleEditCancel}
                        disabled={isSubmitting}
                      >
                        <X className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="primary"
                        size="sm"
                        onClick={() => handleEditSave(price.id)}
                        disabled={isSubmitting}
                        isLoading={isSubmitting}
                      >
                        <Save className="w-4 h-4" />
                      </Button>
                    </>
                  )}
                </div>
              </div>
            </div>

            {/* Content - Only show when expanded */}
            {!collapsedPrices.has(price.id) && (
            <div className="p-4 space-y-4 transition-all duration-200 ease-in-out">
              {/* Pricing Information Section */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                    Precio Unitario
                  </label>
                  {isEditing ? (
                    <input
                      type="number"
                      step="0.01"
                      value={editData.unit_price || ''}
                      onChange={(e) => setEditData(prev => ({ ...prev, unit_price: Number(e.target.value) }))}
                      className="w-full px-3 py-2 border border-[var(--border-color)] bg-[var(--background-primary)] text-[var(--text-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  ) : (
                    <div className="text-lg font-bold text-[var(--text-primary)]">
                      {formatters.currency(price.unit_price)}
                    </div>
                  )}
                </div>

                <div>
                  <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                    Precio por Unidad
                  </label>
                  <div className="text-sm text-[var(--text-secondary)]">
                    {formatters.currency(price.price_per_unit)}
                  </div>
                </div>

                <div>
                  <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                    Unidad de Medida
                  </label>
                  {isEditing ? (
                    <input
                      type="text"
                      value={editData.unit_of_measure || ''}
                      onChange={(e) => setEditData(prev => ({ ...prev, unit_of_measure: e.target.value }))}
                      className="w-full px-3 py-2 border border-[var(--border-color)] bg-[var(--background-primary)] text-[var(--text-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  ) : (
                    <div className="text-sm text-[var(--text-secondary)]">
                      {price.unit_of_measure}
                    </div>
                  )}
                </div>

                <div>
                  <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                    Cantidad Mínima de Pedido
                  </label>
                  {isEditing ? (
                    <input
                      type="number"
                      value={editData.minimum_order_quantity || ''}
                      onChange={(e) => setEditData(prev => ({ ...prev, minimum_order_quantity: Number(e.target.value) || null }))}
                      placeholder="Opcional"
                      className="w-full px-3 py-2 border border-[var(--border-color)] bg-[var(--background-primary)] text-[var(--text-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  ) : (
                    <div className="text-sm text-[var(--text-secondary)]">
                      {price.minimum_order_quantity || 'N/A'}
                    </div>
                  )}
                </div>
              </div>

              {/* Product Details Section */}
              {(price.product_code || price.brand || price.packaging_size) && (
                <div className="pt-3 border-t border-[var(--border-secondary)]">
                  <div className="text-sm font-medium text-[var(--text-tertiary)] mb-3">
                    Detalles del Producto
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    {price.product_code && (
                      <div>
                        <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                          Código de Producto
                        </label>
                        <div className="text-sm text-[var(--text-secondary)]">
                          {price.product_code}
                        </div>
                      </div>
                    )}

                    <div>
                      <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                        Marca
                      </label>
                      {isEditing ? (
                        <input
                          type="text"
                          value={editData.brand || ''}
                          onChange={(e) => setEditData(prev => ({ ...prev, brand: e.target.value || null }))}
                          placeholder="Marca"
                          className="w-full px-3 py-2 border border-[var(--border-color)] bg-[var(--background-primary)] text-[var(--text-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                        />
                      ) : (
                        <div className="text-sm text-[var(--text-secondary)]">
                          {price.brand || 'N/A'}
                        </div>
                      )}
                    </div>

                    <div>
                      <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                        Tamaño del Empaque
                      </label>
                      {isEditing ? (
                        <input
                          type="text"
                          value={editData.packaging_size || ''}
                          onChange={(e) => setEditData(prev => ({ ...prev, packaging_size: e.target.value || null }))}
                          placeholder="Ej: 25kg"
                          className="w-full px-3 py-2 border border-[var(--border-color)] bg-[var(--background-primary)] text-[var(--text-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                        />
                      ) : (
                        <div className="text-sm text-[var(--text-secondary)]">
                          {price.packaging_size || 'N/A'}
                        </div>
                      )}
                    </div>

                    {price.origin_country && (
                      <div>
                        <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                          País de Origen
                        </label>
                        {isEditing ? (
                          <input
                            type="text"
                            value={editData.origin_country || ''}
                            onChange={(e) => setEditData(prev => ({ ...prev, origin_country: e.target.value || null }))}
                            placeholder="País"
                            className="w-full px-3 py-2 border border-[var(--border-color)] bg-[var(--background-primary)] text-[var(--text-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                          />
                        ) : (
                          <div className="text-sm text-[var(--text-secondary)]">
                            {price.origin_country}
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* Validity Section */}
              <div className="pt-3 border-t border-[var(--border-secondary)]">
                <div className="text-sm font-medium text-[var(--text-tertiary)] mb-3">
                  Vigencia
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                  <div>
                    <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                      Fecha de Vigencia
                    </label>
                    {isEditing ? (
                      <input
                        type="date"
                        value={editData.effective_date ? new Date(editData.effective_date).toISOString().split('T')[0] : ''}
                        onChange={(e) => setEditData(prev => ({ ...prev, effective_date: e.target.value }))}
                        className="w-full px-3 py-2 border border-[var(--border-color)] bg-[var(--background-primary)] text-[var(--text-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    ) : (
                      <div className="text-sm text-[var(--text-secondary)]">
                        {price.effective_date
                          ? new Date(price.effective_date).toLocaleDateString('es-ES')
                          : 'N/A'
                        }
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                      Fecha de Vencimiento
                    </label>
                    {isEditing ? (
                      <input
                        type="date"
                        value={editData.expiry_date ? new Date(editData.expiry_date).toISOString().split('T')[0] : ''}
                        onChange={(e) => setEditData(prev => ({ ...prev, expiry_date: e.target.value || null }))}
                        className="w-full px-3 py-2 border border-[var(--border-color)] bg-[var(--background-primary)] text-[var(--text-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    ) : (
                      <div className="text-sm text-[var(--text-secondary)]">
                        {price.expiry_date
                          ? new Date(price.expiry_date).toLocaleDateString('es-ES')
                          : 'Sin vencimiento'
                        }
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                      Estado
                    </label>
                    {isEditing ? (
                      <select
                        value={editData.is_active ? 'active' : 'inactive'}
                        onChange={(e) => setEditData(prev => ({ ...prev, is_active: e.target.value === 'active' }))}
                        className="w-full px-3 py-2 border border-[var(--border-color)] bg-[var(--background-primary)] text-[var(--text-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      >
                        <option value="active">Activo</option>
                        <option value="inactive">Inactivo</option>
                      </select>
                    ) : (
                      <div className="text-sm text-[var(--text-secondary)]">
                        {price.is_active ? 'Activo' : 'Inactivo'}
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Storage Section */}
              {(price.shelf_life_days || price.storage_requirements) && (
                <div className="pt-3 border-t border-[var(--border-secondary)]">
                  <div className="text-sm font-medium text-[var(--text-tertiary)] mb-3">
                    Almacenamiento
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    {price.shelf_life_days && (
                      <div>
                        <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                          Vida Útil (días)
                        </label>
                        {isEditing ? (
                          <input
                            type="number"
                            value={editData.shelf_life_days || ''}
                            onChange={(e) => setEditData(prev => ({ ...prev, shelf_life_days: Number(e.target.value) || null }))}
                            placeholder="Días"
                            className="w-full px-3 py-2 border border-[var(--border-color)] bg-[var(--background-primary)] text-[var(--text-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                          />
                        ) : (
                          <div className="text-sm text-[var(--text-secondary)]">
                            {price.shelf_life_days} días
                          </div>
                        )}
                      </div>
                    )}

                    {(price.storage_requirements || isEditing) && (
                      <div className={price.shelf_life_days ? '' : 'col-span-2'}>
                        <label className="text-xs font-medium text-[var(--text-tertiary)] mb-1 block">
                          Requisitos de Almacenamiento
                        </label>
                        {isEditing ? (
                          <textarea
                            value={editData.storage_requirements || ''}
                            onChange={(e) => setEditData(prev => ({ ...prev, storage_requirements: e.target.value || null }))}
                            placeholder="Requisitos especiales..."
                            rows={2}
                            className="w-full px-3 py-2 border border-[var(--border-color)] bg-[var(--background-primary)] text-[var(--text-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                          />
                        ) : (
                          price.storage_requirements ? (
                            <div className="p-2 bg-[var(--surface-tertiary)] rounded-md">
                              <div className="text-xs text-[var(--text-secondary)] italic">
                                "{price.storage_requirements}"
                              </div>
                            </div>
                          ) : (
                            <div className="text-sm text-[var(--text-secondary)]">
                              N/A
                            </div>
                          )
                        )}
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
            )}
          </div>
        );
      })}
    </div>
  ) : (
    <div className="text-center py-12 text-[var(--text-secondary)]">
      <DollarSign className="w-16 h-16 mx-auto mb-4 opacity-30" />
      <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
        No hay precios registrados
      </h3>
      <p className="text-sm mb-6">
        Agregue precios para los productos que suministra este proveedor
      </p>
      {onAddPrice && (
        <Button
          variant="primary"
          onClick={onAddPrice}
          className="inline-flex items-center gap-2"
        >
          <Plus className="w-4 h-4" />
          Agregar Primer Precio
        </Button>
      )}
    </div>
  );

  const sections = [
    {
      title: 'Lista de Precios',
      icon: DollarSign,
      fields: [
        {
          label: '',
          value: priceCards,
          span: 2 as const
        }
      ]
    }
  ];

  const actions = [];

  // Only show "Agregar Precio" button when there are existing prices
  if (onAddPrice && priceLists.length > 0) {
    actions.push({
      label: 'Agregar Precio',
      icon: Plus,
      variant: 'primary' as const,
      onClick: onAddPrice
    });
  }

  return (
    <EditViewModal
      isOpen={isOpen}
      onClose={onClose}
      mode="view"
      title={`Lista de Precios - ${supplier.name}`}
      subtitle={`${priceLists.length} precios registrados`}
      statusIndicator={statusConfig}
      sections={sections}
      size="lg"
      loading={loading || isSubmitting || isWaitingForRefetch}
      showDefaultActions={false}
      actions={actions}
    />
  );
};

export default SupplierPriceListViewModal;
