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

export const VehicleCreatePage = observer(() => {
  const navigate = useNavigate();
  const [tailNumber, setTailNumber] = useState("");
  const [type, setType] = useState("");
  const [carrierId, setCarrierId] = useState<number | null>(null);
  const [model, setModel] = useState("");
  const [cityId, setCityId] = useState<number | null>(selectedCityStore.selectedCityId);
  const [isLoading, setIsLoading] = useState(false);
  const { language } = languageStore;

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

  useEffect(() => {
    carrierStore.getCarriers(language);
    cityStore.getCities("ru");
  }, [language]);

  const handleCreate = async () => {
    try {
      setIsLoading(true);
      await vehicleStore.createVehicle(
        tailNumber,
        Number(type),
        carrierStore.carriers[language].data?.find((c) => c.id === carrierId)
          ?.full_name as string,
        carrierId!,
        model || undefined,
        cityId ?? undefined,
      );
      toast.success("Транспорт успешно создан");
    } 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={tailNumber}
          required
          onChange={(e) => setTailNumber(e.target.value)}
        />

        <FormControl fullWidth required>
          <InputLabel>Тип</InputLabel>
          <Select
            value={type}
            label="Тип"
            onChange={(e) => setType(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={carrierId || ""}
            label="Перевозчик"
            onChange={(e) => setCarrierId(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={model}
          onChange={(e) => setModel(e.target.value)}
          placeholder="Произвольное название модели"
        />

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

        <Button
          variant="contained"
          className="w-min flex gap-2 items-center"
          startIcon={<Save size={20} />}
          onClick={handleCreate}
          disabled={isLoading || !tailNumber || !type || !carrierId || !cityId}
        >
          {isLoading ? (
            <Loader2 size={20} className="animate-spin" />
          ) : (
            "Создать"
          )}
        </Button>
      </div>
    </Paper>
  );
});
