import { Autocomplete, Box, TextField } from "@mui/material";
import { Edit, useAutocomplete } from "@refinedev/mui";
import { useForm } from "@refinedev/react-hook-form";
import { Controller } from "react-hook-form";

import { VEHICLE_TYPES } from "../../lib/constants";

type VehicleFormValues = {
  tail_number: number;
  type: number;
  city_id: number;
};

export const VehicleEdit = () => {
  const {
    saveButtonProps,
    register,
    control,
    formState: { errors },
  } = useForm<VehicleFormValues>({});

  const { autocompleteProps: carrierAutocompleteProps } = useAutocomplete({
    resource: "carrier",
    onSearch: (value) => [
      {
        field: "short_name",
        operator: "contains",
        value,
      },
    ],
  });

  return (
    <Edit saveButtonProps={saveButtonProps}>
      <Box
        component="form"
        sx={{ display: "flex", flexDirection: "column" }}
        autoComplete="off"
      >
        <TextField
          {...register("tail_number", {
            required: "Это поле является обязательным",
            valueAsNumber: true,
          })}
          error={!!(errors as any)?.tail_number}
          helperText={(errors as any)?.tail_number?.message}
          margin="normal"
          fullWidth
          InputLabelProps={{ shrink: true }}
          type="number"
          label="Бортовой номер *"
          name="tail_number"
        />

        <Controller
          control={control}
          name="type"
          rules={{
            required: "Это поле является обязательным",
          }}
          defaultValue={null}
          render={({ field }) => (
            <Autocomplete
              options={VEHICLE_TYPES}
              value={
                VEHICLE_TYPES.find((option) => option.value === field.value) ||
                null
              }
              onChange={(_, value) => {
                field.onChange(value?.value || null);
              }}
              getOptionLabel={(item) => {
                return item ? item.label : "";
              }}
              isOptionEqualToValue={(option, value) => {
                return option.value === value?.value;
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="Выберите тип"
                  margin="normal"
                  variant="outlined"
                  error={!!errors.type}
                  helperText={(errors as any)?.type?.message}
                  required
                />
              )}
            />
          )}
        />

        <Controller
          control={control}
          name="carrier_id"
          rules={{ required: "Это поле является обязательным" }}
          defaultValue={null}
          render={({ field }) => (
            <Autocomplete
              {...carrierAutocompleteProps}
              value={
                carrierAutocompleteProps.options.find(
                  (option) => option.id === field.value
                ) || null
              }
              onChange={(_, value) => {
                field.onChange(value?.id || "");
              }}
              getOptionLabel={(item) => {
                return item ? item.short_name : "";
              }}
              isOptionEqualToValue={(option, value) => {
                return option.id === value?.id;
              }}
              filterOptions={(options, { inputValue }) => {
                return options.filter((option) =>
                  option.short_name
                    .toLowerCase()
                    .includes(inputValue.toLowerCase())
                );
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="Выберите перевозчика"
                  margin="normal"
                  variant="outlined"
                  error={!!errors.city_id}
                  helperText={(errors as any)?.city_id?.message}
                  required
                />
              )}
            />
          )}
        />
      </Box>
    </Edit>
  );
};
