import React from 'react';
import { Card, CardHeader, CardBody } from '../../ui/Card';
import { StatusCard } from '../../ui/StatusCard/StatusCard';
import { Badge } from '../../ui/Badge';
import { Button } from '../../ui/Button';
import {
  ShoppingCart,
  Clock,
  Package,
  AlertTriangle,
  CheckCircle,
  ChevronRight,
  Calendar,
  User,
  DollarSign,
  Truck
} from 'lucide-react';

export interface ProcurementItem {
  id: string;
  ingredient: string;
  quantity: number;
  unit: string;
  supplier: string;
  priority: 'urgent' | 'high' | 'medium' | 'low';
  estimatedCost: number;
  deliveryTime: string;
  currentStock: number;
  minStock: number;
  plannedFor: string;
  status: 'pending' | 'ordered' | 'in_transit' | 'delivered';
  notes?: string;
}

export interface ProcurementPlansProps {
  className?: string;
  items?: ProcurementItem[];
  onOrderItem?: (itemId: string) => void;
  onViewDetails?: (itemId: string) => void;
  onViewAllPlans?: () => void;
}

const ProcurementPlansToday: React.FC<ProcurementPlansProps> = ({
  className,
  items = [],
  onOrderItem,
  onViewDetails,
  onViewAllPlans
}) => {
  const defaultItems: ProcurementItem[] = [
    {
      id: '1',
      ingredient: 'Harina de Trigo',
      quantity: 50,
      unit: 'kg',
      supplier: 'Molinos San José',
      priority: 'urgent',
      estimatedCost: 87.50,
      deliveryTime: '10:00',
      currentStock: 3,
      minStock: 15,
      plannedFor: '09:00',
      status: 'pending',
      notes: 'Stock crítico - necesario para producción matutina'
    },
    {
      id: '2',
      ingredient: 'Levadura Fresca',
      quantity: 5,
      unit: 'kg',
      supplier: 'Distribuidora Alba',
      priority: 'urgent',
      estimatedCost: 32.50,
      deliveryTime: '11:30',
      currentStock: 1,
      minStock: 3,
      plannedFor: '09:30',
      status: 'pending'
    },
    {
      id: '3',
      ingredient: 'Mantequilla',
      quantity: 15,
      unit: 'kg',
      supplier: 'Lácteos Premium',
      priority: 'high',
      estimatedCost: 105.00,
      deliveryTime: '14:00',
      currentStock: 8,
      minStock: 12,
      plannedFor: '10:00',
      status: 'ordered'
    },
    {
      id: '4',
      ingredient: 'Azúcar Blanco',
      quantity: 25,
      unit: 'kg',
      supplier: 'Azucarera Local',
      priority: 'medium',
      estimatedCost: 62.50,
      deliveryTime: '16:00',
      currentStock: 18,
      minStock: 20,
      plannedFor: '11:00',
      status: 'pending'
    }
  ];

  const displayItems = items.length > 0 ? items : defaultItems;

  const getItemStatusConfig = (item: ProcurementItem) => {
    const baseConfig = {
      isCritical: item.priority === 'urgent',
      isHighlight: item.priority === 'high' || item.status === 'pending',
    };

    switch (item.status) {
      case 'pending':
        return {
          ...baseConfig,
          color: 'var(--color-warning)',
          text: 'Pendiente',
          icon: Clock
        };
      case 'ordered':
        return {
          ...baseConfig,
          color: 'var(--color-info)',
          text: 'Pedido',
          icon: CheckCircle
        };
      case 'in_transit':
        return {
          ...baseConfig,
          color: 'var(--color-primary)',
          text: 'En Camino',
          icon: Truck
        };
      case 'delivered':
        return {
          ...baseConfig,
          color: 'var(--color-success)',
          text: 'Entregado',
          icon: Package
        };
      default:
        return {
          ...baseConfig,
          color: 'var(--color-warning)',
          text: 'Pendiente',
          icon: Clock
        };
    }
  };

  const urgentItems = displayItems.filter(item => item.priority === 'urgent').length;
  const pendingItems = displayItems.filter(item => item.status === 'pending').length;
  const totalValue = displayItems.reduce((sum, item) => sum + item.estimatedCost, 0);

  return (
    <Card className={className} variant="elevated" padding="none">
      <CardHeader padding="lg" divider>
        <div className="flex items-center justify-between w-full">
          <div className="flex items-center gap-3">
            <div
              className="p-2 rounded-lg"
              style={{ backgroundColor: 'var(--color-primary)20' }}
            >
              <ShoppingCart className="w-5 h-5" style={{ color: 'var(--color-primary)' }} />
            </div>
            <div>
              <h3 className="text-lg font-semibold" style={{ color: 'var(--text-primary)' }}>
                Planes de Compra - Hoy
              </h3>
              <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
                Gestiona los pedidos programados para hoy
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            {urgentItems > 0 && (
              <Badge variant="error" size="sm">
                {urgentItems} urgentes
              </Badge>
            )}
            <Badge variant="info" size="sm">
              €{totalValue.toFixed(2)}
            </Badge>
          </div>
        </div>
      </CardHeader>

      <CardBody padding="none">
        {displayItems.length === 0 ? (
          <div className="p-8 text-center">
            <div
              className="p-4 rounded-full mx-auto mb-4 w-16 h-16 flex items-center justify-center"
              style={{ backgroundColor: 'var(--color-success)20' }}
            >
              <Package className="w-8 h-8" style={{ color: 'var(--color-success)' }} />
            </div>
            <h4 className="text-lg font-medium mb-2" style={{ color: 'var(--text-primary)' }}>
              No hay compras programadas
            </h4>
            <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
              Todos los suministros están al día
            </p>
          </div>
        ) : (
          <div className="space-y-3 p-4">
            {displayItems.map((item) => {
              const statusConfig = getItemStatusConfig(item);
              const stockPercentage = Math.round((item.currentStock / item.minStock) * 100);

              return (
                <StatusCard
                  key={item.id}
                  id={item.id}
                  statusIndicator={statusConfig}
                  title={item.ingredient}
                  subtitle={`${item.supplier} • ${item.quantity} ${item.unit}`}
                  primaryValue={`€${item.estimatedCost.toFixed(2)}`}
                  primaryValueLabel="COSTO"
                  secondaryInfo={{
                    label: 'Stock actual',
                    value: `${item.currentStock}/${item.minStock} ${item.unit} (${stockPercentage}%)`
                  }}
                  progress={item.currentStock < item.minStock ? {
                    label: `Stock: ${stockPercentage}% del mínimo`,
                    percentage: stockPercentage,
                    color: stockPercentage < 50 ? 'var(--color-error)' :
                           stockPercentage < 80 ? 'var(--color-warning)' : 'var(--color-success)'
                  } : undefined}
                  metadata={[
                    `📅 Pedido: ${item.plannedFor}`,
                    `🚚 Llegada: ${item.deliveryTime}`,
                    ...(item.notes ? [`📋 ${item.notes}`] : [])
                  ]}
                  actions={[
                    ...(item.status === 'pending' ? [{
                      label: 'Realizar Pedido',
                      icon: ShoppingCart,
                      variant: 'primary' as const,
                      onClick: () => onOrderItem?.(item.id),
                      priority: 'primary' as const
                    }] : []),
                    {
                      label: 'Ver Detalles',
                      icon: ChevronRight,
                      variant: 'outline' as const,
                      onClick: () => onViewDetails?.(item.id),
                      priority: 'secondary' as const
                    }
                  ]}
                  compact={true}
                  className="border-l-4"
                />
              );
            })}
          </div>
        )}

        {displayItems.length > 0 && (
          <div
            className="p-4 border-t"
            style={{
              borderColor: 'var(--border-primary)',
              backgroundColor: 'var(--bg-secondary)'
            }}
          >
            <div className="flex items-center justify-between">
              <div className="text-sm">
                <span style={{ color: 'var(--text-secondary)' }}>
                  {pendingItems} pendientes de {displayItems.length} total
                </span>
              </div>

              <Button
                variant="outline"
                size="sm"
                onClick={onViewAllPlans}
                className="flex items-center gap-2"
              >
                Ver Todos los Planes
                <ChevronRight className="w-4 h-4" />
              </Button>
            </div>
          </div>
        )}
      </CardBody>
    </Card>
  );
};

export default ProcurementPlansToday;