"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function NewProjectPage() {
  const [formData, setFormData] = useState({
    name: "",
    description: "",
    technologies: "",
    image: "",
    url: "",
    source: "",
    status: "En cours",
  });

  const router = useRouter();

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const res = await fetch("/api/projects", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formData),
    });

    if (res.ok) {
      router.push("/projects");
    } else {
      const error = await res.json();
      alert(`Erreur lors de la tentative d'ajout d'un projet : ${error.error}`);
    }
  };

  return (
    <div className="max-w-md mx-auto p-6">
      <h1 className="text-2xl font-bold mb-4">Créer un projet</h1>
      <form onSubmit={handleSubmit} className="space-y-4">
        {Object.keys(formData).map((key) => (
          <div key={key}>
            <label className="block font-medium capitalize">{key.replace("_", " ")}</label>
            {key === "description" ? (
              <textarea
                name={key}
                value={formData[key as keyof typeof formData]}
                onChange={handleChange}
                className="w-full p-2 border rounded"
              />
            ) : key === "status" ? (
              <select
                name={key}
                value={formData[key as keyof typeof formData]}
                onChange={handleChange}
                className="w-full p-2 border rounded"
              >
                <option value="En cours">En cours</option>
                <option value="En cours">Terminé</option>
                <option value="En cours">Futur Projet</option>
              </select>
            ) : (
              <input
                type={key === "url" || key === "image" || key === "source" ? "url" : "text"}
                name={key}
                value={formData[key as keyof typeof formData]}
                onChange={handleChange}
                className="w-full p-2 border rounded"
              />
            )}
          </div>
        ))}
        <button
          type="submit"
          className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
        >
          Sauvegarder
        </button>
      </form>
    </div>
  );
}