import React, { useState } from "react";
import { BadgePlus } from "lucide-react";
import axios from "axios";
import { API_BASE_URL } from "../config";
import { useAuth } from "../AuthContext";

function FormNewObject({ isAdmin }) {
  const { user } = useAuth();

  const [description, setDescription] = useState("");
  const [type, setType] = useState("");
  const [location, setLocalisation] = useState("");
  const [proprio_id,setProprio_id] = useState(user?.id);
  const [batterieType,setBatterieType] = useState("");
  const [status, setStatus] = useState("active");
  const [nom, setNom] = useState("");
  const [Response, setResponse] = useState(null);
  const [isActive, setActive] = useState(true);
  const [verif, setVerif] = useState(false);
  const [enregistre, setEnregistre] = useState(false);
  const [messRequete, setMessRequete] = useState("");
  function handleSubmit(event) {
    event.preventDefault();

    if (verif) {
      console.log("Envoi requete");
      axios
        .post(`${API_BASE_URL}/addObject`, {
          nom,
          description,
          type,
          location,
          status,
          batterieType,
          proprio_id
        })
        .then((response) => {
          setMessRequete("Votre objet à bien été enregistré !");
          setEnregistre(true);
          console.log("Ajout de l'objet réussit :", response.data);
        })
        .catch((error) => {
          setMessRequete("Il y a eu une erreur dans l'ajout de votre objet !");
          console.error("Erreur lors de l'ajout de l'objet :", error);
        });
      setVerif(false);
      resetForm();
    } else {
      setVerif(true);
    }
  }
  function resetForm() {
    setNom("");
    setStatus("active");
    setDescription("");
    setType("");
    setLocalisation("");
    setBatterieType("");
    if(isAdmin)set_id("");
    setActive(true);
  }
  function handleCancel() {
    if (verif) {
      setVerif(false);
    } else {
      resetForm();
    }
  }
  function handleStatusChange() {
    setActive((prevIsActive) => {
      const newIsActive = !prevIsActive;
      setStatus(newIsActive ? "active" : "inactive");
      return newIsActive;
    });
  }

  return (
    <form onSubmit={handleSubmit} className="bg-white p-6 rounded-xl min-w-5xl">
      <div className="flex align-items gap-9">
        {isAdmin ? (
          <h2 className="text-2xl font-semibold mb-3">
            Ajouter un nouvel objet
          </h2>
        ) : (
          <>
            <div className="w-12 h-12 bg-indigo-100 rounded-lg flex items-center justify-center mb-4">
              <BadgePlus className="text-indigo-600" size={24} />
            </div>
            <h1 className="text-black text-2xl font-bold mb-1">
              {!verif
                ? "Entrez les données de votre nouvel objet"
                : "Êtes-vous sûr de ces données ?"}
            </h1>
          </>
        )}
      </div>
      <div className="mb-5">
        <label
          htmlFor="nom"
          className="block mb-2 text-sm font-medium text-gray-900"
        >
          Nom :
        </label>
        <input
          id="nom"
          className="text-gray-600 border rounded-lg p-2 w-full"
          type="text"
          value={nom}
          onChange={(e) => setNom(e.target.value)}
          required
          disabled={verif}
        />
      </div>
      <div className="mb-5">
        <label
          htmlFor="description"
          className="block mb-2 text-sm font-medium text-gray-900"
        >
          Description :
        </label>
        <input
          id="description"
          className="text-gray-600 border rounded-lg p-2 w-full"
          type="text"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          required
          disabled={verif}
        />
      </div>

      <div className="mb-5">
        <label
          htmlFor="type"
          className="block mb-2 text-sm font-medium text-gray-900"
        >
          Type :
        </label>
        <input
          id="type"
          className="text-gray-600 border rounded-lg p-2 w-full"
          type="text"
          value={type}
          onChange={(e) => setType(e.target.value)}
          required
          disabled={verif}
        />
      </div>

      <div className="mb-5">
        <label
          htmlFor="location"
          className="block mb-2 text-sm font-medium text-gray-900"
        >
          Localisation :
        </label>
        <input
          id="location"
          className="text-gray-600 border rounded-lg p-2 w-full"
          type="text"
          value={location}
          onChange={(e) => setLocalisation(e.target.value)}
          required
          disabled={verif}
        />
      </div>
      <div className="mb-5">
        <label
          htmlFor="batterieType"
          className="block mb-2 text-sm font-medium text-gray-900"
        >
          Type de batterie :
        </label>
        <input
          id="batterieType"
          className="text-gray-600 border rounded-lg p-2 w-full"
          type="text"
          value={batterieType}
          onChange={(e) => setBatterieType(e.target.value)}
          required
          disabled={verif}
        />
      </div>
      <div className="mb-5">
        <label
          htmlFor="proprio_id"
          className="block mb-2 text-sm font-medium text-gray-900"
        >
          Propriétaire :
        </label>
        <input
          id="proprio_id"
          className="text-gray-600 border rounded-lg p-2 w-full"
          type="number"
          value={proprio_id}
          onChange={(e) => setProprio_id(e.target.value)}
          required
          disabled={verif||!isAdmin}
        />
      </div>

      <div className="mb-5">
        <label className="block mb-2 text-sm font-medium text-gray-900">
          Status :
        </label>
        <div className="inline-flex items-center gap-2">
          <label
            htmlFor="switch-component-on"
            className="text-slate-600 text-sm cursor-pointer"
          >
            Inactive
          </label>
          <div className="relative inline-block w-11 h-5">
            <input
              id="switch-component-on"
              type="checkbox"
              checked={isActive}
              onChange={handleStatusChange}
              className="peer appearance-none w-11 h-5 bg-slate-100 rounded-full checked:bg-slate-800 cursor-pointer transition-colors duration-300"
              disabled={verif}
            />
            <label
              htmlFor="switch-component-on"
              className="absolute top-0 left-0 w-5 h-5 bg-white rounded-full border border-slate-300 shadow-sm transition-transform duration-300 peer-checked:translate-x-6 peer-checked:border-slate-800 cursor-pointer"
            ></label>
          </div>
          <label
            htmlFor="switch-component-on"
            className="text-slate-600 text-sm cursor-pointer"
          >
            Active
          </label>
        </div>
      </div>

      <div className="flex flex-col mb-5 ">
        <button
          type={"submit"}
          className="text-blue-500 hover:cursor-pointer hover:underline mb-2"
        >
          {!verif ? "Confirmer les informations" : "Oui je suis sûr !"}
        </button>
        <button
          type="button"
          className="text-red-500 hover:cursor-pointer hover:underline"
          onClick={handleCancel}
        >
          {!verif ? "Supprimer les informations" : "Non je veux changer !"}
        </button>
      </div>
      <p className={enregistre ? "text-green-700" : "text-red-700"}>
        {messRequete}
      </p>
    </form>
  );
}

export default FormNewObject;
