import {
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  FormControlLabel,
  MenuItem,
  Switch,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { MonedaInput } from "../common/MonedaInput";
import { useEffect, useMemo, useState } from "react";
import { ProveedorSelector } from "../organismos/ProveedoresDesign/ProveedorSelector";

const CRITERIOS = [
  { value: "FOB", label: "FOB", tooltip: "Se distribuye proporcionalmente según el valor FOB de cada ítem" },
  { value: "PESO", label: "Peso (kg)", tooltip: "Se distribuye proporcionalmente según el peso de cada ítem" },
  { value: "CBM", label: "Volumen (CBM)", tooltip: "Se distribuye proporcionalmente según el volumen en m³ de cada ítem" },
  { value: "CANTIDAD", label: "Cantidad", tooltip: "Se distribuye proporcionalmente según la cantidad de unidades de cada ítem" },
  { value: "IGUAL", label: "Partes iguales", tooltip: "El mismo monto para cada ítem, sin importar valor, peso ni volumen" },
];

const emptyForm = {
  concepto_id: "",
  item_id: "",
  moneda_id: "",
  proveedor_id: "",
  descripcion: "",
  numero_factura: "",
  importe: 0,
  cotizacion: 1,
  es_directo: false,
  criterio_prorrateo: "FOB",
  fecha_devengo: "",
  fecha_pago: "",
  es_gasto_extra: false,
  motivo_gasto_extra: "",
  observaciones: "",
};

const itemLabel = (item) => {
  if (!item) return "";
  return item.chasis || item.sku_proveedor || item.descripcion_origen || item.producto?.descripcion || "Sin descripción";
};

const conceptoLabel = (concepto) => {
  if (!concepto) return "";
  const titulo = concepto.nombre || concepto.descripcion || concepto.codigo;
  const sufijo = concepto.es_sistema ? " · sistema" : "";
  return `${titulo}${sufijo}`;
};

function SectionLabel({ children }) {
  return (
    <Box sx={{ gridColumn: "1 / -1", display: "flex", alignItems: "center", gap: 1, mt: 0.5 }}>
      <Typography variant="caption" color="text.secondary" sx={{ whiteSpace: "nowrap", fontWeight: 600 }}>
        {children}
      </Typography>
      <Divider sx={{ flex: 1 }} />
    </Box>
  );
}

export function CostoFormDialog({ open, onClose, onSubmit, embarque, costo, conceptos = [], monedas = [], loading = false }) {
  const [form, setForm] = useState(emptyForm);
  const [proveedor, setProveedor] = useState(null);

  useEffect(() => {
    if (!open) return;
    if (costo?.id) {
      setForm({
        concepto_id: costo.concepto_id || "",
        item_id: costo.item_id || "",
        moneda_id: costo.moneda_id || "",
        proveedor_id: costo.proveedor_id || "",
        descripcion: costo.descripcion || "",
        numero_factura: costo.numero_factura || "",
        importe: Number(costo.importe || 0),
        cotizacion: Number(costo.cotizacion || 1),
        es_directo: Boolean(costo.es_directo),
        criterio_prorrateo: costo.criterio_prorrateo || "FOB",
        fecha_devengo: costo.fecha_devengo ? String(costo.fecha_devengo).slice(0, 10) : "",
        fecha_pago: costo.fecha_pago ? String(costo.fecha_pago).slice(0, 10) : "",
        es_gasto_extra: Boolean(costo.es_gasto_extra),
        motivo_gasto_extra: costo.motivo_gasto_extra || "",
        observaciones: costo.observaciones || "",
      });
      setProveedor(costo.proveedor || null);
    } else {
      setForm(emptyForm);
      setProveedor(null);
    }
  }, [open, costo]);

  const monedaOptions = useMemo(
    () => (Array.isArray(monedas) ? monedas : []).map((m) => m.moneda || m).filter(Boolean),
    [monedas],
  );

  const monedaSeleccionada = useMemo(
    () => monedaOptions.find((m) => m.id === form.moneda_id) || null,
    [monedaOptions, form.moneda_id],
  );

  const importeGs = Number(form.importe || 0) * Number(form.cotizacion || 1);

  const handleChange = (field, value) => {
    setForm((prev) => ({ ...prev, [field]: value }));
  };

  const motivoFaltante = form.es_gasto_extra && !form.motivo_gasto_extra.trim();

  const criterioActual = CRITERIOS.find((c) => c.value === form.criterio_prorrateo);

  const handleSubmit = () => {
    onSubmit?.({
      concepto_id: form.concepto_id,
      item_id: form.es_directo ? form.item_id : undefined,
      moneda_id: form.moneda_id || undefined,
      proveedor_id: proveedor?.id || form.proveedor_id || undefined,
      descripcion: form.descripcion?.trim() || undefined,
      numero_factura: form.numero_factura?.trim() || undefined,
      importe: Number(form.importe || 0),
      cotizacion: Number(form.cotizacion || 1),
      es_directo: form.es_directo,
      criterio_prorrateo: form.es_directo ? undefined : form.criterio_prorrateo,
      fecha_devengo: form.fecha_devengo || undefined,
      fecha_pago: form.fecha_pago || undefined,
      es_gasto_extra: form.es_gasto_extra,
      motivo_gasto_extra: form.es_gasto_extra ? form.motivo_gasto_extra.trim() : undefined,
      observaciones: form.observaciones?.trim() || undefined,
    });
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>{costo?.id ? "Editar costo" : "Agregar costo"}</DialogTitle>
      <DialogContent sx={{ pt: 2 }}>
        <Box
          sx={{
            mt: 0,
            display: "grid",
            gap: 2,
            gridTemplateColumns: {
              xs: "1fr",
              sm: "repeat(2, minmax(0, 1fr))",
              md: "repeat(12, minmax(0, 1fr))",
            },
            "& .MuiFormControl-root": { minWidth: 0 },
          }}
        >
          <SectionLabel>¿Qué costo es?</SectionLabel>

          <Box sx={{ gridColumn: { xs: "1 / -1", md: "span 7" } }}>
            <TextField
              select
              fullWidth
              required
              size="small"
              label="Concepto"
              value={form.concepto_id}
              onChange={(e) => handleChange("concepto_id", e.target.value)}
              SelectProps={{ MenuProps: { PaperProps: { sx: { minWidth: 320 } } } }}
            >
              {conceptos.map((concepto) => (
                <MenuItem key={concepto.id} value={concepto.id}>
                  {conceptoLabel(concepto)}
                </MenuItem>
              ))}
            </TextField>
          </Box>
          <Box sx={{ gridColumn: { xs: "1 / -1", md: "span 5" } }}>
            <TextField
              select
              fullWidth
              size="small"
              label="Moneda"
              value={form.moneda_id}
              onChange={(e) => handleChange("moneda_id", e.target.value)}
              SelectProps={{ MenuProps: { PaperProps: { sx: { minWidth: 260 } } } }}
            >
              <MenuItem value="">Sin moneda</MenuItem>
              {monedaOptions.map((m) => (
                <MenuItem key={m.id} value={m.id}>
                  {m.codigo} {m.descripcion ? `- ${m.descripcion}` : ""}
                </MenuItem>
              ))}
            </TextField>
          </Box>
          <Box sx={{ gridColumn: { xs: "1 / -1", md: "span 12" } }}>
            <TextField
              fullWidth
              size="small"
              label="Descripción libre"
              placeholder="Detalle adicional sobre este costo (opcional)"
              value={form.descripcion}
              onChange={(e) => handleChange("descripcion", e.target.value)}
            />
          </Box>

          <SectionLabel>¿De quién?</SectionLabel>

          <Box sx={{ gridColumn: { xs: "1 / -1", md: "span 8" } }}>
            <ProveedorSelector value={proveedor} onChange={setProveedor} label="Proveedor (opcional)" contexto="todos" />
          </Box>
          <Box sx={{ gridColumn: { xs: "1 / -1", md: "span 4" } }}>
            <TextField
              fullWidth
              size="small"
              label="N° factura"
              placeholder="ej: 001-001-0000123"
              value={form.numero_factura}
              onChange={(e) => handleChange("numero_factura", e.target.value)}
            />
          </Box>

          <SectionLabel>¿Cómo se aplica?</SectionLabel>

          <Box sx={{ gridColumn: { xs: "1 / -1", md: "span 4" }, display: "flex", alignItems: "flex-start", flexDirection: "column", gap: 0.25 }}>
            <FormControlLabel
              control={<Switch checked={form.es_directo} onChange={(e) => handleChange("es_directo", e.target.checked)} />}
              label="Costo directo a un ítem"
              sx={{ m: 0 }}
            />
            <Typography variant="caption" color="text.secondary" sx={{ pl: 1 }}>
              Activar solo si aplica a un vehículo/SKU específico
            </Typography>
          </Box>

          {form.es_directo ? (
            <Box sx={{ gridColumn: { xs: "1 / -1", md: "span 8" } }}>
              <TextField
                select
                fullWidth
                required
                size="small"
                label="Ítem al que aplica"
                value={form.item_id}
                onChange={(e) => handleChange("item_id", e.target.value)}
                SelectProps={{ MenuProps: { PaperProps: { sx: { minWidth: 360 } } } }}
              >
                {(embarque?.items || []).map((item) => (
                  <MenuItem key={item.id} value={item.id}>
                    {itemLabel(item)}
                  </MenuItem>
                ))}
              </TextField>
            </Box>
          ) : (
            <Box sx={{ gridColumn: { xs: "1 / -1", md: "span 8" } }}>
              <TextField
                select
                fullWidth
                size="small"
                label="Criterio de prorrateo"
                value={form.criterio_prorrateo}
                onChange={(e) => handleChange("criterio_prorrateo", e.target.value)}
                helperText={criterioActual?.tooltip}
                SelectProps={{ MenuProps: { PaperProps: { sx: { minWidth: 220 } } } }}
              >
                {CRITERIOS.map((c) => (
                  <MenuItem key={c.value} value={c.value}>{c.label}</MenuItem>
                ))}
              </TextField>
            </Box>
          )}

          <SectionLabel>Fechas</SectionLabel>

          <Box sx={{ gridColumn: { xs: "1 / -1", sm: "span 1", md: "span 6" } }}>
            <TextField
              fullWidth
              size="small"
              type="date"
              label="Fecha devengo"
              InputLabelProps={{ shrink: true }}
              value={form.fecha_devengo}
              onChange={(e) => handleChange("fecha_devengo", e.target.value)}
              helperText="Cuándo se generó la obligación (ej: fecha de la factura)"
            />
          </Box>
          <Box sx={{ gridColumn: { xs: "1 / -1", sm: "span 1", md: "span 6" } }}>
            <TextField
              fullWidth
              size="small"
              type="date"
              label="Fecha pago"
              InputLabelProps={{ shrink: true }}
              value={form.fecha_pago}
              onChange={(e) => handleChange("fecha_pago", e.target.value)}
              helperText="Cuándo se pagó o se pagará al proveedor"
            />
          </Box>

          <SectionLabel>Importe</SectionLabel>

          <Box sx={{ gridColumn: { xs: "1 / -1", sm: "span 1", md: "span 4" } }}>
            <MonedaInput
              fullWidth
              required
              label={`Importe${monedaSeleccionada?.codigo ? ` (${monedaSeleccionada.codigo})` : ""} *`}
              value={Number(form.importe || 0)}
              onChange={(n) => handleChange("importe", n)}
              moneda={monedaSeleccionada?.codigo || "PYG"}
              decimales={monedaSeleccionada?.codigo === "PYG" ? 0 : 4}
            />
          </Box>
          <Box sx={{ gridColumn: { xs: "1 / -1", sm: "span 1", md: "span 4" } }}>
            <MonedaInput
              fullWidth
              required
              label="Cotización (Gs/moneda)"
              value={Number(form.cotizacion || 0)}
              onChange={(n) => handleChange("cotizacion", n)}
              moneda="PYG"
              helperText="Tipo de cambio al momento de este costo"
            />
          </Box>
          <Box sx={{ gridColumn: { xs: "1 / -1", sm: "span 1", md: "span 4" } }}>
            <TextField
              fullWidth
              size="small"
              label="= Importe en Gs."
              value={Math.round(importeGs).toLocaleString("es-PY")}
              InputProps={{ readOnly: true }}
              sx={{ "& .MuiInputBase-root": { bgcolor: "action.hover" } }}
            />
          </Box>

          <SectionLabel>Extras</SectionLabel>

          <Box sx={{ gridColumn: { xs: "1 / -1", md: "span 4" }, display: "flex", alignItems: "flex-start", flexDirection: "column", gap: 0.25 }}>
            <FormControlLabel
              control={<Switch checked={form.es_gasto_extra} onChange={(e) => handleChange("es_gasto_extra", e.target.checked)} />}
              label="Gasto extra de gestión"
              sx={{ m: 0 }}
            />
            <Typography variant="caption" color="text.secondary" sx={{ pl: 1 }}>
              Para costos no previstos — queda auditado en la bitácora
            </Typography>
          </Box>

          {form.es_gasto_extra && (
            <Box sx={{ gridColumn: { xs: "1 / -1", md: "span 8" } }}>
              <TextField
                fullWidth
                required
                size="small"
                label="Motivo del gasto extra"
                placeholder="ej: Almacenamiento extendido por demora en aduana"
                value={form.motivo_gasto_extra}
                onChange={(e) => handleChange("motivo_gasto_extra", e.target.value)}
                error={motivoFaltante}
                helperText={motivoFaltante ? "Campo obligatorio cuando es gasto extra" : "Describí la causa del gasto no previsto"}
              />
            </Box>
          )}

          <Box sx={{ gridColumn: "1 / -1" }}>
            <TextField
              fullWidth
              multiline
              minRows={2}
              size="small"
              label="Observaciones"
              placeholder="Notas internas adicionales (opcional)"
              value={form.observaciones}
              onChange={(e) => handleChange("observaciones", e.target.value)}
            />
          </Box>
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancelar</Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
          disabled={
            loading ||
            !form.concepto_id ||
            (form.es_directo && !form.item_id) ||
            motivoFaltante
          }
        >
          Guardar
        </Button>
      </DialogActions>
    </Dialog>
  );
}

export default CostoFormDialog;
