import {
    Assignment,
    CheckCircle,
    FilterList,
    Person,
    Receipt,
    Search,
} from "@mui/icons-material";
import {
    Box,
    Button,
    Card,
    CardContent,
    Checkbox,
    Chip,
    CircularProgress,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    Divider,
    FormControl,
    InputAdornment,
    InputLabel,
    MenuItem,
    Pagination,
    Paper,
    Select,
    Skeleton,
    Stack,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    TextField,
    Typography,
    useMediaQuery,
    useTheme,
} from "@mui/material";
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { memo, useRef, useState, useCallback } from "react";
import { toast } from "sonner";
import { getEmpresaMonedas } from "../../../api/monedas.service";
import {
    asignarCobradorMasivo,
    asignarVendedor,
    getCobradoresActivos,
    getFacturasPendientes,
    getResumenCobradores,
    getVendedoresActivos,
    getVendedoresCobradores,
} from "../../../api/vendedores-cobradores.service";
import { usePermission } from "../../../hooks/usePermission";
import { AccesoRestringido } from "../../common/AccesoRestringido";

const PAGE_SIZE = 50;

/** Input de búsqueda con estado propio — evita re-render del padre en cada tecla */
const SearchInput = memo(({ onSearch, isFetching }) => {
    const [value, setValue] = useState("");
    const debounceRef = useRef(null);

    const handleChange = (e) => {
        const val = e.target.value;
        setValue(val);
        clearTimeout(debounceRef.current);
        debounceRef.current = setTimeout(() => onSearch(val), 400);
    };

    return (
        <TextField
            size="small"
            placeholder="Buscar factura o cliente..."
            value={value}
            onChange={handleChange}
            sx={{ flex: "1 1 160px", minWidth: 140 }}
            InputProps={{
                startAdornment: <InputAdornment position="start"><Search fontSize="small" /></InputAdornment>,
                endAdornment: isFetching
                    ? <InputAdornment position="end"><CircularProgress size={14} /></InputAdornment>
                    : null,
            }}
        />
    );
});

const AssignSelect = ({ value, options, onChange, disabled }) => (
    <FormControl size="small" sx={{ minWidth: 140 }} disabled={disabled}>
        <Select
            value={value || ""}
            displayEmpty
            onChange={(e) => onChange(e.target.value || null)}
            sx={{ fontSize: "0.8rem" }}
        >
            <MenuItem value="">
                <em style={{ color: "#999" }}>Sin asignar</em>
            </MenuItem>
            {options.map((o) => (
                <MenuItem key={o.id} value={o.id}>
                    {o.nombre} {o.apellido || ""}
                </MenuItem>
            ))}
        </Select>
    </FormControl>
);

const FacturaSkeleton = () => (
    <>
        {[1, 2, 3, 4, 5].map((i) => (
            <TableRow key={i}>
                <TableCell padding="checkbox"><Skeleton variant="rectangular" width={18} height={18} /></TableCell>
                <TableCell><Skeleton width={120} /><Skeleton width={80} /></TableCell>
                <TableCell><Skeleton width={160} /><Skeleton width={90} /></TableCell>
                <TableCell align="right"><Skeleton width={80} /></TableCell>
                <TableCell align="right"><Skeleton width={80} /></TableCell>
                <TableCell><Skeleton width={140} height={32} /></TableCell>
                <TableCell><Skeleton width={140} height={32} /></TableCell>
            </TableRow>
        ))}
    </>
);

export const AsignacionCobranzaPanel = () => {
    const muiTheme = useTheme();
    const isMobile = useMediaQuery(muiTheme.breakpoints.down("sm"));
    const queryClient = useQueryClient();
    const { can: canCobranzas } = usePermission("COBRANZAS");
    const canAsignar = canCobranzas("COB_ASG_ASIGNACION_CREAR");

    const [selectedFacturas, setSelectedFacturas] = useState([]);
    const [searchTerm, setSearchTerm] = useState("");
    const [filterAsignado, setFilterAsignado] = useState("todos");
    const [filterEstado, setFilterEstado] = useState("sin_asignar");
    const [filterMoneda, setFilterMoneda] = useState("todos");
    const [fechaDesde, setFechaDesde] = useState("");
    const [fechaHasta, setFechaHasta] = useState("");
    const [page, setPage] = useState(1);
    const [dialogOpen, setDialogOpen] = useState(false);
    const [cobradorSeleccionado, setCobradorSeleccionado] = useState("");
    const [notas, setNotas] = useState("");
    const [dialogVendedorOpen, setDialogVendedorOpen] = useState(false);
    const [vendedorSeleccionado, setVendedorSeleccionado] = useState("");

    const handleSearch = useCallback((val) => {
        setSearchTerm(val);
        setPage(1);
        setSelectedFacturas([]);
    }, []);

    const handleFilterChange = (setter) => (e) => {
        setter(e.target.value);
        setPage(1);
        setSelectedFacturas([]);
    };

    // Queries estáticas con staleTime alto — no se re-fetchen en cada render
    const { data: monedasData } = useQuery({
        queryKey: ["empresa-monedas"],
        queryFn: getEmpresaMonedas,
        staleTime: 10 * 60 * 1000, // 10 min
    });
    const { data: vendedoresCobradoresData } = useQuery({
        queryKey: ["vendedores-cobradores-activos"],
        queryFn: () => getVendedoresCobradores({ active: true }),
        staleTime: 5 * 60 * 1000,
    });
    const { data: cobradoresData } = useQuery({
        queryKey: ["cobradores-activos"],
        queryFn: getCobradoresActivos,
        staleTime: 5 * 60 * 1000,
    });
    const { data: vendedoresData } = useQuery({
        queryKey: ["vendedores-activos"],
        queryFn: getVendedoresActivos,
        staleTime: 5 * 60 * 1000,
    });
    const { data: resumenData } = useQuery({
        queryKey: ["resumen-cobradores"],
        queryFn: getResumenCobradores,
        staleTime: 60 * 1000, // 1 min — cambia al asignar
    });

    const monedas = monedasData || [];
    const vendedoresCobradores = vendedoresCobradoresData || [];
    const cobradores = cobradoresData || [];
    const vendedores = vendedoresData || [];
    const resumen = resumenData || [];

    const selectedVC = vendedoresCobradores.find((vc) => vc.id === filterAsignado);
    const isCobradorFilter = selectedVC?.tipo === "cobrador";
    const isVendedorFilter = selectedVC?.tipo === "vendedor";

    // Query principal — paginada y con búsqueda server-side
    const { data: facturasData, isLoading: loadingFacturas, isFetching } = useQuery({
        queryKey: ["facturas-pendientes", filterEstado, filterAsignado, filterMoneda, searchTerm, fechaDesde, fechaHasta, page],
        queryFn: () =>
            getFacturasPendientes({
                sin_asignar: filterEstado === "sin_asignar",
                asignadas: filterEstado === "asignadas",
                cobrador_id: filterAsignado !== "todos" && (isCobradorFilter || selectedVC?.tipo === "ambos")
                    ? filterAsignado : undefined,
                vendedor_id: filterAsignado !== "todos" && (isVendedorFilter || selectedVC?.tipo === "ambos")
                    ? filterAsignado : undefined,
                moneda_id: filterMoneda !== "todos" ? filterMoneda : undefined,
                search: searchTerm || undefined,
                fechaDesde: fechaDesde || undefined,
                fechaHasta: fechaHasta || undefined,
                page,
                limit: PAGE_SIZE,
            }),
        placeholderData: keepPreviousData,
        staleTime: 30 * 1000,
    });

    const facturas = facturasData?.data || [];
    const totalPages = facturasData?.pages || 1;
    const totalFacturas = facturasData?.total || 0;

    const asignarMasivaMutation = useMutation({
        mutationFn: ({ ids, cobradorId, notas }) => asignarCobradorMasivo(ids, cobradorId, notas),
        onSuccess: (data) => {
            toast.success(`${data.asignadas} facturas asignadas a ${data.cobrador.nombre}`);
            queryClient.invalidateQueries({ queryKey: ["facturas-pendientes"] });
            queryClient.invalidateQueries({ queryKey: ["resumen-cobradores"] });
            handleCloseDialog();
            setSelectedFacturas([]);
        },
        onError: (error) => toast.error(error.response?.data?.message || "Error al asignar facturas"),
    });

    const asignarCobradorIndividualMutation = useMutation({
        mutationFn: ({ facturaId, cobradorId }) => asignarCobradorMasivo([facturaId], cobradorId, ""),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["facturas-pendientes"] });
            queryClient.invalidateQueries({ queryKey: ["resumen-cobradores"] });
        },
        onError: (error) => toast.error(error.response?.data?.message || "Error al asignar cobrador"),
    });

    const asignarVendedorMutation = useMutation({
        mutationFn: ({ facturaId, vendedorId }) => asignarVendedor(facturaId, vendedorId),
        onSuccess: () => queryClient.invalidateQueries({ queryKey: ["facturas-pendientes"] }),
        onError: (error) => toast.error(error.response?.data?.message || "Error al asignar vendedor"),
    });

    const asignarVendedorMasivoMutation = useMutation({
        mutationFn: ({ ids, vendedorId }) =>
            Promise.all(ids.map((id) => asignarVendedor(id, vendedorId))),
        onSuccess: (results) => {
            const nombre = vendedores.find((v) => v.id === vendedorSeleccionado)?.nombre || "";
            toast.success(`${results.length} facturas asignadas a vendedor ${nombre}`);
            queryClient.invalidateQueries({ queryKey: ["facturas-pendientes"] });
            setDialogVendedorOpen(false);
            setVendedorSeleccionado("");
            setSelectedFacturas([]);
        },
        onError: (error) => toast.error(error.response?.data?.message || "Error al asignar vendedor"),
    });

    const handleSelectAll = (event) => {
        if (event.target.checked) {
            setSelectedFacturas(facturas.map((f) => f.id));
        } else {
            setSelectedFacturas([]);
        }
    };

    const handleSelectFactura = (facturaId) => {
        setSelectedFacturas((prev) =>
            prev.includes(facturaId) ? prev.filter((id) => id !== facturaId) : [...prev, facturaId]
        );
    };

    const handleOpenDialog = () => {
        if (selectedFacturas.length === 0) { toast.error("Seleccione al menos una factura"); return; }
        setDialogOpen(true);
    };

    const handleCloseDialog = () => { setDialogOpen(false); setCobradorSeleccionado(""); setNotas(""); };

    const handleAsignar = () => {
        if (!cobradorSeleccionado) { toast.error("Seleccione un cobrador"); return; }
        asignarMasivaMutation.mutate({ ids: selectedFacturas, cobradorId: cobradorSeleccionado, notas });
    };

    const formatCurrency = (value, moneda = null) => {
        const codigo = moneda?.codigo || "PYG";
        const simbolo = moneda?.simbolo || "Gs.";
        const formatted = new Intl.NumberFormat("es-PY", {
            minimumFractionDigits: codigo === "PYG" ? 0 : 2,
            maximumFractionDigits: codigo === "PYG" ? 0 : 2,
        }).format(value || 0);
        return `${simbolo} ${formatted}`;
    };

    const totalSeleccionado = selectedFacturas.reduce((sum, id) => {
        const f = facturas.find((x) => x.id === id);
        return sum + (Number(f?.saldo_pendiente) || 0);
    }, 0);

    if (!canAsignar) {
        return <AccesoRestringido mensaje="No tienes permisos para gestionar asignaciones de cobranza." />;
    }

    return (
        <Box>
            {/* Header */}
            <Box sx={{ mb: 3 }}>
                <Typography variant="h6" fontWeight={600}>Asignación de Cobranza</Typography>
                <Typography variant="body2" color="text.secondary">
                    Asigna facturas pendientes a vendedores y cobradores
                </Typography>
            </Box>

            {/* Resumen de Cobradores */}
            <Box sx={{ display: "grid", gridTemplateColumns: { xs: "repeat(2,1fr)", sm: "repeat(4,1fr)" }, gap: 1.5, mb: 3 }}>
                {resumen.slice(0, 4).map((c) => (
                    <Card key={c.id} sx={{ p: { xs: 1.25, sm: 2 } }}>
                        <Box sx={{ display: "flex", alignItems: "center", gap: 0.75, mb: 0.75 }}>
                            <Person fontSize="small" color="primary" />
                            <Typography variant="body2" fontWeight={500} noWrap sx={{ fontSize: { xs: "0.75rem", sm: "0.875rem" } }}>
                                {c.nombre}
                            </Typography>
                        </Box>
                        <Box sx={{ display: "flex", justifyContent: "space-between" }}>
                            <Box>
                                <Typography variant="caption" color="text.secondary" sx={{ fontSize: { xs: "0.6rem", sm: "0.75rem" } }}>Facturas</Typography>
                                <Typography variant="h6" fontWeight={600} sx={{ fontSize: { xs: "1rem", sm: "1.25rem" } }}>{c.facturas_asignadas}</Typography>
                            </Box>
                            <Box sx={{ textAlign: "right" }}>
                                <Typography variant="caption" color="text.secondary" sx={{ fontSize: { xs: "0.6rem", sm: "0.75rem" } }}>Monto</Typography>
                                <Typography variant="body2" fontWeight={500} color="primary.main" sx={{ fontSize: { xs: "0.7rem", sm: "0.875rem" } }}>
                                    {formatCurrency(c.monto_total_pendiente)}
                                </Typography>
                            </Box>
                        </Box>
                    </Card>
                ))}
            </Box>

            {/* Filtros */}
            <Paper sx={{ p: 1.5, mb: 2 }}>
                <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
                    <Box sx={{ display: "flex", gap: 1.5, alignItems: "center", flexWrap: "wrap" }}>
                        <FilterList color="action" fontSize="small" />
                        <SearchInput onSearch={handleSearch} isFetching={isFetching} />
                        <FormControl size="small" sx={{ minWidth: 130 }}>
                            <InputLabel>Estado</InputLabel>
                            <Select value={filterEstado} label="Estado" onChange={handleFilterChange(setFilterEstado)}>
                                <MenuItem value="todos">Todas</MenuItem>
                                <MenuItem value="sin_asignar">Sin Asignar</MenuItem>
                                <MenuItem value="asignadas">Asignadas</MenuItem>
                            </Select>
                        </FormControl>
                        <FormControl size="small" sx={{ minWidth: 100 }}>
                            <InputLabel>Moneda</InputLabel>
                            <Select value={filterMoneda} label="Moneda" onChange={handleFilterChange(setFilterMoneda)}>
                                <MenuItem value="todos">Todas</MenuItem>
                                {monedas.map((m) => (
                                    <MenuItem key={m.moneda?.id || m.id} value={m.moneda?.id || m.id}>
                                        {m.moneda?.codigo || m.codigo}
                                    </MenuItem>
                                ))}
                            </Select>
                        </FormControl>
                        <FormControl size="small" sx={{ minWidth: 160 }}>
                            <InputLabel>Vendedor/Cobrador</InputLabel>
                            <Select value={filterAsignado} label="Vendedor/Cobrador" onChange={handleFilterChange(setFilterAsignado)}>
                                <MenuItem value="todos">Todos</MenuItem>
                                {vendedoresCobradores.map((vc) => (
                                    <MenuItem key={vc.id} value={vc.id}>
                                        {vc.nombre} {vc.apellido || ""}
                                        <Chip
                                            label={vc.tipo === "vendedor" ? "V" : vc.tipo === "cobrador" ? "C" : "V/C"}
                                            size="small"
                                            sx={{ ml: 1, height: 18, fontSize: "0.65rem" }}
                                            color={vc.tipo === "vendedor" ? "primary" : vc.tipo === "cobrador" ? "secondary" : "success"}
                                        />
                                    </MenuItem>
                                ))}
                            </Select>
                        </FormControl>
                        <TextField
                            size="small"
                            type="date"
                            label="Desde"
                            value={fechaDesde}
                            onChange={(e) => { setFechaDesde(e.target.value); setPage(1); setSelectedFacturas([]); }}
                            InputLabelProps={{ shrink: true }}
                            sx={{ minWidth: 140 }}
                        />
                        <TextField
                            size="small"
                            type="date"
                            label="Hasta"
                            value={fechaHasta}
                            onChange={(e) => { setFechaHasta(e.target.value); setPage(1); setSelectedFacturas([]); }}
                            InputLabelProps={{ shrink: true }}
                            sx={{ minWidth: 140 }}
                        />
                        {(fechaDesde || fechaHasta) && (
                            <Chip
                                label="Limpiar fechas"
                                size="small"
                                color="error"
                                variant="outlined"
                                onDelete={() => { setFechaDesde(""); setFechaHasta(""); setPage(1); setSelectedFacturas([]); }}
                                onClick={() => { setFechaDesde(""); setFechaHasta(""); setPage(1); setSelectedFacturas([]); }}
                            />
                        )}
                    </Box>

                    {selectedFacturas.length > 0 && (
                        <Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}>
                            <Typography variant="caption" color="text.secondary">
                                {selectedFacturas.length} seleccionadas · {formatCurrency(totalSeleccionado)}
                            </Typography>
                            <Button variant="contained" startIcon={<Person />} onClick={() => setDialogVendedorOpen(true)} size={isMobile ? "small" : "medium"}>
                                Asignar Vendedor
                            </Button>
                            <Button variant="contained" startIcon={<Assignment />} onClick={handleOpenDialog} size={isMobile ? "small" : "medium"}>
                                Asignar Cobrador
                            </Button>
                        </Box>
                    )}
                </Box>
            </Paper>

            {/* Contador */}
            {!loadingFacturas && (
                <Typography variant="caption" color="text.secondary" sx={{ display: "block", mb: 1 }}>
                    {totalFacturas} facturas · página {page} de {totalPages}
                </Typography>
            )}

            {/* Vista */}
            {isMobile ? (
                <Stack spacing={1.5}>
                    {loadingFacturas ? (
                        [1, 2, 3].map((i) => <Skeleton key={i} variant="rectangular" height={120} sx={{ borderRadius: 2 }} />)
                    ) : facturas.length === 0 ? (
                        <Box sx={{ textAlign: "center", py: 4 }}>
                            <Receipt sx={{ fontSize: 40, color: "text.secondary", mb: 1 }} />
                            <Typography color="text.secondary" variant="body2">No hay facturas pendientes</Typography>
                        </Box>
                    ) : (
                        facturas.map((factura) => (
                            <Card key={factura.id} variant="outlined" sx={{
                                borderRadius: 2,
                                outline: selectedFacturas.includes(factura.id) ? "2px solid" : undefined,
                                outlineColor: "primary.main",
                            }}>
                                <CardContent sx={{ p: "12px !important" }}>
                                    <Box sx={{ display: "flex", alignItems: "flex-start", gap: 1, mb: 0.5 }}>
                                        <Checkbox size="small" checked={selectedFacturas.includes(factura.id)}
                                            onChange={() => handleSelectFactura(factura.id)} sx={{ p: 0, mt: 0.25 }} />
                                        <Box sx={{ flex: 1, minWidth: 0 }}>
                                            <Typography variant="subtitle2" fontWeight={600} noWrap>{factura.numero_factura}</Typography>
                                            <Typography variant="caption" color="text.secondary">
                                                {new Date(factura.fecha_emision).toLocaleDateString()}
                                            </Typography>
                                        </Box>
                                        <Box sx={{ textAlign: "right", flexShrink: 0 }}>
                                            <Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
                                                {formatCurrency(factura.total, factura.moneda)}
                                            </Typography>
                                            <Typography variant="body2" fontWeight={600} color="error.main">
                                                {formatCurrency(factura.saldo_pendiente, factura.moneda)}
                                            </Typography>
                                        </Box>
                                    </Box>
                                    <Typography variant="caption" color="text.secondary" sx={{ display: "block", mb: 0.75 }}>
                                        {factura.cliente?.nombre}{factura.cliente?.ruc ? ` · ${factura.cliente.ruc}` : ""}
                                    </Typography>
                                    <Divider sx={{ mb: 0.75 }} />
                                    <Box sx={{ display: "flex", flexDirection: "column", gap: 0.75 }}>
                                        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                                            <Typography variant="caption" color="text.secondary" sx={{ minWidth: 60 }}>Vendedor:</Typography>
                                            <AssignSelect value={factura.vendedor?.id} options={vendedores}
                                                onChange={(id) => asignarVendedorMutation.mutate({ facturaId: factura.id, vendedorId: id })} />
                                        </Box>
                                        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                                            <Typography variant="caption" color="text.secondary" sx={{ minWidth: 60 }}>Cobrador:</Typography>
                                            <AssignSelect value={factura.cobrador_asignado?.id} options={cobradores}
                                                onChange={(id) => id && asignarCobradorIndividualMutation.mutate({ facturaId: factura.id, cobradorId: id })} />
                                        </Box>
                                    </Box>
                                </CardContent>
                            </Card>
                        ))
                    )}
                </Stack>
            ) : (
                <TableContainer component={Paper}>
                    <Table size="small">
                        <TableHead>
                            <TableRow>
                                <TableCell padding="checkbox">
                                    <Checkbox
                                        indeterminate={selectedFacturas.length > 0 && selectedFacturas.length < facturas.length}
                                        checked={facturas.length > 0 && selectedFacturas.length === facturas.length}
                                        onChange={handleSelectAll}
                                        disabled={loadingFacturas}
                                    />
                                </TableCell>
                                <TableCell>Factura</TableCell>
                                <TableCell>Cliente</TableCell>
                                <TableCell align="right">Total</TableCell>
                                <TableCell align="right">Saldo</TableCell>
                                <TableCell>Vendedor</TableCell>
                                <TableCell>Cobrador</TableCell>
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {loadingFacturas ? (
                                <FacturaSkeleton />
                            ) : facturas.length === 0 ? (
                                <TableRow>
                                    <TableCell colSpan={7} align="center" sx={{ py: 4 }}>
                                        <Receipt sx={{ fontSize: 40, color: "text.secondary", mb: 1 }} />
                                        <Typography color="text.secondary">No hay facturas pendientes</Typography>
                                    </TableCell>
                                </TableRow>
                            ) : (
                                facturas.map((factura) => (
                                    <TableRow key={factura.id} hover selected={selectedFacturas.includes(factura.id)}>
                                        <TableCell padding="checkbox">
                                            <Checkbox checked={selectedFacturas.includes(factura.id)}
                                                onChange={() => handleSelectFactura(factura.id)} />
                                        </TableCell>
                                        <TableCell>
                                            <Typography variant="body2" fontWeight={500}>{factura.numero_factura}</Typography>
                                            <Typography variant="caption" color="text.secondary">
                                                {new Date(factura.fecha_emision).toLocaleDateString()}
                                            </Typography>
                                        </TableCell>
                                        <TableCell>
                                            <Typography variant="body2">{factura.cliente?.nombre}</Typography>
                                            <Typography variant="caption" color="text.secondary">{factura.cliente?.ruc}</Typography>
                                        </TableCell>
                                        <TableCell align="right">{formatCurrency(factura.total, factura.moneda)}</TableCell>
                                        <TableCell align="right">
                                            <Typography fontWeight={500} color="error.main">{formatCurrency(factura.saldo_pendiente, factura.moneda)}</Typography>
                                        </TableCell>
                                        <TableCell>
                                            <AssignSelect value={factura.vendedor?.id} options={vendedores}
                                                onChange={(id) => asignarVendedorMutation.mutate({ facturaId: factura.id, vendedorId: id })} />
                                        </TableCell>
                                        <TableCell>
                                            <AssignSelect value={factura.cobrador_asignado?.id} options={cobradores}
                                                onChange={(id) => id && asignarCobradorIndividualMutation.mutate({ facturaId: factura.id, cobradorId: id })} />
                                        </TableCell>
                                    </TableRow>
                                ))
                            )}
                        </TableBody>
                    </Table>
                </TableContainer>
            )}

            {/* Paginación */}
            {totalPages > 1 && (
                <Box sx={{ display: "flex", justifyContent: "center", mt: 2 }}>
                    <Pagination
                        count={totalPages}
                        page={page}
                        onChange={(_, p) => { setPage(p); setSelectedFacturas([]); }}
                        color="primary"
                        size={isMobile ? "small" : "medium"}
                    />
                </Box>
            )}

            {/* Dialog Vendedor */}
            <Dialog open={dialogVendedorOpen} onClose={() => { setDialogVendedorOpen(false); setVendedorSeleccionado(""); }} maxWidth="xs" fullWidth>
                <DialogTitle>Asignar Vendedor</DialogTitle>
                <DialogContent>
                    <Box sx={{ display: "flex", flexDirection: "column", gap: 2, mt: 1 }}>
                        <Typography variant="body2" color="text.secondary">
                            Se asignará el vendedor a <strong>{selectedFacturas.length}</strong> facturas por un total de <strong>{formatCurrency(totalSeleccionado)}</strong>
                        </Typography>
                        <FormControl fullWidth size="small">
                            <InputLabel>Vendedor</InputLabel>
                            <Select value={vendedorSeleccionado} label="Vendedor" onChange={(e) => setVendedorSeleccionado(e.target.value)}>
                                {vendedores.map((v) => (
                                    <MenuItem key={v.id} value={v.id}>
                                        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                                            <Person fontSize="small" />{v.nombre} {v.apellido || ""}
                                        </Box>
                                    </MenuItem>
                                ))}
                            </Select>
                        </FormControl>
                    </Box>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => { setDialogVendedorOpen(false); setVendedorSeleccionado(""); }}>Cancelar</Button>
                    <Button variant="contained"
                        onClick={() => asignarVendedorMasivoMutation.mutate({ ids: selectedFacturas, vendedorId: vendedorSeleccionado })}
                        disabled={asignarVendedorMasivoMutation.isPending || !vendedorSeleccionado}>
                        {asignarVendedorMasivoMutation.isPending ? "Asignando..." : "Asignar"}
                    </Button>
                </DialogActions>
            </Dialog>

            {/* Dialog Cobrador */}
            <Dialog open={dialogOpen} onClose={handleCloseDialog} maxWidth="xs" fullWidth>
                <DialogTitle>Asignar Cobrador</DialogTitle>
                <DialogContent>
                    <Box sx={{ display: "flex", flexDirection: "column", gap: 2, mt: 1 }}>
                        <Typography variant="body2" color="text.secondary">
                            Se asignarán <strong>{selectedFacturas.length}</strong> facturas por un total de <strong>{formatCurrency(totalSeleccionado)}</strong>
                        </Typography>
                        <FormControl fullWidth size="small">
                            <InputLabel>Cobrador</InputLabel>
                            <Select value={cobradorSeleccionado} label="Cobrador" onChange={(e) => setCobradorSeleccionado(e.target.value)}>
                                {cobradores.map((c) => (
                                    <MenuItem key={c.id} value={c.id}>
                                        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                                            <Person fontSize="small" />{c.nombre} {c.apellido || ""}
                                        </Box>
                                    </MenuItem>
                                ))}
                            </Select>
                        </FormControl>
                        <TextField label="Notas (opcional)" value={notas} onChange={(e) => setNotas(e.target.value)} size="small" multiline rows={2} fullWidth />
                    </Box>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleCloseDialog}>Cancelar</Button>
                    <Button variant="contained" onClick={handleAsignar} disabled={asignarMasivaMutation.isPending || !cobradorSeleccionado}>
                        {asignarMasivaMutation.isPending ? "Asignando..." : "Asignar"}
                    </Button>
                </DialogActions>
            </Dialog>
        </Box>
    );
};

export default AsignacionCobranzaPanel;
