import { Icon } from "@iconify/react";
import {
  Alert,
  Box,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControlLabel,
  Grid,
  IconButton,
  Paper,
  Stack,
  Switch,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import {
  createImportacionIscVehiculo,
  deleteImportacionIscVehiculo,
  getImportacionIscVehiculos,
  updateImportacionIscVehiculo,
} from "../../api/importaciones.service";
import { usePermission } from "../../hooks/usePermission";
import { ScreenGuia } from "../_standards";
import { AccesoRestringido } from "../common/AccesoRestringido";
import { ConfirmDialog } from "../ui/ConfirmDialog";
import { hoyISO } from "../../utils/fecha";

const todayISO = () => hoyISO();

const emptyForm = {
  anio_desde: "",
  anio_hasta: "",
  cc_desde: "",
  cc_hasta: "",
  tasa_isc_pct: "",
  descripcion: "",
  vigente_desde: todayISO(),
  vigente_hasta: "",
  activo: true,
};

const normalizeError = (error) => {
  const msg = error?.response?.data?.message || error?.message || "Error inesperado";
  return Array.isArray(msg) ? msg.join(", ") : msg;
};

const fmtDate = (value) => (value ? String(value).slice(0, 10) : "—");

export function IscVehiculosTab() {
  const { hasAccess, can } = usePermission("IMPORTACIONES");
  const canConfig = can("IMP_CFG_CONFIG_EDITAR");
  const queryClient = useQueryClient();

  const [dialog, setDialog] = useState({ open: false, data: null });
  const [form, setForm] = useState(emptyForm);
  const [deleteTarget, setDeleteTarget] = useState(null);

  const { data, isLoading } = useQuery({
    queryKey: ["importaciones-isc"],
    queryFn: getImportacionIscVehiculos,
    enabled: hasAccess,
  });

  const items = Array.isArray(data) ? data : [];

  const invalidate = () => queryClient.invalidateQueries({ queryKey: ["importaciones-isc"] });

  const createMutation = useMutation({
    mutationFn: (payload) => createImportacionIscVehiculo(payload),
    onSuccess: () => {
      toast.success("Tasa ISC creada");
      invalidate();
      setDialog({ open: false, data: null });
    },
    onError: (e) => toast.error(normalizeError(e)),
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, payload }) => updateImportacionIscVehiculo(id, payload),
    onSuccess: () => {
      toast.success("Tasa ISC actualizada");
      invalidate();
      setDialog({ open: false, data: null });
    },
    onError: (e) => toast.error(normalizeError(e)),
  });

  const deleteMutation = useMutation({
    mutationFn: (id) => deleteImportacionIscVehiculo(id),
    onSuccess: () => {
      toast.success("Tasa eliminada");
      invalidate();
      setDeleteTarget(null);
    },
    onError: (e) => toast.error(normalizeError(e)),
  });

  const handleOpen = (row) => {
    if (row) {
      setForm({
        anio_desde: String(row.anio_desde ?? ""),
        anio_hasta: String(row.anio_hasta ?? ""),
        cc_desde: String(row.cc_desde ?? ""),
        cc_hasta: String(row.cc_hasta ?? ""),
        tasa_isc_pct: String(row.tasa_isc_pct ?? ""),
        descripcion: row.descripcion ?? "",
        vigente_desde: row.vigente_desde ? String(row.vigente_desde).slice(0, 10) : todayISO(),
        vigente_hasta: row.vigente_hasta ? String(row.vigente_hasta).slice(0, 10) : "",
        activo: row.activo !== false,
      });
    } else {
      setForm(emptyForm);
    }
    setDialog({ open: true, data: row });
  };

  const handleClose = () => setDialog({ open: false, data: null });

  const handleSubmit = () => {
    const payload = {
      anio_desde: Number(form.anio_desde),
      anio_hasta: Number(form.anio_hasta),
      cc_desde: Number(form.cc_desde),
      cc_hasta: Number(form.cc_hasta),
      tasa_isc_pct: Number(form.tasa_isc_pct),
      descripcion: form.descripcion?.trim() || undefined,
      vigente_desde: form.vigente_desde,
      vigente_hasta: form.vigente_hasta || undefined,
      activo: form.activo,
    };

    if (!payload.anio_desde || !payload.anio_hasta || !payload.cc_desde || !payload.cc_hasta) {
      toast.error("Completá los rangos de año y cilindrada");
      return;
    }
    if (payload.anio_hasta < payload.anio_desde) {
      toast.error("Año hasta debe ser ≥ Año desde");
      return;
    }
    if (payload.cc_hasta < payload.cc_desde) {
      toast.error("cc hasta debe ser ≥ cc desde");
      return;
    }
    if (!Number.isFinite(payload.tasa_isc_pct) || payload.tasa_isc_pct < 0) {
      toast.error("Tasa ISC inválida");
      return;
    }

    if (dialog.data?.id) {
      updateMutation.mutate({ id: dialog.data.id, payload });
    } else {
      createMutation.mutate(payload);
    }
  };

  const handleDelete = (row) => {
    if (row.empresa_id == null) {
      toast.error("No se puede eliminar una tasa del sistema");
      return;
    }
    setDeleteTarget(row);
  };

  const confirmarEliminar = () => {
    if (!deleteTarget?.id) return;
    deleteMutation.mutate(deleteTarget.id);
  };

  // Preview de la tasa en el formulario
  const preview = useMemo(() => {
    const { anio_desde, anio_hasta, cc_desde, cc_hasta, tasa_isc_pct } = form;
    if (!anio_desde || !anio_hasta || !cc_desde || !cc_hasta || !tasa_isc_pct) return null;
    return `Vehículos año ${anio_desde}–${anio_hasta}, cilindrada ${cc_desde}–${cc_hasta}cc → ISC ${tasa_isc_pct}%`;
  }, [form]);

  if (!hasAccess) {
    return <AccesoRestringido modulo="IMPORTACIONES" mensaje="No tenés acceso al módulo Importaciones." />;
  }
  if (!canConfig) {
    return (
      <AccesoRestringido modulo="IMPORTACIONES" mensaje="Necesitás el privilegio IMP_CFG_CONFIG_EDITAR." />
    );
  }

  return (
    <>
      <ScreenGuia
        titulo="¿Cómo funciona la Tabla ISC?"
        intro="Define qué tasa de Impuesto Selectivo al Consumo sugerir automáticamente según la cilindrada y el año del vehículo, al cargar el despacho aduanero."
        pasos={[
          {
            icon: "mdi:car-cog",
            color: "#60a5fa",
            titulo: "Rango de vehículo",
            desc: "Cilindrada (cc) y año del modelo que cubre esta tasa.",
          },
          {
            icon: "mdi:percent",
            color: "#f59e0b",
            titulo: "Tasa aplicable",
            desc: "Porcentaje de ISC que se sugiere automáticamente en el despacho.",
          },
          {
            icon: "mdi:calendar-range",
            color: "#22c55e",
            titulo: "Vigencia",
            desc: "Desde / hasta. Dejá \"hasta\" vacío si la tasa no tiene vencimiento previsto.",
          },
        ]}
        notas={[
          {
            icon: "mdi:lock-outline",
            text: "Las tasas de sistema (chip \"Sistema\") son de solo lectura — solo se editan/eliminan las propias de la empresa.",
          },
          {
            icon: "mdi:alert-outline",
            text: "Si un vehículo no coincide con ningún rango cargado, el despacho va a pedir cargar la tasa manualmente.",
          },
        ]}
      />

      <Paper sx={{ p: 3, borderRadius: 2, mt: 2 }}>
      <Stack direction="row" justifyContent="space-between" alignItems="flex-start" sx={{ mb: 2 }}>
        <Box>
          <Typography variant="h6" fontWeight={800}>
            Tasas ISC vehículos
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ maxWidth: 600 }}>
            Definí las tasas de Impuesto Selectivo al Consumo según cilindrada y año del modelo.
            El sistema sugerirá la tasa correspondiente automáticamente al cargar el despacho.
          </Typography>
          <Typography variant="caption" color="text.secondary">
            Ejemplo: vehículo año 2022 de 1600 cc → aplica la tasa 1001–2000 cc del rango que incluya 2022.
          </Typography>
        </Box>
        <Button
          variant="contained"
          startIcon={<Icon icon="lucide:plus" />}
          onClick={() => handleOpen(null)}
          sx={{ flexShrink: 0, ml: 2 }}
        >
          Nueva tasa
        </Button>
      </Stack>

      {isLoading ? (
        <Box sx={{ py: 2, display: "flex", alignItems: "center", gap: 1 }}>
          <CircularProgress size={18} />
          <Typography variant="body2" color="text.secondary">
            Cargando…
          </Typography>
        </Box>
      ) : !items.length ? (
        <Alert severity="info">
          No hay tasas configuradas. Agregá la primera con el botón <strong>Nueva tasa</strong>.
        </Alert>
      ) : (
        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell>Origen</TableCell>
                <TableCell>Año desde</TableCell>
                <TableCell>Año hasta</TableCell>
                <TableCell align="right">cc desde</TableCell>
                <TableCell align="right">cc hasta</TableCell>
                <TableCell align="right">Tasa %</TableCell>
                <TableCell>Vigencia</TableCell>
                <TableCell>Estado</TableCell>
                <TableCell align="right">Acciones</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {items.map((row) => {
                const isSystem = row.empresa_id == null;
                return (
                  <TableRow key={row.id} hover>
                    <TableCell>
                      <Chip
                        size="small"
                        label={isSystem ? "Sistema" : "Empresa"}
                        color={isSystem ? "default" : "primary"}
                      />
                    </TableCell>
                    <TableCell>{row.anio_desde}</TableCell>
                    <TableCell>{row.anio_hasta}</TableCell>
                    <TableCell align="right">{row.cc_desde}</TableCell>
                    <TableCell align="right">{row.cc_hasta}</TableCell>
                    <TableCell align="right">{Number(row.tasa_isc_pct).toFixed(2)}</TableCell>
                    <TableCell>
                      {fmtDate(row.vigente_desde)} → {row.vigente_hasta ? fmtDate(row.vigente_hasta) : "∞"}
                    </TableCell>
                    <TableCell>
                      <Chip
                        size="small"
                        label={row.activo ? "Activo" : "Inactivo"}
                        color={row.activo ? "success" : "default"}
                      />
                    </TableCell>
                    <TableCell align="right">
                      {!isSystem && (
                        <>
                          <Tooltip title="Editar">
                            <IconButton size="small" onClick={() => handleOpen(row)}>
                              <Icon icon="lucide:pencil" />
                            </IconButton>
                          </Tooltip>
                          <Tooltip title="Eliminar">
                            <IconButton size="small" color="error" onClick={() => handleDelete(row)}>
                              <Icon icon="lucide:trash-2" />
                            </IconButton>
                          </Tooltip>
                        </>
                      )}
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      <Dialog open={dialog.open} onClose={handleClose} maxWidth="sm" fullWidth>
        <DialogTitle>{dialog.data?.id ? "Editar tasa ISC" : "Nueva tasa ISC"}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ pt: 1 }}>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                size="small"
                type="number"
                label="Año desde *"
                placeholder={`ej: ${new Date().getFullYear() - 5}`}
                value={form.anio_desde}
                onChange={(e) => setForm((p) => ({ ...p, anio_desde: e.target.value }))}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                size="small"
                type="number"
                label="Año hasta *"
                placeholder={`ej: ${new Date().getFullYear() + 5}`}
                value={form.anio_hasta}
                onChange={(e) => setForm((p) => ({ ...p, anio_hasta: e.target.value }))}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                size="small"
                type="number"
                label="Cilindrada desde (cc) *"
                placeholder="ej: 1001"
                value={form.cc_desde}
                onChange={(e) => setForm((p) => ({ ...p, cc_desde: e.target.value }))}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                size="small"
                type="number"
                label="Cilindrada hasta (cc) *"
                placeholder="ej: 2000"
                value={form.cc_hasta}
                onChange={(e) => setForm((p) => ({ ...p, cc_hasta: e.target.value }))}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                size="small"
                type="number"
                inputProps={{ step: "0.01", min: 0 }}
                label="Tasa ISC % *"
                placeholder="ej: 5.00"
                value={form.tasa_isc_pct}
                onChange={(e) => setForm((p) => ({ ...p, tasa_isc_pct: e.target.value }))}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }} sx={{ display: "flex", alignItems: "center" }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={form.activo}
                    onChange={(e) => setForm((p) => ({ ...p, activo: e.target.checked }))}
                  />
                }
                label="Activo"
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                size="small"
                type="date"
                label="Vigente desde *"
                InputLabelProps={{ shrink: true }}
                value={form.vigente_desde}
                onChange={(e) => setForm((p) => ({ ...p, vigente_desde: e.target.value }))}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                size="small"
                type="date"
                label="Vigente hasta"
                InputLabelProps={{ shrink: true }}
                value={form.vigente_hasta}
                onChange={(e) => setForm((p) => ({ ...p, vigente_hasta: e.target.value }))}
                helperText="Dejá vacío si la tasa no tiene vencimiento previsto"
              />
            </Grid>
            <Grid size={12}>
              <TextField
                fullWidth
                size="small"
                label="Descripción (opcional)"
                placeholder="ej: Sedanes 1001–2000cc mod. 2020–2030"
                value={form.descripcion}
                onChange={(e) => setForm((p) => ({ ...p, descripcion: e.target.value }))}
              />
            </Grid>
            {preview && (
              <Grid size={12}>
                <Alert severity="info" sx={{ py: 0.5 }}>
                  <Typography variant="caption">{preview}</Typography>
                </Alert>
              </Grid>
            )}
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose}>Cancelar</Button>
          <Button
            variant="contained"
            onClick={handleSubmit}
            disabled={createMutation.isPending || updateMutation.isPending}
          >
            Guardar
          </Button>
        </DialogActions>
      </Dialog>
      </Paper>

      <ConfirmDialog
        open={Boolean(deleteTarget)}
        onClose={() => (deleteMutation.isPending ? undefined : setDeleteTarget(null))}
        onConfirm={confirmarEliminar}
        loading={deleteMutation.isPending}
        title="Eliminar tasa ISC"
        message={
          deleteTarget
            ? `¿Eliminar la tasa ISC ${deleteTarget.cc_desde}–${deleteTarget.cc_hasta}cc / ${deleteTarget.anio_desde}–${deleteTarget.anio_hasta}?`
            : ""
        }
        confirmText="Sí, eliminar"
        cancelText="Volver"
        confirmColor="error"
      />
    </>
  );
}

export default IscVehiculosTab;
