// @ts-nocheck
import React from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Star, Gift, TrendingUp, Users, Plus, Minus, Edit, History, Clock } from "lucide-react";
import { toast } from "sonner";
import { useCustomerPoints } from "@/hooks/useCustomerPoints";
import { usePoints } from "@/hooks/usePoints";

export default function CustomerPointsPage() {
  const {
    selectedCompany,
    config,
    filteredCustomers,
    showRedeemDialog,
    showAdjustDialog,
    showCommissionDialog,
    selectedCustomer,
    searchTerm,
    activeTab,
    adjustmentData,
    commissionAmount,
    totals,
    isAdjusting,
    isRedeemingCommission,
    showHistoryDialog,
    setShowHistoryDialog,
    setShowRedeemDialog,
    setShowAdjustDialog,
    setShowCommissionDialog,
    setSelectedCustomer,
    setSearchTerm,
    setActiveTab,
    setAdjustmentData,
    setCommissionAmount,
    adjustPoints,
    redeemCommission,
  } = useCustomerPoints();

  const { 
        history: transactions,
        isHistoryLoading 
    } = usePoints(selectedCustomer?.id);

    // LOG PARA DEBUG: Ver qué llega a la vista
    console.log("DEBUG: Transactions in View:", {
        isLoading: isHistoryLoading,
        count: transactions?.length,
        data: transactions,
        selectedId: selectedCustomer?.id
    });

  const handleAdjustment = async (type) => {
    try {
      await adjustPoints(type);
      toast.success("Puntos actualizados exitosamente");
    } catch (error) {
      toast.error("Error al actualizar puntos: " + error.message);
    }
  };

    if (!selectedCompany) {
        return (
            <div className="flex items-center justify-center h-screen">
                <p className="text-gray-500">Cargando...</p>
            </div>
        );
    }

    return (
        <div className="p-6 max-w-7xl mx-auto space-y-6">
            <div>
                <h1 className="text-3xl font-bold text-gray-900">Puntos y Comisiones</h1>
                <p className="text-gray-500 mt-1">Gestiona puntos y comisiones de clientes</p>
            </div>

            <div className="flex gap-2">
                <Button
                    variant={activeTab === "points" ? "default" : "outline"}
                    onClick={() => setActiveTab("points")}
                >
                    <Star className="w-4 h-4 mr-2" />
                    Puntos
                </Button>
                <Button
                    variant={activeTab === "commissions" ? "default" : "outline"}
                    onClick={() => setActiveTab("commissions")}
                >
                    <Gift className="w-4 h-4 mr-2" />
                    Comisiones
                </Button>
            </div>

            {activeTab === "points" ? (
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <Card>
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-yellow-100 rounded-lg">
                                    <Star className="w-6 h-6 text-yellow-600" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-500">Total Puntos</p>
                                    <p className="text-2xl font-bold">{totals.totalPoints.toLocaleString()}</p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-blue-100 rounded-lg">
                                    <Users className="w-6 h-6 text-blue-600" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-500">Clientes con Puntos</p>
                                    <p className="text-2xl font-bold">{totals.customersWithPoints}</p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-green-100 rounded-lg">
                                    <TrendingUp className="w-6 h-6 text-green-600" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-500">$ por Punto</p>
                                    <p className="text-2xl font-bold">${config?.amount_per_point || 100}</p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <Card>
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-green-100 rounded-lg">
                                    <Gift className="w-6 h-6 text-green-600" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-500">Total Comisiones</p>
                                    <p className="text-2xl font-bold">${totals.totalCommissions.toLocaleString()}</p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-blue-100 rounded-lg">
                                    <Users className="w-6 h-6 text-blue-600" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-500">Clientes con Comisiones</p>
                                    <p className="text-2xl font-bold">{totals.customersWithCommissions}</p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-purple-100 rounded-lg">
                                    <TrendingUp className="w-6 h-6 text-purple-600" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-500">Bonificación Canje</p>
                                    <p className="text-2xl font-bold">{config?.commission_bonus_percentage || 30}%</p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </div>
            )}

            <Card>
                <CardContent className="pt-6">
                    <Input
                        placeholder="Buscar cliente..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                    />
                </CardContent>
            </Card>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {activeTab === "points" ? (
                    filteredCustomers.map((customer) => (
                        <Card key={customer.id} className="hover:shadow-lg transition-shadow">
                            <CardHeader className="pb-3">
                                <div className="flex justify-between items-start">
                                    <div className="flex-1">
                                        <CardTitle className="text-lg">{customer.name}</CardTitle>
                                        <p className="text-sm text-gray-500">{customer.email}</p>
                                    </div>
                                    <Badge className="bg-yellow-100 text-yellow-800">
                                        <Star className="w-3 h-3 mr-1" />
                                        {customer.accumulated_points || 0}
                                    </Badge>
                                </div>
                            </CardHeader>
                            <CardContent>
                                <div className="flex gap-2">
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => {
                                            setSelectedCustomer(customer);
                                            setShowHistoryDialog(true);
                                        }}
                                        title="Ver historial de puntos"
                                        className="px-2"
                                    >
                                        <History className="w-4 h-4" />
                                    </Button>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => {
                                            setSelectedCustomer(customer);
                                            setShowAdjustDialog(true);
                                        }}
                                        className="flex-1"
                                    >
                                        <Edit className="w-3 h-3 mr-1" />
                                        Ajustar
                                    </Button>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => {
                                            setSelectedCustomer(customer);
                                            setShowRedeemDialog(true);
                                        }}
                                        className="flex-1"
                                        disabled={(customer.accumulated_points || 0) < (config?.min_points_for_redemption || 2500)}
                                    >
                                        <Gift className="w-3 h-3 mr-1" />
                                        Canjear
                                    </Button>
                                </div>
                            </CardContent>
                        </Card>
                    ))
                ) : (
                    filteredCustomers.map((customer) => (
                        <Card key={customer.id} className="hover:shadow-lg transition-shadow">
                            <CardHeader className="pb-3">
                                <div className="flex justify-between items-start">
                                    <div className="flex-1">
                                        <CardTitle className="text-lg">{customer.name}</CardTitle>
                                        <p className="text-sm text-gray-500">{customer.email}</p>
                                    </div>
                                    <Badge className="bg-green-100 text-green-800">
                                        ${(customer.accumulated_commissions || 0).toLocaleString()}
                                    </Badge>
                                </div>
                            </CardHeader>
                            <CardContent>
                                <div className="mb-3 text-sm text-gray-600">
                                    <p>Con bonificación: <span className="font-bold text-green-600">
                                        ${((customer.accumulated_commissions || 0) * (1 + (config?.commission_bonus_percentage || 30) / 100)).toLocaleString()}
                                    </span></p>
                                </div>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => {
                                        setSelectedCustomer(customer);
                                        setCommissionAmount(customer.accumulated_commissions || 0);
                                        setShowCommissionDialog(true);
                                    }}
                                    className="w-full"
                                    disabled={(customer.accumulated_commissions || 0) === 0}
                                >
                                    <Gift className="w-3 h-3 mr-1" />
                                    Canjear Comisión
                                </Button>
                            </CardContent>
                        </Card>
                    ))
                )}
            </div>

            <Dialog open={showAdjustDialog} onOpenChange={setShowAdjustDialog}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Ajustar Puntos - {selectedCustomer?.name}</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                        <div className="p-3 bg-gray-50 rounded-lg">
                            <p className="text-sm text-gray-600">Puntos actuales</p>
                            <p className="text-2xl font-bold">{selectedCustomer?.accumulated_points || 0}</p>
                        </div>

                        <div>
                            <Label>Cantidad de Puntos *</Label>
                            <Input
                                type="number"
                                min="0"
                                value={adjustmentData.points}
                                onChange={(e) => setAdjustmentData({ ...adjustmentData, points: parseInt(e.target.value) || 0 })}
                                placeholder="0"
                            />
                        </div>

                        <div>
                            <Label>Descripción</Label>
                            <Textarea
                                value={adjustmentData.description}
                                onChange={(e) => setAdjustmentData({ ...adjustmentData, description: e.target.value })}
                                placeholder="Motivo del ajuste"
                                rows={2}
                            />
                        </div>
                    </div>
                    <DialogFooter className="gap-2">
                        <Button 
                            variant="outline" 
                            onClick={() => setShowAdjustDialog(false)}
                        >
                            Cancelar
                        </Button>
                        <Button 
                            variant="destructive"
                            onClick={() => handleAdjustment("remove")}
                            disabled={adjustmentData.points > (selectedCustomer?.accumulated_points || 0)}
                        >
                            <Minus className="w-4 h-4 mr-2" />
                            Restar
                        </Button>
                        <Button 
                            onClick={() => handleAdjustment("add")}
                            className="bg-green-600 hover:bg-green-700"
                            disabled={isAdjusting}
                        >
                            <Plus className="w-4 h-4 mr-2" />
                            Sumar
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <Dialog open={showRedeemDialog} onOpenChange={setShowRedeemDialog}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Canje de Puntos - {selectedCustomer?.name}</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                        <div className="p-3 bg-gray-50 rounded-lg">
                            <p className="text-sm text-gray-600">Puntos disponibles</p>
                            <p className="text-2xl font-bold">{selectedCustomer?.accumulated_points || 0}</p>
                        </div>

                        <div>
                            <Label>Puntos a Canjear *</Label>
                            <Input
                                type="number"
                                min="0"
                                max={selectedCustomer?.accumulated_points || 0}
                                value={adjustmentData.points}
                                onChange={(e) => setAdjustmentData({ ...adjustmentData, points: parseInt(e.target.value) || 0 })}
                                placeholder="0"
                            />
                        </div>

                        <div>
                            <Label>Descripción del Canje</Label>
                            <Textarea
                                value={adjustmentData.description}
                                onChange={(e) => setAdjustmentData({ ...adjustmentData, description: e.target.value })}
                                placeholder="Ej: Canje por descuento, regalo, etc."
                                rows={2}
                            />
                        </div>

                        <div className="space-y-2">
                            <div className="p-3 bg-blue-50 rounded-lg">
                                <p className="text-sm text-blue-600">
                                    Puntos restantes: {(selectedCustomer?.accumulated_points || 0) - adjustmentData.points}
                                </p>
                            </div>
                            {(config?.min_points_for_redemption || 0) > 0 && (
                                <p className="text-xs text-gray-500">
                                    * Mínimo requerido para canje: {config.min_points_for_redemption} puntos
                                </p>
                            )}
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setShowRedeemDialog(false)}>
                            Cancelar
                        </Button>
                        <Button 
                            onClick={() => handleAdjustment("remove")}
                            className="bg-orange-600 hover:bg-orange-700"
                            disabled={adjustmentData.points > (selectedCustomer?.accumulated_points || 0) || adjustmentData.points <= 0}
                        >
                            <Gift className="w-4 h-4 mr-2" />
                            Confirmar Canje
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <Dialog open={showCommissionDialog} onOpenChange={setShowCommissionDialog}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Canje de Comisión - {selectedCustomer?.name}</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                        <div className="p-3 bg-gray-50 rounded-lg">
                            <p className="text-sm text-gray-600">Comisión disponible</p>
                            <p className="text-2xl font-bold">${(selectedCustomer?.accumulated_commissions || 0).toLocaleString()}</p>
                        </div>

                        <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
                            <p className="text-sm font-medium text-green-800 mb-2">Bonificación del {config?.commission_bonus_percentage || 30}%</p>
                            <p className="text-sm text-green-700">
                                Al canjear ${commissionAmount.toLocaleString()}, recibirás:
                            </p>
                            <p className="text-3xl font-bold text-green-600 mt-2">
                                ${(commissionAmount * (1 + (config?.commission_bonus_percentage || 30) / 100)).toLocaleString()}
                            </p>
                        </div>

                        <div>
                            <Label>Monto a Canjear</Label>
                            <Input
                                type="number"
                                min="0"
                                max={selectedCustomer?.accumulated_commissions || 0}
                                value={commissionAmount}
                                onChange={(e) => setCommissionAmount(parseFloat(e.target.value) || 0)}
                                placeholder="0"
                            />
                        </div>

                        <div className="p-3 bg-blue-50 rounded-lg">
                            <p className="text-sm text-blue-600">
                                Comisión restante: ${((selectedCustomer?.accumulated_commissions || 0) - commissionAmount).toLocaleString()}
                            </p>
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setShowCommissionDialog(false)}>
                            Cancelar
                        </Button>
                        <Button 
                            onClick={async () => {
                                try {
                                    await redeemCommission();
                                    toast.success("Comisión canjeada exitosamente");
                                } catch (error) {
                                    toast.error("Error al canjear comisión: " + error.message);
                                }
                            }}
                            className="bg-green-600 hover:bg-green-700"
                            disabled={
                                commissionAmount > (selectedCustomer?.accumulated_commissions || 0) ||
                                commissionAmount <= 0 ||
                                isRedeemingCommission
                            }
                        >
                            <Gift className="w-4 h-4 mr-2" />
                            Confirmar Canje
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
            
            <Dialog open={showHistoryDialog} onOpenChange={setShowHistoryDialog}>
                <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>Historial de Puntos - {selectedCustomer?.name}</DialogTitle>
                    </DialogHeader>
                    <DialogDescription>
                        Aquí puedes ver el detalle de tus movimientos.
                    </DialogDescription>
                    
                    <div className="space-y-4">
                        <div className="rounded-md border">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Fecha</TableHead>
                                        <TableHead>Tipo</TableHead>
                                        <TableHead>Descripción</TableHead>
                                        <TableHead>Vencimiento</TableHead>
                                        <TableHead className="text-right">Puntos</TableHead>
                                        <TableHead className="text-right">Saldo</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {isHistoryLoading ? (
                                        <TableRow>
                                        <TableCell colSpan={6} className="text-center py-8">
                                            <div className="flex flex-col items-center gap-2">
                                            <span className="animate-spin h-5 w-5 border-2 border-primary border-t-transparent rounded-full" />
                                            <p className="text-sm text-muted-foreground">Cargando historial...</p>
                                            </div>
                                        </TableCell>
                                        </TableRow>
                                    ) : transactions && transactions.length > 0 ? (
                                        transactions.map((t) => (
                                        <TableRow key={t.id} className="hover:bg-gray-50/50">
                                            <TableCell className="text-sm text-gray-600">
                                            {new Date(t.transaction_date).toLocaleDateString()}
                                            </TableCell>
                                            <TableCell>
                                            <span className={`px-2 py-1 rounded-full text-[10px] font-bold uppercase ${
                                                t.transaction_type === 'accumulation' 
                                                ? 'bg-green-100 text-green-700' 
                                                : t.transaction_type === 'redemption' 
                                                    ? 'bg-blue-100 text-blue-700' 
                                                    : 'bg-gray-100 text-gray-700'
                                            }`}>
                                                {t.transaction_type}
                                            </span>
                                            </TableCell>
                                            <TableCell className="max-w-[200px] truncate text-sm" title={t.description}>
                                            {t.description || '-'}
                                            </TableCell>
                                            <TableCell className="text-sm text-gray-500 italic">
                                            {t.expires_at && (t.transaction_type === 'accumulation' || t.transaction_type === 'adjustment') ? (
                                                new Date(t.expires_at).toLocaleDateString()
                                            ) : (
                                                <span className="text-gray-300">-</span>
                                            )}
                                            </TableCell>
                                            <TableCell className={`text-right font-semibold ${
                                            t.points >= 0 ? "text-green-600" : "text-red-600"
                                            }`}>
                                            {t.points >= 0 ? `+${t.points}` : t.points}
                                            </TableCell>
                                            <TableCell className="text-right font-bold text-gray-900">
                                            {t.balance_after}
                                            </TableCell>
                                        </TableRow>
                                        ))
                                    ) : (
                                        <TableRow>
                                        <TableCell colSpan={6} className="text-center py-10 text-gray-500">
                                            <p>No hay movimientos registrados para este cliente.</p>
                                        </TableCell>
                                        </TableRow>
                                    )}
                                    </TableBody>
                            </Table>
                        </div>
                    </div>

                    <DialogFooter>
                        <Button variant="outline" onClick={() => setShowHistoryDialog(false)}>
                            Cerrar
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
}
