import {
  Add,
  CreditCard,
  Delete,
  Edit,
  Payment,
  Star,
  StarBorder,
} from "@mui/icons-material";
import {
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  FormControlLabel,
  IconButton,
  MenuItem,
  Paper,
  Stack,
  Switch,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { usePermission } from "../../hooks/usePermission";
import {
  useCondicionesPagoQuery,
  useCreateCondicionPagoMutation,
  useDeleteCondicionPagoMutation,
  useMediosPagoEmpresaQuery,
  useToggleMedioPagoMutation,
  useUpdateCondicionPagoMutation,
} from "../../tanstack/PagosStack";
import { AccesoRestringido } from "../common/AccesoRestringido";
import { esMedioPagoAnticipo, medioNoMueveCaja } from "../_standards";

// ==================== CONDICIONES DE PAGO ====================

function CondicionPagoFormDialog({ open, onClose, condicion }) {
  const isEdit = !!condicion;
  const createMutation = useCreateCondicionPagoMutation();
  const updateMutation = useUpdateCondicionPagoMutation();

  const {
    register,
    handleSubmit,
    reset,
    watch,
    formState: { errors },
  } = useForm({
    defaultValues: {
      descripcion: "",
      dias_plazo: 0,
      cuotas: 1,
      intervalo_dias: 30,
      cod_tipo_credito: 1,
      cuota_inicial: false,
      es_default: false,
      activo: true,
    },
  });

  // Resetear formulario cuando cambia la condición
  useEffect(() => {
    if (condicion) {
      reset({
        descripcion: condicion.descripcion || "",
        dias_plazo: condicion.dias_plazo || 0,
        cuotas: condicion.cuotas || 1,
        intervalo_dias: condicion.intervalo_dias || 30,
        cod_tipo_credito: condicion.cod_tipo_credito || 1,
        cuota_inicial: condicion.cuota_inicial || false,
        es_default: condicion.es_default || false,
        activo: condicion.activo ?? true,
      });
    } else {
      reset({
        descripcion: "",
        dias_plazo: 0,
        cuotas: 1,
        intervalo_dias: 30,
        cod_tipo_credito: 1,
        cuota_inicial: false,
        es_default: false,
        activo: true,
      });
    }
  }, [condicion, reset]);

  const codTipoCredito = watch("cod_tipo_credito");

  const onSubmit = async (data) => {
    const payload = {
      ...data,
      dias_plazo: Number(data.dias_plazo),
      cuotas: Number(data.cuotas),
      intervalo_dias: Number(data.intervalo_dias),
      cod_tipo_credito: Number(data.cod_tipo_credito),
    };

    if (isEdit) {
      await updateMutation.mutateAsync({ id: condicion.id, ...payload });
    } else {
      await createMutation.mutateAsync(payload);
    }
    reset();
    onClose();
  };

  const isSaving = createMutation.isPending || updateMutation.isPending;

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        {isEdit ? "Editar Condición de Pago" : "Nueva Condición de Pago"}
      </DialogTitle>
      <form onSubmit={handleSubmit(onSubmit)}>
        <DialogContent>
          <Box sx={{ display: "flex", flexDirection: "column", gap: 2, pt: 1 }}>
            <TextField
              label="Descripción"
              size="small"
              fullWidth
              {...register("descripcion", {
                required: "Requerido",
                minLength: { value: 2, message: "Mínimo 2 caracteres" },
                maxLength: { value: 15, message: "Máximo 15 caracteres" },
              })}
              error={!!errors.descripcion}
              helperText={errors.descripcion?.message || "2-15 caracteres"}
              disabled={isEdit && condicion?.es_sistema}
            />

            <TextField
              label="Tipo de Crédito"
              size="small"
              select
              defaultValue={condicion?.cod_tipo_credito || 1}
              {...register("cod_tipo_credito")}
            >
              <MenuItem value={1}>Plazo</MenuItem>
              <MenuItem value={2}>Cuota</MenuItem>
            </TextField>

            {/* Tipo Plazo: solo días de plazo */}
            {codTipoCredito == 1 && (
              <TextField
                label="Días de Plazo"
                size="small"
                type="number"
                fullWidth
                {...register("dias_plazo")}
              />
            )}

            {/* Tipo Cuota: cantidad de cuotas e intervalo */}
            {codTipoCredito == 2 && (
              <Box sx={{ display: "flex", gap: 2 }}>
                <TextField
                  label="Cantidad de Cuotas"
                  size="small"
                  type="number"
                  {...register("cuotas")}
                />
                <TextField
                  label="Intervalo (días)"
                  size="small"
                  type="number"
                  {...register("intervalo_dias")}
                />
                <FormControlLabel
                  control={
                    <Switch
                      {...register("cuota_inicial")}
                      checked={watch("cuota_inicial")}
                    />
                  }
                  label="Cuota inicial"
                />
              </Box>
            )}

            <Divider />

            <Box sx={{ display: "flex", gap: 2 }}>
              <FormControlLabel
                control={
                  <Switch
                    {...register("es_default")}
                    checked={watch("es_default")}
                  />
                }
                label="Condición por defecto"
              />
              <FormControlLabel
                control={
                  <Switch {...register("activo")} checked={watch("activo")} />
                }
                label="Activo"
              />
            </Box>
          </Box>
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button onClick={onClose} color="inherit">
            Cancelar
          </Button>
          <Button type="submit" variant="contained" disabled={isSaving}>
            {isSaving ? "Guardando..." : "Guardar"}
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  );
}

function CondicionesPagoSection() {
  const muiTheme = useTheme();
  const isMobile = useMediaQuery(muiTheme.breakpoints.down("sm"));
  const { can } = usePermission("ADMINISTRACION");
  const canRead = can("ADM_CONDPAGO_VER");
  const canCreate = can("ADM_CONDPAGO_CREAR");
  const canEdit = can("ADM_CONDPAGO_EDITAR");
  const canDelete = can("ADM_CONDPAGO_ELIMINAR");
  const { data: condiciones = [], isLoading } = useCondicionesPagoQuery();
  const deleteMutation = useDeleteCondicionPagoMutation();
  const updateMutation = useUpdateCondicionPagoMutation();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedCondicion, setSelectedCondicion] = useState(null);

  const handleOpenCreate = () => {
    setSelectedCondicion(null);
    setDialogOpen(true);
  };

  const handleOpenEdit = (condicion) => {
    setSelectedCondicion(condicion);
    setDialogOpen(true);
  };

  const handleDelete = async (id) => {
    if (window.confirm("¿Estás seguro de eliminar esta condición de pago?")) {
      await deleteMutation.mutateAsync(id);
    }
  };

  const handleSetDefault = async (condicion) => {
    await updateMutation.mutateAsync({ id: condicion.id, es_default: true });
  };

  if (!canRead) {
    return (
      <AccesoRestringido mensaje="No tienes permisos para ver las condiciones de pago." />
    );
  }

  if (isLoading) {
    return (
      <Box sx={{ display: "flex", justifyContent: "center", py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Paper sx={{ p: { xs: 2, sm: 3 } }}>
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "flex-start",
          mb: 2,
          gap: 1,
          flexWrap: "wrap",
        }}
      >
        <Box>
          <Typography
            variant="h6"
            sx={{
              display: "flex",
              alignItems: "center",
              gap: 1,
              fontSize: { xs: "1rem", sm: "1.25rem" },
            }}
          >
            <Payment /> Condiciones de Pago
          </Typography>
          <Typography
            variant="body2"
            color="text.secondary"
            sx={{ fontSize: { xs: "0.75rem", sm: "0.875rem" } }}
          >
            Define las condiciones de pago disponibles (Contado, Crédito,
            Cuotas)
          </Typography>
        </Box>
        {canCreate && (
          <Button
            variant="contained"
            size={isMobile ? "small" : "medium"}
            startIcon={<Add />}
            onClick={handleOpenCreate}
          >
            {isMobile ? "Nueva" : "Nueva Condición"}
          </Button>
        )}
      </Box>

      {isMobile ? (
        <Stack spacing={1.5}>
          {condiciones.length === 0 ? (
            <Typography color="text.secondary" textAlign="center" py={3}>
              No hay condiciones de pago registradas
            </Typography>
          ) : (
            condiciones.map((cond) => (
              <Card
                key={cond.id}
                variant="outlined"
                sx={{ opacity: cond.activo ? 1 : 0.65 }}
              >
                <CardContent sx={{ p: 1.5, "&:last-child": { pb: 1.5 } }}>
                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "flex-start",
                      mb: 0.75,
                    }}
                  >
                    <Box
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        gap: 0.75,
                        flex: 1,
                        minWidth: 0,
                      }}
                    >
                      <Tooltip
                        title={
                          cond.es_default
                            ? "Condición por defecto"
                            : "Establecer como defecto"
                        }
                      >
                        <IconButton
                          size="small"
                          sx={{ p: 0.25 }}
                          onClick={() => handleSetDefault(cond)}
                          disabled={cond.es_default}
                        >
                          {cond.es_default ? (
                            <Star color="warning" fontSize="small" />
                          ) : (
                            <StarBorder fontSize="small" />
                          )}
                        </IconButton>
                      </Tooltip>
                      <Typography variant="subtitle2" fontWeight={600} noWrap>
                        {cond.descripcion}
                      </Typography>
                    </Box>
                    <Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}>
                      <Chip
                        label={
                          cond.cod_condicion_venta === 1 ? "Contado" : "Crédito"
                        }
                        size="small"
                        color={
                          cond.cod_condicion_venta === 1 ? "success" : "primary"
                        }
                        variant="outlined"
                        sx={{ fontSize: "0.65rem" }}
                      />
                      <Chip
                        label={cond.activo ? "Activo" : "Inactivo"}
                        size="small"
                        color={cond.activo ? "success" : "default"}
                        sx={{ fontSize: "0.65rem" }}
                      />
                    </Box>
                  </Box>
                  <Box
                    sx={{ display: "flex", gap: 1, flexWrap: "wrap", mb: 0.75 }}
                  >
                    <Chip
                      label={`Plazo: ${cond.dias_plazo || 0}d`}
                      size="small"
                      variant="outlined"
                      sx={{ fontSize: "0.65rem" }}
                    />
                    <Chip
                      label={`${cond.cuotas || 1} cuota${(cond.cuotas || 1) !== 1 ? "s" : ""}`}
                      size="small"
                      variant="outlined"
                      sx={{ fontSize: "0.65rem" }}
                    />
                    {cond.es_sistema && (
                      <Chip
                        label="Sistema"
                        size="small"
                        variant="outlined"
                        sx={{ fontSize: "0.65rem" }}
                      />
                    )}
                  </Box>
                  {!cond.es_sistema && (canEdit || canDelete) && (
                    <Box
                      sx={{
                        display: "flex",
                        justifyContent: "flex-end",
                        gap: 0.5,
                        borderTop: "1px solid",
                        borderColor: "divider",
                        pt: 0.75,
                      }}
                    >
                      {canEdit && (
                        <Tooltip title="Editar">
                          <IconButton
                            size="small"
                            onClick={() => handleOpenEdit(cond)}
                          >
                            <Edit fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      )}
                      {canDelete && (
                        <Tooltip title="Eliminar">
                          <IconButton
                            size="small"
                            color="error"
                            onClick={() => handleDelete(cond.id)}
                          >
                            <Delete fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      )}
                    </Box>
                  )}
                </CardContent>
              </Card>
            ))
          )}
        </Stack>
      ) : (
        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell>Descripción</TableCell>
                <TableCell>Tipo</TableCell>
                <TableCell align="center">Plazo</TableCell>
                <TableCell align="center">Cuotas</TableCell>
                <TableCell align="center">Default</TableCell>
                <TableCell align="center">Estado</TableCell>
                <TableCell align="right">Acciones</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {condiciones.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} align="center" sx={{ py: 4 }}>
                    <Typography color="text.secondary">
                      No hay condiciones de pago registradas
                    </Typography>
                  </TableCell>
                </TableRow>
              ) : (
                condiciones.map((cond) => (
                  <TableRow key={cond.id} hover>
                    <TableCell>{cond.descripcion}</TableCell>
                    <TableCell>
                      <Chip
                        label={
                          cond.cod_condicion_venta === 1 ? "Contado" : "Crédito"
                        }
                        size="small"
                        color={
                          cond.cod_condicion_venta === 1 ? "success" : "primary"
                        }
                        variant="outlined"
                      />
                    </TableCell>
                    <TableCell align="center">
                      {cond.dias_plazo || 0} días
                    </TableCell>
                    <TableCell align="center">{cond.cuotas || 1}</TableCell>
                    <TableCell align="center">
                      <Tooltip
                        title={
                          cond.es_default
                            ? "Condición por defecto"
                            : "Establecer como defecto"
                        }
                      >
                        <IconButton
                          size="small"
                          onClick={() => handleSetDefault(cond)}
                          disabled={cond.es_default}
                        >
                          {cond.es_default ? (
                            <Star color="warning" fontSize="small" />
                          ) : (
                            <StarBorder color="disabled" fontSize="small" />
                          )}
                        </IconButton>
                      </Tooltip>
                    </TableCell>
                    <TableCell align="center">
                      <Chip
                        label={cond.activo ? "Activo" : "Inactivo"}
                        size="small"
                        color={cond.activo ? "success" : "default"}
                      />
                    </TableCell>
                    <TableCell align="right">
                      {!cond.es_sistema ? (
                        <>
                          {canEdit && (
                            <Tooltip title="Editar">
                              <IconButton
                                size="small"
                                onClick={() => handleOpenEdit(cond)}
                              >
                                <Edit fontSize="small" />
                              </IconButton>
                            </Tooltip>
                          )}
                          {canDelete && (
                            <Tooltip title="Eliminar">
                              <IconButton
                                size="small"
                                color="error"
                                onClick={() => handleDelete(cond.id)}
                              >
                                <Delete fontSize="small" />
                              </IconButton>
                            </Tooltip>
                          )}
                        </>
                      ) : (
                        <Chip label="Sistema" size="small" variant="outlined" />
                      )}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      <CondicionPagoFormDialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        condicion={selectedCondicion}
      />
    </Paper>
  );
}

// ==================== MEDIOS DE PAGO ====================

function MediosPagoSection() {
  const muiTheme = useTheme();
  const isMobile = useMediaQuery(muiTheme.breakpoints.down("sm"));
  const { can } = usePermission("ADMINISTRACION");
  const canRead = can("ADM_MEDPAGO_VER");
  const canEdit = can("ADM_MEDPAGO_EDITAR");
  const { data: medios = [], isLoading } = useMediosPagoEmpresaQuery();
  const toggleMutation = useToggleMedioPagoMutation();

  const handleToggle = async (medio) => {
    await toggleMutation.mutateAsync({
      medio_pago_id: medio.id,
      activo: !medio.activo,
    });
  };

  // "No mueve dinero": un gasto pagado con este medio no sale del banco y se asienta contra
  // la cuenta «Al pagar» del medio (pedido DOBA con "Otro", oct-2026). "Pago por anticipo"
  // no mueve dinero siempre, por eso no se puede cambiar.
  const handleToggleNoMueveCaja = async (medio) => {
    await toggleMutation.mutateAsync({
      medio_pago_id: medio.id,
      activo: Boolean(medio.activo),
      no_mueve_caja: !medio.no_mueve_caja,
    });
  };

  const ayudaNoMueveCaja = (medio) =>
    esMedioPagoAnticipo(medio)
      ? "«Pago por anticipo» nunca mueve dinero: descuenta del anticipo ya entregado."
      : "Activalo si con este medio cargás gastos que no salen del banco ni de la caja. El gasto no genera egreso " +
        "y el asiento va contra la cuenta «Al pagar» del medio (Contabilidad → Mapeo de cuentas → Cuentas por medio de pago).";

  const switchNoMueveCaja = (medio, size) => (
    <Tooltip title={ayudaNoMueveCaja(medio)} enterDelay={300}>
      <span>
        <Switch
          size={size}
          checked={medioNoMueveCaja(medio)}
          onChange={() => handleToggleNoMueveCaja(medio)}
          disabled={toggleMutation.isPending || !canEdit || !medio.activo || esMedioPagoAnticipo(medio)}
          slotProps={{ input: { "aria-label": `${medio.descripcion}: no mueve dinero` } }}
        />
      </span>
    </Tooltip>
  );

  if (!canRead) {
    return (
      <AccesoRestringido mensaje="No tienes permisos para ver los medios de pago." />
    );
  }

  if (isLoading) {
    return (
      <Box sx={{ display: "flex", justifyContent: "center", py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Paper sx={{ p: { xs: 2, sm: 3 } }}>
      <Box sx={{ mb: 2 }}>
        <Typography
          variant="h6"
          sx={{
            display: "flex",
            alignItems: "center",
            gap: 1,
            fontSize: { xs: "1rem", sm: "1.25rem" },
          }}
        >
          <CreditCard /> Medios de Pago
        </Typography>
        <Typography
          variant="body2"
          color="text.secondary"
          sx={{ fontSize: { xs: "0.75rem", sm: "0.875rem" } }}
        >
          Activa los medios de pago que acepta tu empresa (Catálogo SIFEN). «No mueve dinero» es para los medios
          con los que se cargan gastos que no salen del banco ni de la caja.
        </Typography>
      </Box>

      {isMobile ? (
        <Stack spacing={1}>
          {medios.map((medio) => (
            <Card
              key={medio.id}
              variant="outlined"
              sx={{ opacity: medio.activo ? 1 : 0.65 }}
            >
              <CardContent sx={{ p: 1.5, "&:last-child": { pb: 1.5 } }}>
                <Box
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    gap: 1,
                  }}
                >
                  <Box
                    sx={{
                      display: "flex",
                      alignItems: "center",
                      gap: 1,
                      flex: 1,
                      minWidth: 0,
                    }}
                  >
                    <Chip
                      label={medio.codigo}
                      size="small"
                      variant="outlined"
                      sx={{ fontFamily: "monospace", flexShrink: 0 }}
                    />
                    <Typography variant="body2" fontWeight={500} noWrap>
                      {medio.descripcion}
                    </Typography>
                  </Box>
                  <Switch
                    checked={medio.activo || false}
                    onChange={() => handleToggle(medio)}
                    disabled={toggleMutation.isPending || !canEdit}
                    size="small"
                  />
                </Box>
                {medio.activo && (
                  <Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between", mt: 0.5 }}>
                    <Typography variant="caption" color="text.secondary">
                      No mueve dinero
                    </Typography>
                    {switchNoMueveCaja(medio, "small")}
                  </Box>
                )}
              </CardContent>
            </Card>
          ))}
        </Stack>
      ) : (
        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell>Código SIFEN</TableCell>
                <TableCell>Descripción</TableCell>
                <TableCell align="center">Habilitado</TableCell>
                <TableCell align="center">No mueve dinero</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {medios.map((medio) => (
                <TableRow key={medio.id} hover>
                  <TableCell>
                    <Chip
                      label={medio.codigo}
                      size="small"
                      variant="outlined"
                    />
                  </TableCell>
                  <TableCell>
                    <Typography fontWeight={500}>
                      {medio.descripcion}
                    </Typography>
                  </TableCell>
                  <TableCell align="center">
                    <Switch
                      checked={medio.activo || false}
                      onChange={() => handleToggle(medio)}
                      disabled={toggleMutation.isPending || !canEdit}
                    />
                  </TableCell>
                  <TableCell align="center">{switchNoMueveCaja(medio)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Paper>
  );
}

// ==================== COMPONENTE PRINCIPAL ====================

export function PagosConfigTab() {
  return (
    <Box sx={{ display: "flex", flexDirection: "column", gap: 3 }}>
      <CondicionesPagoSection />
      <MediosPagoSection />
    </Box>
  );
}
