import React, { useState, useMemo } from 'react';
import { Plus, ShoppingCart, Euro, Calendar, CheckCircle, AlertCircle, Package, Eye, X, Send, Building2, Play, FileText, Star, TrendingUp, TrendingDown, Minus } from 'lucide-react';
import { Button, Card, StatsGrid, StatusCard, getStatusColor, EditViewModal, SearchAndFilter, Input, type FilterConfig, EmptyState } from '../../../../components/ui';
import { formatters } from '../../../../components/ui/Stats/StatsPresets';
import { PageHeader } from '../../../../components/layout';
import { UnifiedPurchaseOrderModal } from '../../../../components/domain/procurement/UnifiedPurchaseOrderModal';
import { UnifiedAddWizard } from '../../../../components/domain/unified-wizard';
import type { ItemType } from '../../../../components/domain/unified-wizard';
import {
  usePurchaseOrders,
  usePurchaseOrder,
  useApprovePurchaseOrder,
  useRejectPurchaseOrder,
  useUpdatePurchaseOrder
} from '../../../../api/hooks/purchase-orders';
import { useTriggerDailyScheduler } from '../../../../api';
import type { PurchaseOrderStatus, PurchaseOrderPriority, PurchaseOrderDetail } from '../../../../api/services/purchase_orders';
import { useTenantStore } from '../../../../stores/tenant.store';
import { useUserById } from '../../../../api/hooks/user';
import { showToast } from '../../../../utils/toast';
import { useTenantCurrency } from '../../../../hooks/useTenantCurrency';

const ProcurementPage: React.FC = () => {
  const { currencySymbol } = useTenantCurrency();

  // State
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<PurchaseOrderStatus | ''>('');
  const [priorityFilter, setPriorityFilter] = useState<PurchaseOrderPriority | ''>('');
  const [showArchived, setShowArchived] = useState(false);
  const [isWizardOpen, setIsWizardOpen] = useState(false);
  const [showDetailsModal, setShowDetailsModal] = useState(false);
  const [selectedPOId, setSelectedPOId] = useState<string | null>(null);
  const [showApprovalModal, setShowApprovalModal] = useState(false);
  const [approvalAction, setApprovalAction] = useState<'approve' | 'reject'>('approve');
  const [approvalNotes, setApprovalNotes] = useState('');

  const { currentTenant } = useTenantStore();
  const tenantId = currentTenant?.id || '';

  // API Hooks
  const { data: purchaseOrdersData = [], isLoading: isPOsLoading, refetch: refetchPOs } = usePurchaseOrders(
    tenantId,
    {
      status: statusFilter || undefined,
      priority: priorityFilter || undefined,
      search_term: searchTerm || undefined,
      limit: 100,
      offset: 0
    },
    {
      enabled: !!tenantId
    }
  );

  const { data: poDetails, isLoading: isLoadingDetails } = usePurchaseOrder(
    tenantId,
    selectedPOId || '',
    {
      enabled: !!tenantId && !!selectedPOId && showDetailsModal
    }
  );

  const approvePOMutation = useApprovePurchaseOrder();
  const rejectPOMutation = useRejectPurchaseOrder();
  const updatePOMutation = useUpdatePurchaseOrder();

  // Filter POs
  const filteredPOs = useMemo(() => {
    return purchaseOrdersData.filter(po => {
      // Hide archived POs by default
      if (!showArchived && (po.status === 'COMPLETED' || po.status === 'CANCELLED')) {
        return false;
      }
      return true;
    });
  }, [purchaseOrdersData, showArchived]);

  // Calculate stats
  const poStats = useMemo(() => {
    const total = filteredPOs.length;
    // API returns lowercase status values (e.g., 'pending_approval' not 'PENDING_APPROVAL')
    const pendingApproval = filteredPOs.filter(po => po.status === 'pending_approval').length;
    const approved = filteredPOs.filter(po => po.status === 'approved').length;
    const inProgress = filteredPOs.filter(po =>
      ['sent_to_supplier', 'confirmed'].includes(po.status)
    ).length;
    const received = filteredPOs.filter(po => po.status === 'received').length;
    const totalAmount = filteredPOs.reduce((sum, po) => {
      // API returns total_amount as a string, so parse it
      const amount = typeof po.total_amount === 'string'
        ? parseFloat(po.total_amount) || 0
        : typeof po.total_amount === 'number'
          ? po.total_amount
          : 0;
      return sum + amount;
    }, 0);

    return {
      total,
      pendingApproval,
      approved,
      inProgress,
      received,
      totalAmount
    };
  }, [filteredPOs]);

  // Handlers
  const handleViewDetails = (po: any) => {
    setSelectedPOId(po.id);
    setShowDetailsModal(true);
  };

  const handleApprovePO = (po: any) => {
    setSelectedPOId(po.id);
    setApprovalAction('approve');
    setApprovalNotes('');
    setShowApprovalModal(true);
  };

  const handleRejectPO = (po: any) => {
    setSelectedPOId(po.id);
    setApprovalAction('reject');
    setApprovalNotes('');
    setShowApprovalModal(true);
  };

  const handleSendToSupplier = async (po: any) => {
    try {
      await updatePOMutation.mutateAsync({
        tenantId,
        poId: po.id,
        data: { status: 'SENT_TO_SUPPLIER' }
      });
      showToast.success('Orden enviada al proveedor');
      refetchPOs();
    } catch (error) {
      console.error('Error sending PO to supplier:', error);
      showToast.error('Error al enviar orden al proveedor');
    }
  };

  const handleConfirmPO = async (po: any) => {
    try {
      await updatePOMutation.mutateAsync({
        tenantId,
        poId: po.id,
        data: { status: 'CONFIRMED' }
      });
      showToast.success('Orden confirmada');
      refetchPOs();
    } catch (error) {
      console.error('Error confirming PO:', error);
      showToast.error('Error al confirmar orden');
    }
  };

  const handleApprovalSubmit = async () => {
    if (!selectedPOId) return;

    try {
      if (approvalAction === 'approve') {
        await approvePOMutation.mutateAsync({
          tenantId,
          poId: selectedPOId,
          notes: approvalNotes || undefined
        });
        showToast.success('Orden aprobada exitosamente');
      } else {
        if (!approvalNotes.trim()) {
          showToast.error('Debes proporcionar una razón para rechazar');
          return;
        }
        await rejectPOMutation.mutateAsync({
          tenantId,
          poId: selectedPOId,
          reason: approvalNotes
        });
        showToast.success('Orden rechazada');
      }
      setShowApprovalModal(false);
      setShowDetailsModal(false);
      setApprovalNotes('');
      refetchPOs();
    } catch (error) {
      console.error('Error in approval action:', error);
      showToast.error('Error al procesar aprobación');
    }
  };

  const handleTriggerScheduler = async () => {
    try {
      await triggerSchedulerMutation.mutateAsync(tenantId);
      showToast.success('Scheduler ejecutado exitosamente');
      refetchPOs();
    } catch (error) {
      console.error('Error triggering scheduler:', error);
      showToast.error('Error al ejecutar scheduler');
    }
  };

  // Get PO status configuration
  const getPOStatusConfig = (status: PurchaseOrderStatus | string) => {
    // API returns lowercase status, normalize it
    const normalizedStatus = status?.toUpperCase().replace(/_/g, '_') as PurchaseOrderStatus;

    const configs: Record<string, any> = {
      DRAFT: {
        color: getStatusColor('neutral'),
        text: 'Borrador',
        icon: FileText,
        isCritical: false
      },
      PENDING_APPROVAL: {
        color: getStatusColor('warning'),
        text: 'Pendiente de Aprobación',
        icon: AlertCircle,
        isCritical: true
      },
      APPROVED: {
        color: getStatusColor('approved'),
        text: 'Aprobado',
        icon: CheckCircle,
        isCritical: false
      },
      SENT_TO_SUPPLIER: {
        color: getStatusColor('inProgress'),
        text: 'Enviado al Proveedor',
        icon: Send,
        isCritical: false
      },
      CONFIRMED: {
        color: getStatusColor('approved'),
        text: 'Confirmado',
        icon: CheckCircle,
        isCritical: false
      },
      RECEIVED: {
        color: getStatusColor('delivered'),
        text: 'Recibido',
        icon: Package,
        isCritical: false
      },
      COMPLETED: {
        color: getStatusColor('completed'),
        text: 'Completado',
        icon: CheckCircle,
        isCritical: false
      },
      CANCELLED: {
        color: getStatusColor('cancelled'),
        text: 'Cancelado',
        icon: X,
        isCritical: false
      },
      DISPUTED: {
        color: getStatusColor('expired'),
        text: 'En Disputa',
        icon: AlertCircle,
        isCritical: true
      }
    };

    // Return config or default if status is undefined/invalid
    return configs[normalizedStatus] || {
      color: getStatusColor('neutral'),
      text: status || 'Desconocido',
      icon: FileText,
      isCritical: false
    };
  };

  // Get quick actions for a PO based on status
  const getPOQuickActions = (po: any) => {
    const actions = [
      {
        label: 'Ver Detalles',
        icon: Eye,
        onClick: () => handleViewDetails(po),
        priority: 'primary' as const
      }
    ];

    if (po.status === 'pending_approval') {
      actions.push(
        {
          label: 'Aprobar',
          icon: CheckCircle,
          onClick: () => handleApprovePO(po),
          priority: 'primary' as const,
          variant: 'primary' as const
        },
        {
          label: 'Rechazar',
          icon: X,
          onClick: () => handleRejectPO(po),
          priority: 'secondary' as const,
          variant: 'outline' as const,
          destructive: true
        }
      );
    } else if (po.status === 'approved') {
      actions.push({
        label: 'Enviar al Proveedor',
        icon: Send,
        onClick: () => handleSendToSupplier(po),
        priority: 'primary' as const,
        variant: 'primary' as const
      });
    } else if (po.status === 'sent_to_supplier') {
      actions.push({
        label: 'Confirmar',
        icon: CheckCircle,
        onClick: () => handleConfirmPO(po),
        priority: 'primary' as const,
        variant: 'primary' as const
      });
    }

    return actions;
  };

  // Component to display user name with data fetching
  const UserName: React.FC<{ userId: string | undefined | null }> = ({ userId }) => {
    // Handle null/undefined
    if (!userId) return <>N/A</>;

    // Check for system/demo UUID patterns
    if (userId === '00000000-0000-0000-0000-000000000001' || userId === '00000000-0000-0000-0000-000000000000') {
      return <>Sistema</>;
    }

    // Fetch user data
    const { data: user, isLoading } = useUserById(userId, {
      retry: 1,
      staleTime: 10 * 60 * 1000, // 10 minutes
    });

    if (isLoading) return <>Cargando...</>;
    if (!user) return <>Usuario Desconocido</>;

    return <>{user.full_name || user.email || 'Usuario'}</>;
  };


  // Filters configuration
  const filterConfig: FilterConfig[] = [
    {
      key: 'status',
      type: 'dropdown',
      label: 'Estado',
      value: statusFilter,
      onChange: (value) => setStatusFilter(value as PurchaseOrderStatus | ''),
      placeholder: 'Todos los estados',
      options: [
        { value: 'DRAFT', label: 'Borrador' },
        { value: 'PENDING_APPROVAL', label: 'Pendiente de Aprobación' },
        { value: 'APPROVED', label: 'Aprobado' },
        { value: 'SENT_TO_SUPPLIER', label: 'Enviado al Proveedor' },
        { value: 'CONFIRMED', label: 'Confirmado' },
        { value: 'RECEIVED', label: 'Recibido' },
        { value: 'COMPLETED', label: 'Completado' },
        { value: 'CANCELLED', label: 'Cancelado' },
        { value: 'DISPUTED', label: 'En Disputa' }
      ]
    },
    {
      key: 'priority',
      type: 'dropdown',
      label: 'Prioridad',
      value: priorityFilter,
      onChange: (value) => setPriorityFilter(value as PurchaseOrderPriority | ''),
      placeholder: 'Todas las prioridades',
      options: [
        { value: 'urgent', label: 'Urgente' },
        { value: 'high', label: 'Alta' },
        { value: 'normal', label: 'Normal' },
        { value: 'low', label: 'Baja' }
      ]
    },
    {
      key: 'archived',
      type: 'checkbox',
      label: 'Mostrar Archivados',
      value: showArchived,
      onChange: setShowArchived
    }
  ];

  return (
    <div className="space-y-6">
      {/* Header */}
      <PageHeader
        title="Órdenes de Compra"
        description="Gestiona órdenes de compra y aprovisionamiento"
        actions={[
          {
            id: 'create-po',
            label: 'Nueva Orden',
            icon: Plus,
            onClick: () => setIsWizardOpen(true),
            variant: 'primary',
            size: 'md'
          }
        ]}
      />

      {/* Stats */}
      <StatsGrid
        columns={3}
        stats={[
          {
            title: 'Total de Órdenes',
            value: poStats.total,
            formatValue: formatters.number,
            icon: ShoppingCart,
            variant: 'info'
          },
          {
            title: 'Pendientes de Aprobación',
            value: poStats.pendingApproval,
            formatValue: formatters.number,
            icon: AlertCircle,
            variant: 'warning'
          },
          {
            title: 'Aprobadas',
            value: poStats.approved,
            formatValue: formatters.number,
            icon: CheckCircle,
            variant: 'success'
          },
          {
            title: 'En Proceso',
            value: poStats.inProgress,
            formatValue: formatters.number,
            icon: Package,
            variant: 'purple'
          },
          {
            title: 'Recibidas',
            value: poStats.received,
            formatValue: formatters.number,
            icon: CheckCircle,
            variant: 'success'
          },
          {
            title: 'Valor Total',
            value: poStats.totalAmount,
            formatValue: formatters.currency,
            icon: Euro,
            variant: 'success'
          }
        ]}
      />

      {/* Search and Filters */}
      <SearchAndFilter
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="Buscar por número de orden, proveedor..."
        filters={filterConfig}
      />

      {/* Purchase Orders Grid */}
      {isPOsLoading ? (
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
        </div>
      ) : filteredPOs.length === 0 ? (
        <EmptyState
          icon={ShoppingCart}
          title="No hay órdenes de compra"
          description="Comienza creando una nueva orden de compra"
          actionLabel="Nueva Orden"
          actionIcon={Plus}
          onAction={() => setIsWizardOpen(true)}
        />
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredPOs.map((po) => {
            const statusConfig = getPOStatusConfig(po.status);
            const priorityText = String(po.priority === 'urgent' ? 'Urgente' : po.priority === 'high' ? 'Alta' : po.priority === 'low' ? 'Baja' : 'Normal');

            // Parse total_amount - API returns it as a string
            const totalAmountNum = typeof po.total_amount === 'string'
              ? parseFloat(po.total_amount)
              : typeof po.total_amount === 'number'
                ? po.total_amount
                : 0;
            const totalAmount = String(totalAmountNum.toFixed(2));

            // items_count is not in the API response, so we don't show it
            const deliveryDate = String(po.required_delivery_date
              ? new Date(po.required_delivery_date).toLocaleDateString('es-ES', { month: 'short', day: 'numeric' })
              : 'Sin especificar');

            return (
              <StatusCard
                key={po.id}
                id={String(po.id)}
                title={String(po.po_number || 'Sin número')}
                subtitle={String(po.supplier_name || po.supplier?.name || 'Proveedor desconocido')}
                statusIndicator={statusConfig}
                primaryValue={`${currencySymbol}${totalAmount}`}
                primaryValueLabel="Total"
                metadata={[
                  `Prioridad: ${priorityText}`,
                  `Entrega: ${deliveryDate}`,
                  `Proveedor: ${po.supplier_name || 'Desconocido'}`
                ]}
                actions={getPOQuickActions(po)}
                onClick={() => handleViewDetails(po)}
              />
            );
          })}
        </div>
      )}

      {/* Unified Add Wizard for Purchase Orders */}
      <UnifiedAddWizard
        isOpen={isWizardOpen}
        onClose={() => setIsWizardOpen(false)}
        onComplete={(itemType: ItemType, data?: any) => {
          console.log('Purchase order created:', data);
          refetchPOs();
        }}
        initialItemType="purchase-order"
      />

      {/* PO Details Modal - Using Unified Component */}
      {showDetailsModal && selectedPOId && (
        <UnifiedPurchaseOrderModal
          poId={selectedPOId}
          tenantId={tenantId}
          isOpen={showDetailsModal}
          onClose={() => {
            setShowDetailsModal(false);
            setSelectedPOId(null);
            refetchPOs();
          }}
          onApprove={(poId) => {
            // Handle approve action - already handled in the unified modal
          }}
          onReject={(poId, reason) => {
            // Handle reject action - already handled in the unified modal
          }}
          showApprovalActions={true}
          initialMode="view"
        />
      )}
    </div>
  );
};

export default ProcurementPage;
