// ================================================================
// frontend/src/components/procurement/CriticalRequirements.tsx
// ================================================================
/**
 * Critical Requirements Component
 * Displays urgent procurement requirements that need immediate attention
 */

import React from 'react';
import type { ProcurementRequirement } from '@/api/types/procurement';
import { Priority, RequirementStatus } from '@/api/types/procurement';

export interface CriticalRequirementsProps {
  requirements: ProcurementRequirement[];
  onViewDetails?: (requirementId: string) => void;
  onUpdateStatus?: (requirementId: string, status: string) => void;
}

export const CriticalRequirements: React.FC<CriticalRequirementsProps> = ({
  requirements,
  onViewDetails,
  onUpdateStatus,
}) => {
  const formatCurrency = (amount: number | undefined) => {
    if (!amount) return 'N/A';
    return new Intl.NumberFormat('es-ES', {
      style: 'currency',
      currency: 'EUR'
    }).format(amount);
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const today = new Date();
    const diffTime = date.getTime() - today.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays < 0) {
      return `Overdue by ${Math.abs(diffDays)} days`;
    } else if (diffDays === 0) {
      return 'Due today';
    } else if (diffDays === 1) {
      return 'Due tomorrow';
    } else {
      return `Due in ${diffDays} days`;
    }
  };

  const getStatusColor = (status: string) => {
    const colors = {
      [RequirementStatus.PENDING]: 'bg-yellow-100 text-yellow-800',
      [RequirementStatus.APPROVED]: 'bg-blue-100 text-blue-800',
      [RequirementStatus.ORDERED]: 'bg-purple-100 text-purple-800',
      [RequirementStatus.PARTIALLY_RECEIVED]: 'bg-orange-100 text-orange-800',
      [RequirementStatus.RECEIVED]: 'bg-green-100 text-green-800',
      [RequirementStatus.CANCELLED]: 'bg-red-100 text-red-800',
    };
    return colors[status as keyof typeof colors] || 'bg-gray-100 text-gray-800';
  };

  const getDueDateColor = (dateString: string) => {
    const date = new Date(dateString);
    const today = new Date();
    const diffTime = date.getTime() - today.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays < 0) return 'text-red-600 font-medium'; // Overdue
    if (diffDays <= 1) return 'text-orange-600 font-medium'; // Due soon
    return 'text-gray-600';
  };

  const getStockLevelColor = (current: number, needed: number) => {
    const ratio = current / needed;
    if (ratio <= 0.1) return 'text-red-600 font-medium'; // Critical
    if (ratio <= 0.3) return 'text-orange-600 font-medium'; // Low
    return 'text-gray-600';
  };

  if (requirements.length === 0) {
    return (
      <div className="text-center py-8 text-gray-500">
        <p>No critical requirements at this time</p>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {requirements.map((requirement) => (
        <div 
          key={requirement.id}
          className="border border-red-200 rounded-lg p-4 bg-red-50 hover:bg-red-100 transition-colors"
        >
          <div className="flex items-start justify-between">
            <div className="flex-1">
              <div className="flex items-center space-x-2 mb-2">
                <h4 className="font-medium text-gray-900">
                  {requirement.product_name}
                </h4>
                <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(requirement.status)}`}>
                  {requirement.status.replace('_', ' ').toUpperCase()}
                </span>
                <span className="px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-700">
                  CRITICAL
                </span>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-4 gap-4 text-sm">
                <div>
                  <span className="text-gray-500">Required:</span>
                  <div className="font-medium">
                    {requirement.net_requirement} {requirement.unit_of_measure}
                  </div>
                </div>

                <div>
                  <span className="text-gray-500">Current Stock:</span>
                  <div className={getStockLevelColor(requirement.current_stock_level, requirement.net_requirement)}>
                    {requirement.current_stock_level} {requirement.unit_of_measure}
                  </div>
                </div>

                <div>
                  <span className="text-gray-500">Due Date:</span>
                  <div className={getDueDateColor(requirement.required_by_date)}>
                    {formatDate(requirement.required_by_date)}
                  </div>
                </div>

                <div>
                  <span className="text-gray-500">Est. Cost:</span>
                  <div className="font-medium">
                    {formatCurrency(requirement.estimated_total_cost)}
                  </div>
                </div>
              </div>

              {requirement.supplier_name && (
                <div className="mt-2 text-sm">
                  <span className="text-gray-500">Supplier:</span>
                  <span className="ml-1 font-medium">{requirement.supplier_name}</span>
                  {requirement.supplier_lead_time_days && (
                    <span className="ml-2 text-gray-500">
                      ({requirement.supplier_lead_time_days} days lead time)
                    </span>
                  )}
                </div>
              )}

              {requirement.special_requirements && (
                <div className="mt-2 p-2 bg-yellow-50 rounded border border-yellow-200">
                  <span className="text-xs text-yellow-700 font-medium">Special Requirements:</span>
                  <p className="text-xs text-yellow-600 mt-1">
                    {requirement.special_requirements}
                  </p>
                </div>
              )}
            </div>

            <div className="flex flex-col space-y-2 ml-4">
              {requirement.status === RequirementStatus.PENDING && (
                <button
                  onClick={() => onUpdateStatus?.(requirement.id, RequirementStatus.APPROVED)}
                  className="px-3 py-1 bg-blue-600 text-white text-xs rounded hover:bg-blue-700 transition-colors"
                >
                  Approve
                </button>
              )}

              {requirement.status === RequirementStatus.APPROVED && (
                <button
                  onClick={() => onUpdateStatus?.(requirement.id, RequirementStatus.ORDERED)}
                  className="px-3 py-1 bg-purple-600 text-white text-xs rounded hover:bg-purple-700 transition-colors"
                >
                  Order Now
                </button>
              )}

              <button
                onClick={() => onViewDetails?.(requirement.id)}
                className="px-3 py-1 bg-gray-200 text-gray-700 text-xs rounded hover:bg-gray-300 transition-colors"
              >
                Details
              </button>
            </div>
          </div>

          {/* Progress indicator for ordered items */}
          {requirement.status === RequirementStatus.ORDERED && requirement.ordered_quantity > 0 && (
            <div className="mt-3 pt-3 border-t border-red-200">
              <div className="flex justify-between text-xs text-gray-600 mb-1">
                <span>Order Progress</span>
                <span>
                  {requirement.received_quantity} / {requirement.ordered_quantity} {requirement.unit_of_measure}
                </span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div
                  className="bg-blue-600 h-2 rounded-full transition-all"
                  style={{
                    width: `${Math.min(100, (requirement.received_quantity / requirement.ordered_quantity) * 100)}%`
                  }}
                />
              </div>
              {requirement.expected_delivery_date && (
                <div className="text-xs text-gray-500 mt-1">
                  Expected: {formatDate(requirement.expected_delivery_date)}
                </div>
              )}
            </div>
          )}
        </div>
      ))}
    </div>
  );
};