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

export const MediaCreatePage = observer(() => {
  const navigate = useNavigate();
  const [name, setName] = useState("");
  const [type, setType] = useState("");
  const [isLoading, setIsLoading] = useState(false);

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

  const handleCreate = async () => {
    try {
      setIsLoading(true);
      await mediaStore.createMedia(name, type, selectedCityStore.selectedCityId);
      toast.success("Медиа успешно создано");
      navigate("/media");
    } catch (error) {
      toast.error("Ошибка при создании медиа");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Paper className="w-full h-full p-3 flex flex-col gap-10">
      <div className="flex justify-between items-center">
        <button
          className="flex items-center gap-2"
          onClick={() => navigate(-1)}
        >
          <ArrowLeft size={20} />
          Назад
        </button>
      </div>
      <h1 className="text-2xl font-bold">Создание медиа</h1>
      <div className="flex flex-col gap-10 w-full items-end">
        <TextField
          className="w-full"
          label="Название"
          required
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <FormControl fullWidth>
          <InputLabel>Тип</InputLabel>
          <Select
            value={type}
            label="Тип"
            onChange={(e) => setType(e.target.value)}
            required
          >
            {Object.entries(MEDIA_TYPE_LABELS).map(([value, label]) => (
              <MenuItem key={value} value={value}>
                {label}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

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