import React, { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, CardHeader, CardBody } from '../../ui/Card';
import { StatusCard } from '../../ui/StatusCard/StatusCard';
import { Badge } from '../../ui/Badge';
import { Button } from '../../ui/Button';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { usePendingApprovalPurchaseOrders, useApprovePurchaseOrder, useRejectPurchaseOrder } from '../../../api/hooks/purchase-orders';
import { useTenantCurrency } from '../../../hooks/useTenantCurrency';
import {
  ShoppingCart,
  Clock,
  CheckCircle,
  XCircle,
  AlertTriangle,
  ChevronRight,
  Calendar,
  Package,
  TruckIcon,
  Euro,
  FileCheck
} from 'lucide-react';

export interface PendingPOApprovalsProps {
  className?: string;
  maxPOs?: number;
  onApprovePO?: (poId: string) => void;
  onRejectPO?: (poId: string) => void;
  onViewDetails?: (poId: string) => void;
  onViewAllPOs?: () => void;
}

const PendingPOApprovals: React.FC<PendingPOApprovalsProps> = ({
  className,
  maxPOs = 5,
  onApprovePO,
  onRejectPO,
  onViewDetails,
  onViewAllPOs
}) => {
  const { t } = useTranslation(['dashboard']);
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';
  const { currencySymbol } = useTenantCurrency();

  const [approvingPO, setApprovingPO] = useState<string | null>(null);
  const [rejectingPO, setRejectingPO] = useState<string | null>(null);

  // Fetch pending approval POs
  const { data: pendingPOs, isLoading, error } = usePendingApprovalPurchaseOrders(
    tenantId,
    50,
    {
      enabled: !!tenantId,
    }
  );

  // Mutations
  const approveMutation = useApprovePurchaseOrder({
    onSuccess: () => {
      setApprovingPO(null);
      if (approvingPO && onApprovePO) {
        onApprovePO(approvingPO);
      }
    },
    onError: (error) => {
      console.error('Failed to approve PO:', error);
      setApprovingPO(null);
    }
  });

  const rejectMutation = useRejectPurchaseOrder({
    onSuccess: () => {
      setRejectingPO(null);
      if (rejectingPO && onRejectPO) {
        onRejectPO(rejectingPO);
      }
    },
    onError: (error) => {
      console.error('Failed to reject PO:', error);
      setRejectingPO(null);
    }
  });

  const handleApprovePO = async (poId: string) => {
    setApprovingPO(poId);
    await approveMutation.mutateAsync({
      tenantId,
      poId,
      notes: 'Approved from dashboard'
    });
  };

  const handleRejectPO = async (poId: string) => {
    setRejectingPO(poId);
    await rejectMutation.mutateAsync({
      tenantId,
      poId,
      reason: 'Rejected from dashboard - requires review'
    });
  };

  const getPOPriorityConfig = (priority: string) => {
    switch (priority.toLowerCase()) {
      case 'urgent':
        return {
          color: 'var(--color-error)',
          text: 'Urgente',
          icon: AlertTriangle,
          isCritical: true,
          isHighlight: false
        };
      case 'high':
        return {
          color: 'var(--color-warning)',
          text: 'Alta',
          icon: Clock,
          isCritical: false,
          isHighlight: true
        };
      case 'normal':
        return {
          color: 'var(--color-info)',
          text: 'Normal',
          icon: Package,
          isCritical: false,
          isHighlight: false
        };
      case 'low':
        return {
          color: 'var(--color-success)',
          text: 'Baja',
          icon: Clock,
          isCritical: false,
          isHighlight: false
        };
      default:
        return {
          color: 'var(--color-info)',
          text: 'Normal',
          icon: Package,
          isCritical: false,
          isHighlight: false
        };
    }
  };

  const formatCurrency = (amount: string, currency: string = 'EUR') => {
    const value = parseFloat(amount);
    return `${currencySymbol}${value.toFixed(2)}`;
  };

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    const now = new Date();
    const diffDays = Math.ceil((date.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));

    if (diffDays < 0) {
      return `Vencido hace ${Math.abs(diffDays)} días`;
    } else if (diffDays === 0) {
      return 'Hoy';
    } else if (diffDays === 1) {
      return 'Mañana';
    } else if (diffDays <= 7) {
      return `En ${diffDays} días`;
    }
    return date.toLocaleDateString('es-ES', { month: 'short', day: 'numeric' });
  };

  // Process POs and sort by priority and delivery date
  const displayPOs = useMemo(() => {
    if (!pendingPOs || !Array.isArray(pendingPOs)) return [];

    const pos = [...pendingPOs];

    // Sort by priority and delivery date
    const priorityOrder = { urgent: 0, high: 1, normal: 2, low: 3 };
    pos.sort((a, b) => {
      // First by priority
      const aPriority = priorityOrder[a.priority.toLowerCase() as keyof typeof priorityOrder] ?? 4;
      const bPriority = priorityOrder[b.priority.toLowerCase() as keyof typeof priorityOrder] ?? 4;

      if (aPriority !== bPriority) return aPriority - bPriority;

      // Then by delivery date (earliest first)
      if (a.required_delivery_date && b.required_delivery_date) {
        const aDate = new Date(a.required_delivery_date).getTime();
        const bDate = new Date(b.required_delivery_date).getTime();
        return aDate - bDate;
      }

      // Finally by created date (oldest first - longest waiting)
      const aCreated = new Date(a.created_at).getTime();
      const bCreated = new Date(b.created_at).getTime();
      return aCreated - bCreated;
    });

    return pos.slice(0, maxPOs);
  }, [pendingPOs, maxPOs]);

  const urgentPOs = pendingPOs?.filter(po => po.priority === 'urgent' || po.priority === 'high').length || 0;
  const totalPOs = pendingPOs?.length || 0;

  // Calculate total amount pending approval
  const totalAmount = useMemo(() => {
    if (!displayPOs || displayPOs.length === 0) return '0.00';
    const sum = displayPOs.reduce((acc, po) => acc + parseFloat(po.total_amount || '0'), 0);
    return sum.toFixed(2);
  }, [displayPOs]);

  if (isLoading) {
    return (
      <Card className={className} variant="elevated" padding="none">
        <CardHeader padding="lg" divider>
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-[var(--color-primary)]/20">
              <ShoppingCart className="w-5 h-5 text-[var(--color-primary)]" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-[var(--text-primary)]">
                {t('dashboard:sections.pending_po_approvals', 'Órdenes de Compra Pendientes')}
              </h3>
              <p className="text-sm text-[var(--text-secondary)]">
                {t('dashboard:po_approvals.title', '¿Qué órdenes debo aprobar?')}
              </p>
            </div>
          </div>
        </CardHeader>
        <CardBody>
          <div className="flex items-center justify-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--color-primary)]"></div>
          </div>
        </CardBody>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className={className} variant="elevated" padding="none">
        <CardHeader padding="lg" divider>
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-[var(--color-primary)]/20">
              <ShoppingCart className="w-5 h-5 text-[var(--color-primary)]" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-[var(--text-primary)]">
                {t('dashboard:sections.pending_po_approvals', 'Órdenes de Compra Pendientes')}
              </h3>
              <p className="text-sm text-[var(--text-secondary)]">
                {t('dashboard:po_approvals.title', '¿Qué órdenes debo aprobar?')}
              </p>
            </div>
          </div>
        </CardHeader>
        <CardBody>
          <div className="p-4 bg-[var(--color-error)]/10 border border-[var(--color-error)]/20 rounded-lg">
            <p className="text-[var(--color-error)] text-sm">
              {t('dashboard:messages.error_loading', 'Error al cargar los datos')}
            </p>
          </div>
        </CardBody>
      </Card>
    );
  }

  return (
    <Card className={className} variant="elevated" padding="none">
      <CardHeader padding="lg" divider>
        <div className="flex items-center justify-between w-full flex-wrap gap-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-[var(--color-primary)]/20">
              <ShoppingCart className="w-5 h-5 text-[var(--color-primary)]" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-[var(--text-primary)]">
                {t('dashboard:sections.pending_po_approvals', 'Órdenes de Compra Pendientes')}
              </h3>
              <p className="text-sm text-[var(--text-secondary)]">
                {t('dashboard:po_approvals.title', '¿Qué órdenes debo aprobar?')}
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2 flex-wrap">
            {urgentPOs > 0 && (
              <Badge variant="error" size="sm">
                {urgentPOs} urgentes
              </Badge>
            )}
            {totalPOs > 0 && (
              <Badge variant="warning" size="sm">
                {totalPOs} pendientes
              </Badge>
            )}
            <div className="flex items-center gap-1 text-sm font-semibold text-[var(--text-primary)]">
              <Euro className="w-4 h-4" />
              <span>{formatCurrency(totalAmount)}</span>
            </div>
          </div>
        </div>
      </CardHeader>

      <CardBody padding="none">
        {displayPOs.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' }}
            >
              <CheckCircle className="w-8 h-8" style={{ color: 'var(--color-success)' }} />
            </div>
            <h4 className="text-lg font-medium mb-2 text-[var(--text-primary)]">
              {t('dashboard:po_approvals.empty', 'Sin órdenes pendientes de aprobación')}
            </h4>
            <p className="text-sm text-[var(--text-secondary)]">
              Todas las órdenes de compra están aprobadas o en proceso
            </p>
          </div>
        ) : (
          <div className="space-y-3 p-4">
            {displayPOs.map((po) => {
              const priorityConfig = getPOPriorityConfig(po.priority);
              const deliveryDate = po.required_delivery_date
                ? formatDate(po.required_delivery_date)
                : 'Sin fecha';

              const isApproving = approvingPO === po.id;
              const isRejecting = rejectingPO === po.id;

              return (
                <StatusCard
                  key={po.id}
                  id={po.id}
                  statusIndicator={priorityConfig}
                  title={po.supplier_name || 'Proveedor desconocido'}
                  subtitle={`PO #${po.po_number}`}
                  primaryValue={formatCurrency(po.total_amount, po.currency)}
                  primaryValueLabel="MONTO TOTAL"
                  secondaryInfo={{
                    label: 'Entrega requerida',
                    value: deliveryDate
                  }}
                  metadata={[
                    `📦 Orden: ${po.po_number}`,
                    `📅 Creada: ${new Date(po.created_at).toLocaleDateString('es-ES')}`,
                    `🚚 Entrega: ${deliveryDate}`,
                    ...(po.priority === 'urgent' ? [`⚠️ URGENTE - Requiere aprobación inmediata`] : []),
                    ...(po.priority === 'high' ? [`⚡ ALTA PRIORIDAD`] : [])
                  ]}
                  actions={[
                    {
                      label: isApproving ? 'Aprobando...' : 'Aprobar',
                      icon: CheckCircle,
                      variant: 'primary' as const,
                      onClick: () => handleApprovePO(po.id),
                      priority: 'primary' as const,
                      disabled: isApproving || isRejecting
                    },
                    {
                      label: isRejecting ? 'Rechazando...' : 'Rechazar',
                      icon: XCircle,
                      variant: 'outline' as const,
                      onClick: () => handleRejectPO(po.id),
                      priority: 'secondary' as const,
                      destructive: true,
                      disabled: isApproving || isRejecting
                    },
                    {
                      label: 'Ver Detalles',
                      icon: ChevronRight,
                      variant: 'outline' as const,
                      onClick: () => onViewDetails?.(po.id),
                      priority: 'secondary' as const
                    }
                  ]}
                  compact={true}
                  className="border-l-4"
                />
              );
            })}
          </div>
        )}

        {displayPOs.length > 0 && (
          <div
            className="p-4 border-t"
            style={{
              borderColor: 'var(--border-primary)',
              backgroundColor: 'var(--bg-secondary)'
            }}
          >
            <div className="flex items-center justify-between flex-wrap gap-2">
              <div className="text-sm">
                <span className="text-[var(--text-secondary)]">
                  {totalPOs} {t('dashboard:po_approvals.pos_pending', 'órdenes pendientes de aprobación')}
                </span>
                {urgentPOs > 0 && (
                  <span className="ml-2 text-[var(--color-error)] font-semibold">
                    • {urgentPOs} urgentes
                  </span>
                )}
              </div>

              {onViewAllPOs && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={onViewAllPOs}
                  className="flex items-center gap-2"
                >
                  Ver Todas las Órdenes
                  <ChevronRight className="w-4 h-4" />
                </Button>
              )}
            </div>
          </div>
        )}
      </CardBody>
    </Card>
  );
};

export default PendingPOApprovals;
