import {
  Paper,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
} from "@mui/material";
import { observer } from "mobx-react-lite";
import { ArrowLeft, Loader2, Save } from "lucide-react";
import { useNavigate, useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import {
  carrierStore,
  languageStore,
  VEHICLE_TYPES,
  vehicleStore,
} from "@shared";
import { toast } from "react-toastify";

export const VehicleEditPage = observer(() => {
  const navigate = useNavigate();
  const { id } = useParams();
  const {
    getVehicle,
    vehicle,
    editVehicleData,
    setEditVehicleData,
    editVehicle,
  } = vehicleStore;
  const { getCarriers } = carrierStore;
  const { language } = languageStore;

  useEffect(() => {
    // Устанавливаем русский язык при загрузке страницы
    languageStore.setLanguage("ru");
  }, []);

  useEffect(() => {
    (async () => {
      await getVehicle(Number(id));
      await getCarriers(language);

      setEditVehicleData({
        tail_number: vehicle[Number(id)]?.vehicle.tail_number,
        type: vehicle[Number(id)]?.vehicle.type,
        carrier: vehicle[Number(id)]?.vehicle.carrier,
        carrier_id: vehicle[Number(id)]?.vehicle.carrier_id,
      });
    })();
  }, [id, language]);
  const [isLoading, setIsLoading] = useState(false);
  const handleEdit = async () => {
    try {
      setIsLoading(true);
      await editVehicle(Number(id), editVehicleData);
      toast.success("Транспортное средство успешно обновлено");
      navigate("/vehicle");
    } catch (error) {
      toast.error("Ошибка при обновлении транспортного средства");
    } finally {
      setIsLoading(false);
    }
  };
  return (
    <Paper className="w-full h-full p-3 flex flex-col gap-10">
      <div className="flex items-center gap-4">
        <button
          className="flex items-center gap-2"
          onClick={() => navigate(-1)}
        >
          <ArrowLeft size={20} />
          Назад
        </button>
      </div>

      <div className="flex flex-col gap-10 w-full items-end">
        <TextField
          fullWidth
          label="Бортовой номер"
          value={editVehicleData.tail_number}
          required
          onChange={(e) =>
            setEditVehicleData({
              ...editVehicleData,
              tail_number: Number(e.target.value),
            })
          }
        />

        <FormControl fullWidth>
          <InputLabel>Тип</InputLabel>
          <Select
            value={editVehicleData.type}
            label="Тип"
            required
            onChange={(e) =>
              setEditVehicleData({ ...editVehicleData, type: e.target.value })
            }
          >
            {VEHICLE_TYPES.map((type) => (
              <MenuItem key={type.value} value={type.value}>
                {type.label}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <FormControl fullWidth>
          <InputLabel>Перевозчик</InputLabel>
          <Select
            value={editVehicleData.carrier_id}
            label="Перевозчик"
            required
            onChange={(e) =>
              setEditVehicleData({
                ...editVehicleData,
                carrier_id: e.target.value as number,
              })
            }
          >
            {carrierStore.carriers[language].data?.map((carrier) => (
              <MenuItem key={carrier.id} value={carrier.id}>
                {carrier.full_name}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <Button
          variant="contained"
          className="w-min flex gap-2 items-center"
          startIcon={<Save size={20} />}
          onClick={handleEdit}
          disabled={
            isLoading ||
            !editVehicleData.tail_number ||
            !editVehicleData.type ||
            !editVehicleData.carrier_id
          }
        >
          {isLoading ? (
            <Loader2 size={20} className="animate-spin" />
          ) : (
            "Сохранить"
          )}
        </Button>
      </div>
    </Paper>
  );
});
