import React, { useState } from "react";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { uploadMission } from "../../redux/slices/missions";

const UploadMissionForm: React.FC = () => {
  const dispatch = useAppDispatch();
  const { status, error } = useAppSelector(state => state.missions);

  // Локальные состояния формы
  const [name, setName] = useState("");
  const [difficulty, setDifficulty] = useState(1);
  const [tags, setTags] = useState<string[]>([]);
  const [tagsValue, setTagsValue] = useState<string>("");
  const [file, setFile] = useState<File | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!file) return alert("Выберите файл миссии!");

    try {
      dispatch(uploadMission({ file, name, difficulty, tags }));
      
      alert("Миссия успешно загружена!");
      setName("");
      setDifficulty(1);
      setTags([]);
      setFile(null);
    } catch (err) {
      console.error(err);
      alert("Ошибка при загрузке миссии: " + err);
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setFile(e.target.files[0]);
    }
  };

  const handleTagsChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setTagsValue(e.target.value);
    const value = e.target.value;
    const tagsArray = value.split(",").map(tag => tag.trim()).filter(tag => tag);
    setTags(tagsArray);
  };

  return (
    <form onSubmit={handleSubmit} className="max-w-md mx-auto p-4 border rounded">
      <div className="mb-4">
        <label className="block mb-1">Название миссии</label>
        <input
          type="text"
          value={name}
          onChange={e => setName(e.target.value)}
          className="w-full border px-2 py-1"
          required
        />
      </div>

      <div className="mb-4">
        <label className="block mb-1">Сложность</label>
        <input
          type="number"
          value={difficulty}
          min={1}
          max={5}
          onChange={e => setDifficulty(Number(e.target.value))}
          className="w-full border px-2 py-1"
          required
        />
      </div>

      <div className="mb-4">
        <label className="block mb-1">Теги (через запятую)</label>
        <input
          type="text"
          value={tagsValue}
          onChange={handleTagsChange}
          className="w-full border px-2 py-1"
        />
      </div>

      <div className="mb-4">
        <label className="block mb-1">Файл миссии</label>
        <input type="file" onChange={handleFileChange} accept=".zip" required />
      </div>

      <button
        type="submit"
        disabled={status === "loading"}
        className="bg-blue-500 text-white px-4 py-2 rounded disabled:opacity-50"
      >
        {status === "loading" ? "Загрузка..." : "Загрузить миссию"}
      </button>

      {status === "failed" && error && <p className="text-red-500 mt-2">{error}</p>}
    </form>
  );
};

export default UploadMissionForm;
