import {
  Button,
  Paper,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
} from "@mui/material";
import { vehicleStore, VEHICLE_TYPES, carrierStore } 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 [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    carrierStore.getCarriers();
  }, []);

  const handleCreate = async () => {
    try {
      setIsLoading(true);
      await vehicleStore.createVehicle(
        Number(tailNumber),
        Number(type),
        carrierStore.carriers.data.find((c) => c.id === carrierId)?.full_name!,
        carrierId!
      );
      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>
          <InputLabel>Тип</InputLabel>
          <Select
            value={type}
            label="Тип"
            required
            onChange={(e) => setType(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={carrierId || ""}
            label="Перевозчик"
            required
            onChange={(e) => setCarrierId(e.target.value as number)}
          >
            {carrierStore.carriers.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={handleCreate}
          disabled={isLoading || !tailNumber || !type || !carrierId}
        >
          {isLoading ? (
            <Loader2 size={20} className="animate-spin" />
          ) : (
            "Создать"
          )}
        </Button>
      </div>
    </Paper>
  );
});
