// ================================================================
// frontend/src/components/dashboard/PurchaseOrderDetailsModal.tsx
// ================================================================
/**
 * Purchase Order Details Modal
 * Quick view of PO details from the Action Queue
 */

import React from 'react';
import {
  X,
  Package,
  Building2,
  Calendar,
  Truck,
  Euro,
  FileText,
  CheckCircle,
  Clock,
  AlertCircle,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { usePurchaseOrder } from '../../api/hooks/purchase-orders';
import { formatDistanceToNow } from 'date-fns';
import { es, enUS, eu as euLocale } from 'date-fns/locale';

interface PurchaseOrderDetailsModalProps {
  poId: string;
  tenantId: string;
  isOpen: boolean;
  onClose: () => void;
  onApprove?: (poId: string) => void;
  onModify?: (poId: string) => void;
}

const localeMap = {
  es: es,
  en: enUS,
  eu: euLocale,
};

export const PurchaseOrderDetailsModal: React.FC<PurchaseOrderDetailsModalProps> = ({
  poId,
  tenantId,
  isOpen,
  onClose,
  onApprove,
  onModify,
}) => {
  const { t, i18n } = useTranslation();
  const { data: po, isLoading } = usePurchaseOrder(tenantId, poId);

  if (!isOpen) return null;

  const dateLocale = localeMap[i18n.language as keyof typeof localeMap] || enUS;

  // Format currency
  const formatCurrency = (value: any) => {
    const num = Number(value);
    return isNaN(num) ? '0.00' : num.toFixed(2);
  };

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      draft: {
        bg: 'var(--color-gray-100)',
        text: 'var(--color-gray-700)',
        label: t('purchase_orders:status.draft'),
      },
      pending_approval: {
        bg: 'var(--color-warning-100)',
        text: 'var(--color-warning-700)',
        label: t('purchase_orders:status.pending_approval'),
      },
      approved: {
        bg: 'var(--color-success-100)',
        text: 'var(--color-success-700)',
        label: t('purchase_orders:status.approved'),
      },
      sent: {
        bg: 'var(--color-info-100)',
        text: 'var(--color-info-700)',
        label: t('purchase_orders:status.sent'),
      },
      partially_received: {
        bg: 'var(--color-warning-100)',
        text: 'var(--color-warning-700)',
        label: t('purchase_orders:status.partially_received'),
      },
      received: {
        bg: 'var(--color-success-100)',
        text: 'var(--color-success-700)',
        label: t('purchase_orders:status.received'),
      },
      cancelled: {
        bg: 'var(--color-error-100)',
        text: 'var(--color-error-700)',
        label: t('purchase_orders:status.cancelled'),
      },
    };

    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.draft;

    return (
      <span
        className="px-3 py-1 rounded-full text-sm font-medium"
        style={{ backgroundColor: config.bg, color: config.text }}
      >
        {config.label}
      </span>
    );
  };

  return (
    <div
      className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4 animate-fadeIn"
      onClick={onClose}
      style={{
        backdropFilter: 'blur(4px)',
        animation: 'fadeIn 0.2s ease-out'
      }}
    >
      <div
        className="bg-white rounded-xl shadow-2xl max-w-3xl w-full max-h-[90vh] overflow-hidden transform transition-all"
        onClick={(e) => e.stopPropagation()}
        style={{
          backgroundColor: 'var(--bg-primary)',
          animation: 'slideUp 0.3s ease-out'
        }}
      >
        <style>{`
          @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
          }
          @keyframes slideUp {
            from {
              opacity: 0;
              transform: translateY(20px) scale(0.95);
            }
            to {
              opacity: 1;
              transform: translateY(0) scale(1);
            }
          }
        `}</style>
        {/* Header */}
        <div
          className="flex items-center justify-between p-6 border-b bg-gradient-to-r from-transparent to-transparent"
          style={{
            borderColor: 'var(--border-primary)',
            background: 'linear-gradient(to right, var(--bg-primary), var(--bg-secondary))'
          }}
        >
          <div className="flex items-center gap-4">
            <div
              className="p-3 rounded-xl"
              style={{
                backgroundColor: 'var(--color-primary-100)',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.05)'
              }}
            >
              <Package className="w-6 h-6" style={{ color: 'var(--color-primary-600)' }} />
            </div>
            <div>
              <h2 className="text-2xl font-bold mb-1" style={{ color: 'var(--text-primary)' }}>
                {isLoading ? t('common:loading') : po?.po_number || t('purchase_orders:purchase_order')}
              </h2>
              {po && (
                <p className="text-sm flex items-center gap-1" style={{ color: 'var(--text-secondary)' }}>
                  <Clock className="w-3.5 h-3.5" />
                  {t('purchase_orders:created')} {formatDistanceToNow(new Date(po.created_at), { addSuffix: true, locale: dateLocale })}
                </p>
              )}
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-lg hover:bg-gray-100 transition-all hover:scale-110"
            style={{ color: 'var(--text-secondary)' }}
            aria-label={t('purchase_orders:actions.close')}
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 overflow-y-auto max-h-[calc(90vh-200px)]">
          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-10 w-10 border-3 border-primary-200 border-t-primary-600"></div>
            </div>
          ) : po ? (
            <div className="space-y-6">
              {/* Status and Key Info */}
              <div className="flex flex-wrap items-center gap-4 p-4 rounded-xl" style={{
                backgroundColor: 'var(--bg-secondary)',
                border: '1px solid var(--border-primary)'
              }}>
                {getStatusBadge(po.status)}
                <div className="flex-1 min-w-[200px]">
                  <p className="text-xs uppercase tracking-wide mb-1" style={{ color: 'var(--text-secondary)' }}>
                    {t('purchase_orders:total_amount')}
                  </p>
                  <div className="flex items-baseline gap-2">
                    <Euro className="w-5 h-5" style={{ color: 'var(--color-primary-600)' }} />
                    <span className="text-2xl font-bold" style={{ color: 'var(--text-primary)' }}>
                      {formatCurrency(po.total_amount)}
                    </span>
                  </div>
                </div>
              </div>

              {/* Supplier Info */}
              <div className="rounded-xl p-5 border" style={{
                backgroundColor: 'var(--bg-secondary)',
                borderColor: 'var(--border-primary)',
                boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)'
              }}>
                <div className="flex items-center gap-2 mb-3">
                  <div className="p-2 rounded-lg" style={{ backgroundColor: 'var(--color-primary-100)' }}>
                    <Building2 className="w-5 h-5" style={{ color: 'var(--color-primary-600)' }} />
                  </div>
                  <h3 className="font-semibold text-sm uppercase tracking-wide" style={{ color: 'var(--text-secondary)' }}>
                    {t('purchase_orders:supplier')}
                  </h3>
                </div>
                <p className="text-xl font-semibold ml-1" style={{ color: 'var(--text-primary)' }}>
                  {po.supplier_name || t('common:unknown')}
                </p>
              </div>

              {/* Dates */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="rounded-xl p-4 border" style={{
                  backgroundColor: 'var(--bg-secondary)',
                  borderColor: 'var(--border-primary)',
                  boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)'
                }}>
                  <div className="flex items-center gap-2 mb-3">
                    <div className="p-1.5 rounded-lg" style={{ backgroundColor: 'var(--color-primary-100)' }}>
                      <Calendar className="w-4 h-4" style={{ color: 'var(--color-primary-600)' }} />
                    </div>
                    <h3 className="font-semibold text-xs uppercase tracking-wide" style={{ color: 'var(--text-secondary)' }}>
                      {t('purchase_orders:order_date')}
                    </h3>
                  </div>
                  <p className="text-lg font-semibold ml-1" style={{ color: 'var(--text-primary)' }}>
                    {new Date(po.order_date).toLocaleDateString(i18n.language, {
                      year: 'numeric',
                      month: 'short',
                      day: 'numeric'
                    })}
                  </p>
                </div>

                {po.expected_delivery_date && (
                  <div className="rounded-xl p-4 border" style={{
                    backgroundColor: 'var(--bg-secondary)',
                    borderColor: 'var(--border-primary)',
                    boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)'
                  }}>
                    <div className="flex items-center gap-2 mb-3">
                      <div className="p-1.5 rounded-lg" style={{ backgroundColor: 'var(--color-success-100)' }}>
                        <Truck className="w-4 h-4" style={{ color: 'var(--color-success-600)' }} />
                      </div>
                      <h3 className="font-semibold text-xs uppercase tracking-wide" style={{ color: 'var(--text-secondary)' }}>
                        {t('purchase_orders:expected_delivery')}
                      </h3>
                    </div>
                    <p className="text-lg font-semibold ml-1" style={{ color: 'var(--text-primary)' }}>
                      {new Date(po.expected_delivery_date).toLocaleDateString(i18n.language, {
                        year: 'numeric',
                        month: 'short',
                        day: 'numeric'
                      })}
                    </p>
                  </div>
                )}
              </div>

              {/* Items */}
              <div>
                <div className="flex items-center gap-2 mb-4">
                  <div className="p-2 rounded-lg" style={{ backgroundColor: 'var(--color-primary-100)' }}>
                    <FileText className="w-5 h-5" style={{ color: 'var(--color-primary-600)' }} />
                  </div>
                  <h3 className="font-bold text-lg" style={{ color: 'var(--text-primary)' }}>
                    {t('purchase_orders:items')}
                  </h3>
                  {po.items && po.items.length > 0 && (
                    <span
                      className="ml-auto px-3 py-1 rounded-full text-sm font-medium"
                      style={{
                        backgroundColor: 'var(--color-primary-100)',
                        color: 'var(--color-primary-700)'
                      }}
                    >
                      {po.items.length} {po.items.length === 1 ? t('common:item') : t('common:items')}
                    </span>
                  )}
                </div>
                <div className="space-y-3">
                  {po.items && po.items.length > 0 ? (
                    po.items.map((item: any, index: number) => (
                      <div
                        key={index}
                        className="flex justify-between items-center p-4 rounded-xl border transition-all hover:shadow-md"
                        style={{
                          backgroundColor: 'var(--bg-secondary)',
                          borderColor: 'var(--border-primary)'
                        }}
                      >
                        <div className="flex-1">
                          <p className="font-semibold text-base mb-1" style={{ color: 'var(--text-primary)' }}>
                            {item.ingredient_name || item.product_name}
                          </p>
                          <p className="text-sm flex items-center gap-1.5" style={{ color: 'var(--text-secondary)' }}>
                            <span className="font-medium">{item.quantity} {item.unit}</span>
                            <span>×</span>
                            <span>€{formatCurrency(item.unit_price)}</span>
                          </p>
                        </div>
                        <p className="font-bold text-lg ml-4" style={{ color: 'var(--color-primary-600)' }}>
                          €{formatCurrency(item.subtotal)}
                        </p>
                      </div>
                    ))
                  ) : (
                    <div className="text-center py-8 rounded-xl border-2 border-dashed" style={{
                      borderColor: 'var(--border-primary)',
                      color: 'var(--text-secondary)'
                    }}>
                      <FileText className="w-12 h-12 mx-auto mb-2 opacity-30" />
                      <p>{t('purchase_orders:no_items')}</p>
                    </div>
                  )}
                </div>
              </div>

              {/* Notes */}
              {po.notes && (
                <div className="rounded-xl p-5 border-l-4" style={{
                  backgroundColor: 'var(--color-info-50)',
                  borderLeftColor: 'var(--color-info-500)',
                  boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)'
                }}>
                  <div className="flex items-center gap-2 mb-3">
                    <div className="p-1.5 rounded-lg" style={{ backgroundColor: 'var(--color-info-100)' }}>
                      <AlertCircle className="w-5 h-5" style={{ color: 'var(--color-info-600)' }} />
                    </div>
                    <h3 className="font-semibold text-sm uppercase tracking-wide" style={{ color: 'var(--color-info-700)' }}>
                      {t('purchase_orders:notes')}
                    </h3>
                  </div>
                  <p className="text-sm leading-relaxed ml-1" style={{ color: 'var(--text-primary)' }}>{po.notes}</p>
                </div>
              )}
            </div>
          ) : (
            <div className="text-center py-12">
              <p style={{ color: 'var(--text-secondary)' }}>{t('purchase_orders:not_found')}</p>
            </div>
          )}
        </div>

        {/* Footer Actions */}
        {po && po.status === 'pending_approval' && (
          <div
            className="flex justify-end gap-3 p-6 border-t bg-gradient-to-r from-transparent to-transparent"
            style={{
              borderColor: 'var(--border-primary)',
              background: 'linear-gradient(to right, var(--bg-secondary), var(--bg-primary))'
            }}
          >
            <button
              onClick={() => {
                onModify?.(poId);
                onClose();
              }}
              className="px-6 py-2.5 rounded-xl font-semibold transition-all hover:scale-105 hover:shadow-md border"
              style={{
                backgroundColor: 'var(--bg-primary)',
                color: 'var(--text-primary)',
                borderColor: 'var(--border-primary)'
              }}
            >
              {t('purchase_orders:actions.modify')}
            </button>
            <button
              onClick={() => {
                onApprove?.(poId);
                onClose();
              }}
              className="px-6 py-2.5 rounded-xl font-semibold text-white transition-all hover:scale-105 hover:shadow-lg flex items-center gap-2"
              style={{
                backgroundColor: 'var(--color-primary-600)',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
              }}
            >
              <CheckCircle className="w-4 h-4" />
              {t('purchase_orders:actions.approve')}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};
