import {
  Paper,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
  Box,
  FormControlLabel,
  Checkbox,
} 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,
  LoadingSpinner,
  cityStore,
  selectedCityStore,
} 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;
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingData, setIsLoadingData] = useState(true);

  useEffect(() => {
    selectedCityStore.setIsLocked(true);
    return () => selectedCityStore.setIsLocked(false);
  }, []);

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

  useEffect(() => {
    const fetchAndSetVehicleData = async () => {
      if (!id) {
        setIsLoadingData(false);
        return;
      }

      setIsLoadingData(true);
      try {
        await getVehicle(Number(id));
        await getCarriers(language);
        await cityStore.getCities("ru");

        setEditVehicleData({
          tail_number: vehicle[Number(id)]?.vehicle.tail_number ?? "",
          type: vehicle[Number(id)]?.vehicle.type ?? 0,
          carrier: vehicle[Number(id)]?.vehicle.carrier ?? "",
          carrier_id: vehicle[Number(id)]?.vehicle.carrier_id ?? 0,
          model: vehicle[Number(id)]?.vehicle.model ?? "",
          snapshot_update_blocked:
            vehicle[Number(id)]?.vehicle.snapshot_update_blocked ?? false,
          city_id: vehicle[Number(id)]?.vehicle.city_id ?? selectedCityStore.selectedCityId ?? undefined,
        });
      } finally {
        setIsLoadingData(false);
      }
    };

    fetchAndSetVehicleData();
  }, [id, language]);
  const handleEdit = async () => {
    try {
      setIsLoading(true);
      await editVehicle(Number(id), editVehicleData);
      toast.success("Транспортное средство успешно обновлено");
      navigate("/devices");
    } catch (error) {
      toast.error("Ошибка при обновлении транспортного средства");
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoadingData) {
    return (
      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          minHeight: "60vh",
        }}
      >
        <LoadingSpinner message="Загрузка данных транспортного средства..." />
      </Box>
    );
  }

  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: e.target.value,
            })
          }
        />

        <FormControl fullWidth required>
          <InputLabel>Тип</InputLabel>
          <Select
            value={editVehicleData.type}
            label="Тип"
            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 required>
          <InputLabel>Перевозчик</InputLabel>
          <Select
            value={editVehicleData.carrier_id}
            label="Перевозчик"
            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>

        <TextField
          fullWidth
          label="Модель ТС"
          value={editVehicleData.model}
          onChange={(e) =>
            setEditVehicleData({
              ...editVehicleData,
              model: e.target.value,
            })
          }
          placeholder="Произвольное название модели"
        />

        <FormControl fullWidth required>
          <InputLabel>Город</InputLabel>
          <Select
            value={editVehicleData.city_id ?? ""}
            label="Город"
            onChange={(e) =>
              setEditVehicleData({
                ...editVehicleData,
                city_id: e.target.value ? Number(e.target.value) : undefined,
              })
            }
          >
            {cityStore.cities.ru.data.map((city) => (
              <MenuItem key={city.id} value={city.id}>
                {city.name}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <FormControlLabel
          control={
            <Checkbox
              checked={editVehicleData.snapshot_update_blocked}
              onChange={(e) =>
                setEditVehicleData({
                  ...editVehicleData,
                  snapshot_update_blocked: e.target.checked,
                })
              }
              color="primary"
            />
          }
          label="Блокировка обновления ПО"
        />

        <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 ||
            !editVehicleData.city_id
          }
        >
          {isLoading ? (
            <Loader2 size={20} className="animate-spin" />
          ) : (
            "Сохранить"
          )}
        </Button>
      </div>
    </Paper>
  );
});
