/**
 * PendingPurchasesBlock - Block 2: "Compras Pendientes"
 *
 * Displays pending purchase orders awaiting approval:
 * - PO number, supplier, amount
 * - AI reasoning for why the PO was created
 * - Inline actions: Approve, Reject, View Details
 */

import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Brain,
  Check,
  CheckCircle2,
  ChevronDown,
  ChevronUp,
  Eye,
  ShoppingCart,
  X,
} from 'lucide-react';
import { useTenantCurrency } from '../../../hooks/useTenantCurrency';

interface PendingPurchasesBlockProps {
  pendingPOs: any[];
  onApprove?: (poId: string) => Promise<void>;
  onReject?: (poId: string, reason: string) => Promise<void>;
  onViewDetails?: (poId: string) => void;
  loading?: boolean;
}

export function PendingPurchasesBlock({
  pendingPOs = [],
  onApprove,
  onReject,
  onViewDetails,
  loading,
}: PendingPurchasesBlockProps) {
  const { t } = useTranslation(['dashboard', 'common']);
  const { currencySymbol } = useTenantCurrency();
  const [expandedReasoningId, setExpandedReasoningId] = useState<string | null>(null);
  const [processingId, setProcessingId] = useState<string | null>(null);

  if (loading) {
    return (
      <div className="rounded-xl shadow-lg p-6 border border-[var(--border-primary)] bg-[var(--bg-primary)] animate-pulse">
        <div className="flex items-center gap-4 mb-4">
          <div className="w-12 h-12 bg-[var(--bg-secondary)] rounded-full"></div>
          <div className="flex-1 space-y-2">
            <div className="h-5 bg-[var(--bg-secondary)] rounded w-1/3"></div>
            <div className="h-4 bg-[var(--bg-secondary)] rounded w-1/4"></div>
          </div>
        </div>
        <div className="space-y-3">
          <div className="h-20 bg-[var(--bg-secondary)] rounded"></div>
          <div className="h-20 bg-[var(--bg-secondary)] rounded"></div>
        </div>
      </div>
    );
  }

  const hasPendingPOs = pendingPOs.length > 0;

  // Handle approve action
  const handleApprove = async (poId: string) => {
    if (!onApprove || processingId) return;
    setProcessingId(poId);
    try {
      await onApprove(poId);
    } finally {
      setProcessingId(null);
    }
  };

  // Handle reject action
  const handleReject = async (poId: string) => {
    if (!onReject || processingId) return;
    setProcessingId(poId);
    try {
      await onReject(poId, 'Rejected from dashboard');
    } finally {
      setProcessingId(null);
    }
  };

  // Toggle reasoning expansion
  const toggleReasoning = (poId: string) => {
    setExpandedReasoningId(expandedReasoningId === poId ? null : poId);
  };

  // Format AI reasoning from reasoning_data
  const formatReasoning = (po: any): string | null => {
    const reasoningData = po.reasoning_data || po.ai_reasoning;

    // If no structured reasoning data, try the summary field
    if (!reasoningData) {
      return po.ai_reasoning_summary || null;
    }

    if (typeof reasoningData === 'string') return reasoningData;

    // Handle structured reasoning data
    if (reasoningData.type === 'low_stock_forecast' || reasoningData.type === 'low_stock_detection') {
      const params = reasoningData.parameters || {};
      const productNames = params.product_names || params.critical_products || [];
      const productDetails = params.product_details || [];
      const criticalCount = params.critical_product_count || productNames.length;
      const minDepletionDays = Math.ceil(params.min_depletion_days || 0);
      const affectedBatchesCount = params.affected_batches_count || 0;
      const potentialLoss = params.potential_loss_eur || 0;

      // If we have detailed data (multiple products), show comprehensive message
      if (criticalCount > 1 && productNames.length > 0) {
        const productsStr = productNames.slice(0, 3).join(', ') + (productNames.length > 3 ? '...' : '');

        return t('dashboard:new_dashboard.pending_purchases.reasoning.low_stock_detailed', {
          count: criticalCount,
          products: productsStr,
          days: minDepletionDays,
          batches: affectedBatchesCount,
          loss: potentialLoss.toFixed(2),
        });
      }

      // Simple version for single product
      const firstProduct = productDetails[0] || {};
      const ingredient = firstProduct.product_name || productNames[0] || 'ingredient';
      const days = Math.ceil(firstProduct.days_until_depletion || minDepletionDays);

      return t('dashboard:new_dashboard.pending_purchases.reasoning.low_stock', {
        ingredient,
        days,
      });
    }

    if (reasoningData.type === 'demand_forecast') {
      return t('dashboard:new_dashboard.pending_purchases.reasoning.demand_forecast', {
        product: reasoningData.parameters?.product_name || 'product',
        increase: reasoningData.parameters?.demand_increase_percent || 0,
      });
    }

    // Handle production requirement reasoning
    if (reasoningData.type === 'production_requirement') {
      const params = reasoningData.parameters || {};
      const productNames = params.product_names || [];
      const productsStr = productNames.length > 0 ? productNames.join(', ') : 'products';
      
      return t('dashboard:new_dashboard.pending_purchases.reasoning.production_requirement', {
        products: productsStr,
        batches: params.production_batches || params.batches_required || 0,
        days: params.days_until_required || 0,
      });
    }

    // Handle safety stock replenishment reasoning
    if (reasoningData.type === 'safety_stock_replenishment') {
      const params = reasoningData.parameters || {};
      return t('dashboard:new_dashboard.pending_purchases.reasoning.safety_stock', {
        count: params.product_count || 0,
        current: params.current_safety_stock || 0,
        target: params.target_safety_stock || 0,
      });
    }

    // Handle supplier contract reasoning
    if (reasoningData.type === 'supplier_contract') {
      const params = reasoningData.parameters || {};
      return t('dashboard:new_dashboard.pending_purchases.reasoning.supplier_contract', {
        supplier: params.supplier_name || 'supplier',
        products: params.product_categories?.join(', ') || 'products',
      });
    }

    // Handle seasonal demand reasoning
    if (reasoningData.type === 'seasonal_demand') {
      const params = reasoningData.parameters || {};
      return t('dashboard:new_dashboard.pending_purchases.reasoning.seasonal_demand', {
        season: params.season || 'season',
        increase: params.expected_demand_increase_pct || 0,
        products: params.product_names?.join(', ') || 'products',
      });
    }

    // Handle forecast demand reasoning
    if (reasoningData.type === 'forecast_demand') {
      const params = reasoningData.parameters || {};
      return t('dashboard:new_dashboard.pending_purchases.reasoning.forecast_demand', {
        product: params.product_name || 'product',
        confidence: params.confidence_score ? Math.round(params.confidence_score * 100) : 0,
        period: params.forecast_period_days || 0,
      });
    }

    if (reasoningData.summary) return reasoningData.summary;

    // Fallback to ai_reasoning_summary if structured data doesn't have a matching type
    return po.ai_reasoning_summary || null;
  };

  return (
    <div className="rounded-xl shadow-lg border border-[var(--border-primary)] bg-[var(--bg-primary)] overflow-hidden">
      {/* Header */}
      <div className="p-6 pb-4">
        <div className="flex items-center gap-4">
          {/* Icon */}
          <div
            className={`w-12 h-12 rounded-full flex items-center justify-center flex-shrink-0 ${
              hasPendingPOs
                ? 'bg-[var(--color-warning-100)]'
                : 'bg-[var(--color-success-100)]'
            }`}
          >
            {hasPendingPOs ? (
              <ShoppingCart className="w-6 h-6 text-[var(--color-warning-600)]" />
            ) : (
              <CheckCircle2 className="w-6 h-6 text-[var(--color-success-600)]" />
            )}
          </div>

          {/* Title & Count */}
          <div className="flex-1">
            <h2 className="text-xl font-bold text-[var(--text-primary)]">
              {t('dashboard:new_dashboard.pending_purchases.title')}
            </h2>
            <p className="text-sm text-[var(--text-secondary)]">
              {hasPendingPOs
                ? t('dashboard:new_dashboard.pending_purchases.count', {
                    count: pendingPOs.length,
                  })
                : t('dashboard:new_dashboard.pending_purchases.no_pending')}
            </p>
          </div>

          {/* Count Badge */}
          {hasPendingPOs && (
            <div className="px-3 py-1 rounded-full bg-[var(--color-warning-100)] text-[var(--color-warning-700)] font-semibold text-sm">
              {pendingPOs.length}
            </div>
          )}
        </div>
      </div>

      {/* PO List */}
      {hasPendingPOs ? (
        <div className="border-t border-[var(--border-primary)]">
          {pendingPOs.map((po, index) => {
            const poId = po.id || po.po_id;
            const isProcessing = processingId === poId;
            const isExpanded = expandedReasoningId === poId;
            const reasoning = formatReasoning(po);

            return (
              <div
                key={poId || index}
                className={`p-4 ${
                  index < pendingPOs.length - 1 ? 'border-b border-[var(--border-primary)]' : ''
                }`}
              >
                {/* PO Main Info */}
                <div className="flex items-start gap-4">
                  {/* PO Details */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="font-semibold text-[var(--text-primary)]">
                        {t('dashboard:new_dashboard.pending_purchases.po_number', {
                          number: po.po_number || po.id?.slice(0, 8),
                        })}
                      </span>
                      {reasoning && (
                        <button
                          onClick={() => toggleReasoning(poId)}
                          className="flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-[var(--color-primary-50)] text-[var(--color-primary-700)] hover:bg-[var(--color-primary-100)] transition-colors"
                        >
                          <Brain className="w-3 h-3" />
                          AI
                          {isExpanded ? (
                            <ChevronUp className="w-3 h-3" />
                          ) : (
                            <ChevronDown className="w-3 h-3" />
                          )}
                        </button>
                      )}
                    </div>

                    <p className="text-sm text-[var(--text-secondary)] mb-1">
                      {t('dashboard:new_dashboard.pending_purchases.supplier', {
                        name: po.supplier_name || po.supplier?.name || 'Unknown',
                      })}
                    </p>

                    <p className="text-lg font-bold text-[var(--text-primary)]">
                      {currencySymbol}{(po.total_amount || po.total || 0).toLocaleString(undefined, {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2,
                      })}
                    </p>
                  </div>

                  {/* Actions */}
                  <div className="flex items-center gap-2 flex-shrink-0">
                    {/* View Details */}
                    {onViewDetails && (
                      <button
                        onClick={() => onViewDetails(poId)}
                        disabled={isProcessing}
                        className="p-2 rounded-lg border border-[var(--border-primary)] text-[var(--text-secondary)] hover:bg-[var(--bg-secondary)] transition-colors disabled:opacity-50"
                        title={t('dashboard:new_dashboard.pending_purchases.view_details')}
                      >
                        <Eye className="w-5 h-5" />
                      </button>
                    )}

                    {/* Reject */}
                    {onReject && (
                      <button
                        onClick={() => handleReject(poId)}
                        disabled={isProcessing}
                        className="p-2 rounded-lg border border-[var(--color-error-200)] text-[var(--color-error-600)] hover:bg-[var(--color-error-50)] transition-colors disabled:opacity-50"
                        title={t('dashboard:new_dashboard.pending_purchases.reject')}
                      >
                        <X className="w-5 h-5" />
                      </button>
                    )}

                    {/* Approve */}
                    {onApprove && (
                      <button
                        onClick={() => handleApprove(poId)}
                        disabled={isProcessing}
                        className="flex items-center gap-2 px-4 py-2 rounded-lg bg-[var(--color-success-600)] text-white hover:bg-[var(--color-success-700)] transition-colors disabled:opacity-50"
                      >
                        <Check className="w-5 h-5" />
                        <span className="font-medium">
                          {t('dashboard:new_dashboard.pending_purchases.approve')}
                        </span>
                      </button>
                    )}
                  </div>
                </div>

                {/* AI Reasoning (Expanded) */}
                {isExpanded && reasoning && (
                  <div className="mt-3 p-3 rounded-lg bg-[var(--color-primary-50)] border border-[var(--color-primary-100)]">
                    <div className="flex items-start gap-2">
                      <Brain className="w-4 h-4 text-[var(--color-primary-600)] mt-0.5 flex-shrink-0" />
                      <div>
                        <p className="text-sm font-medium text-[var(--color-primary-700)] mb-1">
                          {t('dashboard:new_dashboard.pending_purchases.ai_reasoning')}
                        </p>
                        <p className="text-sm text-[var(--color-primary-600)]">{reasoning}</p>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      ) : (
        /* Empty State */
        <div className="px-6 pb-6">
          <div className="flex items-center gap-3 p-4 rounded-lg bg-[var(--color-success-50)] border border-[var(--color-success-100)]">
            <CheckCircle2 className="w-6 h-6 text-[var(--color-success-600)]" />
            <p className="text-sm text-[var(--color-success-700)]">
              {t('dashboard:new_dashboard.pending_purchases.all_clear')}
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

export default PendingPurchasesBlock;
