import React, { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { 
    Receipt, 
    Eye, 
    FileText, 
    RefreshCw, 
    Search,
    Calendar,
    User,
    DollarSign,
    Package,
    Truck,
    Mail,
    CheckCircle,
    Clock,
    XCircle,
    ExternalLink
} from "lucide-react";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog";
import { usePOSAttentionNumber } from "@/hooks/usePOSAttentionNumber";
import { TaxDocumentAPI } from "@/apis/TaxDocumentAPI";
import { toast } from "sonner";

export default function POSAttentionNumber() {
    const {
      selectedCompany,
      filteredSales,
      dteStatuses,
      isLoading,
      searchTerm,
      selectedSale,
      showDetailModal,
      setSearchTerm,
      setSelectedSale,
      setShowDetailModal,
      getCustomerById,
      sendEmail,
    } = usePOSAttentionNumber();

    const queryClient = useQueryClient();

    const [pdfLoadingId, setPdfLoadingId] = useState(null);
    const [dteLoadingId, setDteLoadingId] = useState(null);
    const [reprocessLoadingId, setReprocessLoadingId] = useState(null);

    const handleViewDetails = (sale) => {
        setSelectedSale(sale);
        setShowDetailModal(true);
    };

    const handleViewPDF = async (sale) => {
        if (pdfLoadingId === sale.id) return;
        setPdfLoadingId(sale.id);
        try {
            const doc = await TaxDocumentAPI.getBySaleId(sale.id);

            if (doc?.status === 'emitted' && doc?.pdf_url) {
                window.open(doc.pdf_url, '_blank');
                return;
            }

            if (doc?.status === 'emitted' && !doc?.pdf_url) {
                toast.info(`La boleta folio ${doc.folio} fue emitida pero el PDF aún no está disponible.`);
                return;
            }

            if (doc?.status === 'pending') {
                toast.info('El DTE está siendo procesado, intenta nuevamente en unos segundos.');
                return;
            }

            if (doc?.status === 'failed') {
                toast.error(`El DTE falló: ${doc.error_message ?? 'error desconocido'}. Usa "Reprocesar".`);
                return;
            }

            toast.info('Esta venta aún no tiene boleta electrónica emitida.');
        } catch (error) {
            console.error('Error al obtener PDF:', error);
            toast.error('Error al obtener el PDF de la boleta.');
        } finally {
            setPdfLoadingId(null);
        }
    };

    const handleViewDTE = async (sale) => {
        if (dteLoadingId === sale.id) return;
        setDteLoadingId(sale.id);
        try {
            const doc = await TaxDocumentAPI.getBySaleId(sale.id);
            if (!doc) {
                toast.info(`No hay DTE registrado para la venta ${sale.sale_number}.`);
                return;
            }
            if (doc.status === "emitted" && doc.pdf_url) {
                window.open(doc.pdf_url, "_blank");
            } else if (doc.status === "emitted") {
                toast.success(`DTE emitido (folio ${doc.folio ?? "N/A"}) para venta ${sale.sale_number}.`);
            } else if (doc.status === "pending") {
                toast.info(`El DTE para la venta ${sale.sale_number} está en proceso de emisión.`);
            } else if (doc.status === "failed") {
                toast.error(`El DTE para la venta ${sale.sale_number} falló: ${doc.error_message ?? "error desconocido"}.`);
            }
        } catch {
            toast.error("Error al consultar el DTE.");
        } finally {
            setDteLoadingId(null);
        }
    };

    const handleReprocessDTE = async (sale) => {
        if (reprocessLoadingId === sale.id) return;
        setReprocessLoadingId(sale.id);
        try {
            const result = await TaxDocumentAPI.reprocess(sale.id);
            if (result) {
                if (result.status === 'emitted') {
                    toast.success(`Boleta emitida correctamente para la venta ${sale.sale_number}.`);
                } else {
                    toast.info(`DTE reprocesado para la venta ${sale.sale_number}.`);
                }
                await queryClient.invalidateQueries({ queryKey: ['pos-sales'] });
            } else {
                toast.info(`No se encontró un DTE para la venta ${sale.sale_number}.`);
            }
        } catch {
            toast.error("Error al reprocesar el DTE.");
        } finally {
            setReprocessLoadingId(null);
        }
    };

    const handleSendDTEByEmail = async (sale) => {
        if (!sale.customer_id) {
            toast.error("Esta venta no tiene un cliente asociado con email");
            return;
        }

        try {
            const customer = await getCustomerById(sale.customer_id);
            
            if (!customer.email) {
                toast.error("El cliente no tiene email registrado");
                return;
            }

            const confirmSend = confirm(`¿Enviar DTE de venta ${sale.sale_number} al email ${customer.email}?`);
            
            if (confirmSend) {
                // Aquí iría la integración con el servicio de email
                await sendEmail({
                    to: customer.email,
                    subject: `DTE - Venta N° ${sale.sale_number}`,
                    body: `
                        <h2>Documento Tributario Electrónico</h2>
                        <p>Estimado/a ${customer.name},</p>
                        <p>Adjunto encontrará el DTE correspondiente a su compra:</p>
                        <ul>
                            <li><strong>N° Venta:</strong> ${sale.sale_number}</li>
                            <li><strong>Fecha:</strong> ${new Date(sale.sale_date).toLocaleDateString('es-CL')}</li>
                            <li><strong>Total:</strong> ${sale.total?.toLocaleString('es-CL')}</li>
                        </ul>
                        <p>Gracias por su preferencia.</p>
                        <p><em>${selectedCompany?.name || 'Mi Empresa'}</em></p>
                    `
                });
                
                toast.success(`DTE enviado exitosamente a ${customer.email}`);
            }
        } catch (error) {
            console.error('Error enviando DTE:', error);
            toast.error("Error al enviar el DTE por correo");
        }
    };

    const getStatusColor = (status) => {
        switch (status) {
            case 'completed': return 'bg-green-100 text-green-800';
            case 'pending': return 'bg-yellow-100 text-yellow-800';
            case 'cancelled': return 'bg-red-100 text-red-800';
            default: return 'bg-gray-100 text-gray-800';
        }
    };

    const getStatusLabel = (status) => {
        switch (status) {
            case 'completed': return 'Completada';
            case 'pending': return 'Pendiente';
            case 'cancelled': return 'Cancelada';
            default: return status;
        }
    };

    const getItemsTotal = (sale) =>
        (Array.isArray(sale?.items) ? sale.items : []).reduce(
            (sum, item) => sum + Number(item?.total || 0),
            0
        );

    const getInferredShipping = (sale) => {
        const subtotal = Number(sale?.subtotal || 0);
        const itemsTotal = getItemsTotal(sale);
        const shipping = subtotal - itemsTotal;
        return shipping > 0 ? shipping : 0;
    };

    if (isLoading) {
        return (
            <div className="p-6">
                <div className="text-center py-12">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
                    <p className="mt-4 text-gray-600">Cargando ventas...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="p-6 space-y-6">
            {/* Header */}
            <div className="flex justify-between items-center">
                <div>
                    <h1 className="text-3xl font-bold text-gradient">N° Atención POS</h1>
                    <p className="text-gray-600 mt-1">Historial de ventas procesadas</p>
                </div>
                <div className="flex items-center gap-2">
                    <Badge className="bg-blue-100 text-blue-800 text-lg px-4 py-2">
                        {filteredSales.length} Ventas
                    </Badge>
                </div>
            </div>

            {/* Search */}
            <Card className="glass-card">
                <CardContent className="p-4">
                    <div className="relative">
                        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <Input
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            placeholder="Buscar por N° atención o cliente..."
                            className="pl-10 text-lg"
                        />
                    </div>
                </CardContent>
            </Card>

            {/* Sales List */}
            <div className="space-y-3">
                {filteredSales.length === 0 ? (
                    <Card className="glass-card">
                        <CardContent className="p-12 text-center">
                            <Receipt className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                            <p className="text-xl text-gray-500">
                                {searchTerm ? 'No se encontraron ventas' : 'No hay ventas registradas'}
                            </p>
                        </CardContent>
                    </Card>
                ) : (
                    filteredSales.map((sale) => (
                        <Card key={sale.id} className="glass-card hover:shadow-lg transition-all">
                            <CardContent className="p-4">
                                <div className="flex items-start justify-between gap-4">
                                    <div className="flex-1 grid grid-cols-1 md:grid-cols-6 gap-3 md:gap-4 min-w-0">
                                        {/* N° Atención */}
                                        <div className="min-w-0">
                                            <p className="text-xs text-gray-500 mb-1">N° Atención</p>
                                            <p className="font-bold text-base md:text-lg text-blue-600 leading-tight whitespace-nowrap overflow-hidden text-ellipsis">
                                                {sale.sale_number}
                                            </p>
                                        </div>

                                        {/* Fecha */}
                                        <div className="min-w-0">
                                            <p className="text-xs text-gray-500 mb-1">Fecha</p>
                                            <div className="flex items-center gap-1">
                                                <Calendar className="w-4 h-4 text-gray-400" />
                                                <p className="text-sm font-medium whitespace-nowrap">
                                                    {new Date(sale.sale_date).toLocaleDateString('es-CL')}
                                                </p>
                                            </div>
                                            <p className="text-xs text-gray-500 whitespace-nowrap">
                                                {new Date(sale.sale_date).toLocaleTimeString('es-CL', { 
                                                    hour: '2-digit', 
                                                    minute: '2-digit' 
                                                })}
                                            </p>
                                        </div>

                                        {/* Cliente */}
                                        <div className="min-w-0">
                                            <p className="text-xs text-gray-500 mb-1">Cliente</p>
                                            <div className="flex items-center gap-1">
                                                <User className="w-4 h-4 text-gray-400" />
                                                <p className="text-sm font-medium truncate">
                                                    {sale.customer_name || 'Cliente General'}
                                                </p>
                                            </div>
                                        </div>

                                        {/* Transporte */}
                                        <div className="min-w-0">
                                            <p className="text-xs text-gray-500 mb-1">Transporte</p>
                                            <div className="flex items-center gap-1">
                                                <Truck className="w-4 h-4 text-blue-600" />
                                                <p className="text-sm font-medium truncate">
                                                    {sale.shipping_info?.shipping_type === 'pickup' 
                                                        ? 'Retiro Tienda'
                                                        : sale.shipping_info?.shipping_company_name || 'Sin Transporte'}
                                                </p>
                                            </div>
                                        </div>

                                        {/* Total */}
                                        <div className="min-w-0">
                                            <p className="text-xs text-gray-500 mb-1">Total</p>
                                            <div className="flex items-center gap-1">
                                                <p className="text-base md:text-lg font-bold text-green-600 whitespace-nowrap">
                                                    ${sale.total?.toLocaleString('es-CL') || 0}
                                                </p>
                                            </div>
                                        </div>

                                        {/* Estado */}
                                        <div className="min-w-0">
                                            <p className="text-xs text-gray-500 mb-1">Estado</p>
                                            <Badge className={getStatusColor(sale.status)}>
                                                {getStatusLabel(sale.status)}
                                            </Badge>
                                        </div>
                                    </div>

                                    {/* Acciones */}
                                    <div className="flex flex-wrap justify-end gap-2 ml-0 md:ml-4 shrink-0">
                                        <Button
                                            size="sm"
                                            variant="outline"
                                            onClick={() => handleViewDetails(sale)}
                                            className="flex items-center gap-1"
                                        >
                                            <Eye className="w-4 h-4" />
                                            Ver
                                        </Button>
                                        <Button
                                            size="sm"
                                            variant="outline"
                                            onClick={() => handleViewPDF(sale)}
                                            disabled={pdfLoadingId === sale.id}
                                            className="flex items-center gap-1"
                                        >
                                            {pdfLoadingId === sale.id
                                                ? <Clock className="w-4 h-4 animate-spin" />
                                                : <FileText className="w-4 h-4" />
                                            }
                                            PDF
                                        </Button>
                                        <Button
                                            size="sm"
                                            variant="outline"
                                            onClick={() => handleViewDTE(sale)}
                                            disabled={dteLoadingId === sale.id}
                                            className="flex items-center gap-1 bg-blue-50"
                                        >
                                            {dteLoadingId === sale.id
                                                ? <Clock className="w-4 h-4 animate-spin" />
                                                : <Receipt className="w-4 h-4" />
                                            }
                                            DTE
                                        </Button>
                                        {dteStatuses[sale.id]?.status !== 'emitted' && (
                                            <Button
                                                size="sm"
                                                variant="outline"
                                                onClick={() => handleReprocessDTE(sale)}
                                                disabled={reprocessLoadingId === sale.id}
                                                className="flex items-center gap-1 bg-orange-50"
                                            >
                                                <RefreshCw className={`w-4 h-4 ${reprocessLoadingId === sale.id ? "animate-spin" : ""}`} />
                                                Reprocesar
                                            </Button>
                                        )}
                                        <Button
                                            size="sm"
                                            variant="outline"
                                            onClick={() => handleSendDTEByEmail(sale)}
                                            className="flex items-center gap-1 bg-green-50"
                                            disabled={!sale.customer_id}
                                        >
                                            <Mail className="w-4 h-4" />
                                            Enviar
                                        </Button>
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    ))
                )}
            </div>

            {/* Detail Modal */}
            {selectedSale && (
                <Dialog open={showDetailModal} onOpenChange={setShowDetailModal}>
                    <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
                        <DialogHeader>
                            <DialogTitle className="text-2xl">
                                Detalle de Venta - {selectedSale.sale_number}
                            </DialogTitle>
                        </DialogHeader>

                        <div className="space-y-4">
                            {/* Header Info */}
                            <div className="grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-lg">
                                <div>
                                    <p className="text-sm text-gray-600">Fecha</p>
                                    <p className="font-medium">
                                        {new Date(selectedSale.sale_date).toLocaleString('es-CL')}
                                    </p>
                                </div>
                                <div>
                                    <p className="text-sm text-gray-600">Cliente</p>
                                    <p className="font-medium">{selectedSale.customer_name || 'Cliente General'}</p>
                                </div>
                                <div>
                                    <p className="text-sm text-gray-600">Estado</p>
                                    <Badge className={getStatusColor(selectedSale.status)}>
                                        {getStatusLabel(selectedSale.status)}
                                    </Badge>
                                </div>
                                <div>
                                    <p className="text-sm text-gray-600">Moneda</p>
                                    <p className="font-medium">{selectedSale.currency || 'CLP'}</p>
                                </div>
                                {selectedSale.shipping_info && (
                                    <>
                                        <div>
                                            <p className="text-sm text-gray-600">Tipo de Entrega</p>
                                            <div className="flex items-center gap-1">
                                                <Truck className="w-4 h-4 text-blue-600" />
                                                <p className="font-medium">
                                                    {selectedSale.shipping_info.shipping_type === 'pickup' 
                                                        ? 'Retiro en Tienda'
                                                        : 'Despacho a Domicilio'}
                                                </p>
                                            </div>
                                        </div>
                                        <div>
                                            <p className="text-sm text-gray-600">Transportista</p>
                                            <p className="font-medium">
                                                {selectedSale.shipping_info.shipping_company_name || 'Sin Transporte'}
                                            </p>
                                        </div>
                                    </>
                                )}
                            </div>

                            {/* Items */}
                            <div>
                                <h3 className="font-semibold mb-3 flex items-center gap-2">
                                    <Package className="w-5 h-5" />
                                    Productos
                                </h3>
                                <div className="space-y-2">
                                    {(Array.isArray(selectedSale.items) ? selectedSale.items : []).map((item, index) => (
                                        <div key={index} className="flex justify-between items-center p-3 bg-white border rounded-lg">
                                            <div className="flex-1">
                                                <p className="font-medium">{item.name}</p>
                                                <p className="text-sm text-gray-500">SKU: {item.sku}</p>
                                            </div>
                                            <div className="text-right">
                                                <p className="text-sm text-gray-600">
                                                    {item.quantity} x ${item.price?.toLocaleString('es-CL')}
                                                </p>
                                                <p className="font-bold">
                                                    ${item.total?.toLocaleString('es-CL')}
                                                </p>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {/* Totals */}
                            <div className="space-y-2 p-4 bg-gray-50 rounded-lg">
                                {getInferredShipping(selectedSale) > 0 && (
                                    <div className="flex justify-between">
                                        <span className="text-gray-600">Productos:</span>
                                        <span className="font-medium">
                                            ${getItemsTotal(selectedSale).toLocaleString('es-CL')}
                                        </span>
                                    </div>
                                )}
                                <div className="flex justify-between">
                                    <span className="text-gray-600">Subtotal:</span>
                                    <span className="font-medium">
                                        ${selectedSale.subtotal?.toLocaleString('es-CL') || 0}
                                    </span>
                                </div>
                                {getInferredShipping(selectedSale) > 0 && (
                                    <div className="flex justify-between text-blue-700">
                                        <span>Despacho:</span>
                                        <span className="font-medium">
                                            ${getInferredShipping(selectedSale).toLocaleString('es-CL')}
                                        </span>
                                    </div>
                                )}
                                {selectedSale.tax_amount > 0 && (
                                    <div className="flex justify-between">
                                        <span className="text-gray-600">IVA:</span>
                                        <span className="font-medium">
                                            ${selectedSale.tax_amount?.toLocaleString('es-CL')}
                                        </span>
                                    </div>
                                )}
                                {selectedSale.discount_amount > 0 && (
                                    <div className="flex justify-between text-red-600">
                                        <span>Descuento:</span>
                                        <span className="font-medium">
                                            -${selectedSale.discount_amount?.toLocaleString('es-CL')}
                                        </span>
                                    </div>
                                )}
                                <div className="flex justify-between text-xl font-bold pt-2 border-t">
                                    <span>Total:</span>
                                    <span className="text-green-600">
                                        ${selectedSale.total?.toLocaleString('es-CL') || 0}
                                    </span>
                                </div>
                            </div>

                            {/* Payments */}
                            {Array.isArray(selectedSale.payments) && selectedSale.payments.length > 0 && (
                                <div>
                                    <h3 className="font-semibold mb-3">Formas de Pago</h3>
                                    <div className="space-y-2">
                                        {selectedSale.payments.map((payment, index) => (
                                            <div key={index} className="flex justify-between p-3 bg-white border rounded-lg">
                                                <span>{payment.payment_method_name}</span>
                                                <span className="font-medium">
                                                    ${payment.amount?.toLocaleString('es-CL')}
                                                </span>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {selectedSale.notes && (
                                <div>
                                    <h3 className="font-semibold mb-2">Notas</h3>
                                    <p className="text-sm text-gray-600 p-3 bg-gray-50 rounded-lg">
                                        {selectedSale.notes}
                                    </p>
                                </div>
                            )}
                        </div>
                    </DialogContent>
                </Dialog>
            )}
        </div>
    );
}