import {
  Autocomplete,
  Box,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import {
  useCreateVehiculoMutation,
  useUpdateVehiculoMutation,
} from "../../../tanstack/VehiculosStack";
import { useTransportistasQuery } from "../../../tanstack/TransportistasStack";
import { useReferencialesQuery } from "../../../tanstack/ReferencialesStack";

export const VehiculoFormDialog = ({ open, onClose, vehiculo }) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));
  const isEdit = !!vehiculo;
  const createMutation = useCreateVehiculoMutation();
  const updateMutation = useUpdateVehiculoMutation();
  const { data: transportistasData } = useTransportistasQuery(1, 200);
  const transportistas = transportistasData?.items || [];
  const { data: referenciales } = useReferencialesQuery();
  const modalidades = referenciales?.modalidad_transporte || [];
  const tiposTransporte = referenciales?.tipo_transporte || [];

  const { control, handleSubmit, reset, watch, formState: { errors } } = useForm({
    defaultValues: {
      transportista_id: "",
      modalidad_transporte_id: "",
      tipo_transporte_id: "",
      marca: "",
      modelo: "",
      anio: "",
      tipo_vehiculo: "",
      nro_matricula: "",
      nro_identificacion: "",
      tipo_identificacion: 1,
      capacidad_carga_kg: "",
      informacion_adicional: "",
    },
  });

  useEffect(() => {
    if (open) {
      if (vehiculo) {
        reset({
          transportista_id: vehiculo.transportista_id || "",
          modalidad_transporte_id: vehiculo.modalidad_transporte_id || "",
          tipo_transporte_id: vehiculo.tipo_transporte_id || "",
          marca: vehiculo.marca || "",
          modelo: vehiculo.modelo || "",
          anio: vehiculo.anio || "",
          tipo_vehiculo: vehiculo.tipo_vehiculo || "",
          nro_matricula: vehiculo.nro_matricula || "",
          nro_identificacion: vehiculo.nro_identificacion || "",
          tipo_identificacion: vehiculo.tipo_identificacion || 1,
          capacidad_carga_kg: vehiculo.capacidad_carga_kg || "",
          informacion_adicional: vehiculo.informacion_adicional || "",
        });
      } else {
        reset();
      }
    }
  }, [open, vehiculo, reset]);

  const onSubmit = (data) => {
    const payload = { ...data };
    if (payload.anio) payload.anio = Number(payload.anio);
    if (payload.capacidad_carga_kg) payload.capacidad_carga_kg = Number(payload.capacidad_carga_kg);
    if (!payload.anio) delete payload.anio;
    if (!payload.capacidad_carga_kg) delete payload.capacidad_carga_kg;
    // UUIDs vacíos → null
    ["modalidad_transporte_id", "tipo_transporte_id"].forEach((f) => {
      if (!payload[f]) payload[f] = null;
    });
    // Opcionales vacíos → null
    ["modelo", "nro_matricula", "nro_identificacion", "informacion_adicional", "tipo_vehiculo"].forEach((f) => {
      if (!payload[f]) payload[f] = null;
    });

    if (isEdit) {
      updateMutation.mutate({ id: vehiculo.id, data: payload }, { onSuccess: onClose });
    } else {
      createMutation.mutate(payload, { onSuccess: onClose });
    }
  };

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

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth fullScreen={isMobile}>
      <DialogTitle>
        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
          {isEdit ? "Editar Vehículo" : "Nuevo Vehículo"}
          {isEdit && <Chip label="Edición" size="small" color="warning" />}
        </Box>
      </DialogTitle>
      <form onSubmit={handleSubmit(onSubmit)}>
        <DialogContent dividers>
          <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr 1fr" }, gap: 2 }}>

            {/* Fila 1: Transportista, Tipo transporte, Modalidad */}
            <Controller
              name="transportista_id"
              control={control}
              rules={{ required: "Transportista es obligatorio" }}
              render={({ field }) => (
                <Autocomplete
                  options={transportistas}
                  getOptionLabel={(o) => o.personas?.razon_social || ""}
                  value={transportistas.find((t) => t.id === field.value) || null}
                  onChange={(_, v) => field.onChange(v?.id || "")}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="Emp. Transportista *"
                      error={!!errors.transportista_id}
                      helperText={errors.transportista_id?.message}
                    />
                  )}
                />
              )}
            />

            <Controller
              name="tipo_transporte_id"
              control={control}
              rules={{ required: "Tipo transporte es obligatorio" }}
              render={({ field }) => (
                <Autocomplete
                  options={tiposTransporte}
                  getOptionLabel={(o) => `${o.codigo} - ${o.descripcion}`}
                  value={tiposTransporte.find((t) => t.id === field.value) || null}
                  onChange={(_, v) => field.onChange(v?.id || "")}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="Tipo transporte *"
                      error={!!errors.tipo_transporte_id}
                      helperText={errors.tipo_transporte_id?.message}
                    />
                  )}
                />
              )}
            />

            <Controller
              name="modalidad_transporte_id"
              control={control}
              rules={{ required: "Modalidad es obligatoria" }}
              render={({ field }) => (
                <Autocomplete
                  options={modalidades}
                  getOptionLabel={(o) => `${o.codigo} - ${o.descripcion}`}
                  value={modalidades.find((m) => m.id === field.value) || null}
                  onChange={(_, v) => field.onChange(v?.id || "")}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="Modalidad *"
                      error={!!errors.modalidad_transporte_id}
                      helperText={errors.modalidad_transporte_id?.message}
                    />
                  )}
                />
              )}
            />

            {/* Fila 2: Marca, Tipo vehículo, Tipo identificación */}
            <Controller
              name="marca"
              control={control}
              rules={{ required: "Marca es obligatoria", maxLength: { value: 10, message: "Máximo 10 caracteres" } }}
              render={({ field }) => (
                <TextField
                  {...field}
                  label="Marca *"
                  fullWidth
                  inputProps={{ maxLength: 10 }}
                  error={!!errors.marca}
                  helperText={errors.marca?.message || `${field.value?.length || 0}/10`}
                />
              )}
            />

            <Controller
              name="tipo_vehiculo"
              control={control}
              rules={{ required: "Tipo vehículo es obligatorio", minLength: { value: 4, message: "Mínimo 4 caracteres" }, maxLength: { value: 10, message: "Máximo 10 caracteres" } }}
              render={({ field }) => (
                <TextField
                  {...field}
                  label="Tipo vehículo *"
                  fullWidth
                  inputProps={{ maxLength: 10 }}
                  error={!!errors.tipo_vehiculo}
                  helperText={errors.tipo_vehiculo?.message || `${field.value?.length || 0}/10`}
                />
              )}
            />

            <Controller
              name="tipo_identificacion"
              control={control}
              rules={{ required: "Tipo identificación es obligatorio" }}
              render={({ field }) => (
                <FormControl fullWidth error={!!errors.tipo_identificacion}>
                  <InputLabel>Tipo identificación *</InputLabel>
                  <Select {...field} label="Tipo identificación *">
                    <MenuItem value={1}>1 - Matrícula</MenuItem>
                    <MenuItem value={2}>2 - Identificación</MenuItem>
                  </Select>
                </FormControl>
              )}
            />
          </Box>

          <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 2, mt: 2 }}>
            {/* Nro matrícula: obligatorio si tipo_identificacion === 1 */}
            <Controller
              name="nro_matricula"
              control={control}
              rules={{
                required: watch("tipo_identificacion") === 1 ? "Nro. Matrícula es obligatorio" : false,
                maxLength: { value: 7, message: "Máximo 7 caracteres" },
              }}
              render={({ field }) => (
                <TextField
                  {...field}
                  label={watch("tipo_identificacion") === 1 ? "Nro. Matrícula *" : "Nro. Matrícula"}
                  fullWidth
                  inputProps={{ maxLength: 7 }}
                  error={!!errors.nro_matricula}
                  helperText={errors.nro_matricula?.message}
                />
              )}
            />

            {/* Nro identificación: obligatorio si tipo_identificacion === 2 */}
            <Controller
              name="nro_identificacion"
              control={control}
              rules={{
                required: watch("tipo_identificacion") === 2 ? "Nro. Identificación es obligatorio" : false,
                maxLength: { value: 20, message: "Máximo 20 caracteres" },
              }}
              render={({ field }) => (
                <TextField
                  {...field}
                  label={watch("tipo_identificacion") === 2 ? "Nro. Identificación *" : "Nro. Identificación"}
                  fullWidth
                  inputProps={{ maxLength: 20 }}
                  error={!!errors.nro_identificacion}
                  helperText={errors.nro_identificacion?.message}
                />
              )}
            />

            {/* Fila 4: Modelo, Capacidad carga */}
            <Controller
              name="modelo"
              control={control}
              render={({ field }) => (
                <TextField {...field} label="Modelo" fullWidth inputProps={{ maxLength: 60 }} />
              )}
            />

            <Controller
              name="capacidad_carga_kg"
              control={control}
              render={({ field }) => (
                <TextField {...field} label="Capacidad carga (kg)" fullWidth type="number" inputProps={{ min: 0 }} />
              )}
            />

            {/* Fila 5: Info adicional (span completo) */}
            <Box sx={{ gridColumn: "1 / -1" }}>
              <Controller
                name="informacion_adicional"
                control={control}
                render={({ field }) => (
                  <TextField {...field} label="Dato adicional del vehículo" fullWidth inputProps={{ maxLength: 20 }} />
                )}
              />
            </Box>
          </Box>
        </DialogContent>
        <DialogActions sx={{ p: 2, gap: 1 }}>
          <Button onClick={onClose} variant="outlined" disabled={isPending}>Cancelar</Button>
          <Button type="submit" variant="contained" disabled={isPending}>
            {isPending ? <CircularProgress size={20} /> : isEdit ? "Guardar" : "Crear"}
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  );
};
