"use client";

import { FormEvent, useEffect, useState } from "react";

type Category = {
id: string;
name: string;
};

type Product = {
id: string;
name: string;
description: string | null;
price: number;
image: string | null;
isAvailable: boolean;
isFeatured: boolean;
categoryId: string;
};

export function EditProductForm({
product,
categories,
onSuccess,
onCancel,
}: {
product: Product;
categories: Category[];
onSuccess: () => void;
onCancel: () => void;
}) {
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState("");
const [preview, setPreview] = useState<string | null>(
product.image
);

useEffect(() => {
return () => {
if (preview?.startsWith("blob:")) {
URL.revokeObjectURL(preview);
}
};
}, [preview]);

function handleImageChange(
event: React.ChangeEvent<HTMLInputElement>
) {
const file = event.target.files?.[0];

if (!file) {
  setPreview(product.image);
  return;
}

if (!file.type.startsWith("image/")) {
  setMessage(
    "Veuillez sélectionner une image valide."
  );
  event.target.value = "";
  return;
}

if (file.size > 5 * 1024 * 1024) {
  setMessage(
    "L'image ne doit pas dépasser 5 Mo."
  );
  event.target.value = "";
  return;
}

if (preview?.startsWith("blob:")) {
  URL.revokeObjectURL(preview);
}

setPreview(URL.createObjectURL(file));
setMessage("");

}

async function handleSubmit(
event: FormEvent<HTMLFormElement>
) {
event.preventDefault();

setLoading(true);
setMessage("");

const form = event.currentTarget;
const formData = new FormData(form);

try {
  const response = await fetch(
    `/api/products/${product.id}`,
    {
      method: "PUT",
      body: formData,
    }
  );

  const result = await response.json();

  if (!response.ok) {
    throw new Error(
      result.message ||
        "Impossible de modifier le produit."
    );
  }

  setMessage(
    "Produit modifié avec succès."
  );

  setTimeout(() => {
    onSuccess();
  }, 700);
} catch (error) {
  console.error(
    "Erreur modification produit :",
    error
  );

  setMessage(
    error instanceof Error
      ? error.message
      : "Une erreur est survenue."
  );

  setLoading(false);
}

}

return ( <form
   onSubmit={handleSubmit}
   className="space-y-5"
 >
{/* NOM */} <div>
<label
htmlFor={`edit-name-${product.id}`}
className="mb-2 block text-sm font-semibold text-gray-800"
>
Nom du produit </label>

    <input
      id={`edit-name-${product.id}`}
      name="name"
      type="text"
      defaultValue={product.name}
      required
      disabled={loading}
      className="w-full rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm outline-none transition focus:border-[#a68b5b] focus:ring-2 focus:ring-[#a68b5b]/10 disabled:opacity-50"
    />
  </div>

  {/* DESCRIPTION */}
  <div>
    <label
      htmlFor={`edit-description-${product.id}`}
      className="mb-2 block text-sm font-semibold text-gray-800"
    >
      Description
    </label>

    <textarea
      id={`edit-description-${product.id}`}
      name="description"
      defaultValue={
        product.description || ""
      }
      rows={4}
      disabled={loading}
      placeholder="Décrivez le produit..."
      className="w-full resize-none rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm outline-none transition focus:border-[#a68b5b] focus:ring-2 focus:ring-[#a68b5b]/10 disabled:opacity-50"
    />
  </div>

  {/* PRIX + CATÉGORIE */}
  <div className="grid gap-4 sm:grid-cols-2">
    <div>
      <label
        htmlFor={`edit-price-${product.id}`}
        className="mb-2 block text-sm font-semibold text-gray-800"
      >
        Prix (FCFA)
      </label>

      <input
        id={`edit-price-${product.id}`}
        name="price"
        type="number"
        min="0"
        step="1"
        defaultValue={product.price}
        required
        disabled={loading}
        className="w-full rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm outline-none transition focus:border-[#a68b5b] focus:ring-2 focus:ring-[#a68b5b]/10 disabled:opacity-50"
      />
    </div>

    <div>
      <label
        htmlFor={`edit-category-${product.id}`}
        className="mb-2 block text-sm font-semibold text-gray-800"
      >
        Catégorie
      </label>

      <select
        id={`edit-category-${product.id}`}
        name="categoryId"
        defaultValue={product.categoryId}
        required
        disabled={loading}
        className="w-full rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm outline-none transition focus:border-[#a68b5b] focus:ring-2 focus:ring-[#a68b5b]/10 disabled:opacity-50"
      >
        <option value="">
          Sélectionner une catégorie
        </option>

        {categories.map((category) => (
          <option
            key={category.id}
            value={category.id}
          >
            {category.name}
          </option>
        ))}
      </select>
    </div>
  </div>

  {/* IMAGE */}
  <div>
    <label
      htmlFor={`edit-image-${product.id}`}
      className="mb-2 block text-sm font-semibold text-gray-800"
    >
      Nouvelle image
    </label>

    <input
      id={`edit-image-${product.id}`}
      name="image"
      type="file"
      accept="image/jpeg,image/jpg,image/png,image/webp"
      disabled={loading}
      onChange={handleImageChange}
      className="w-full rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm file:mr-4 file:rounded-lg file:border-0 file:bg-[#f5efe5] file:px-4 file:py-2 file:font-semibold file:text-[#8d754e] disabled:opacity-50"
    />

    <p className="mt-2 text-xs text-gray-500">
      Formats acceptés : JPG, JPEG, PNG et WEBP.
      Taille maximale : 5 Mo.
    </p>

    {preview && (
      <div className="mt-4 overflow-hidden rounded-xl border border-gray-200 bg-white">
        <img
          src={preview}
          alt={`Aperçu de ${product.name}`}
          className="h-48 w-full object-cover"
        />
      </div>
    )}
  </div>

  {/* OPTIONS */}
  <div className="grid gap-3 sm:grid-cols-2">
    <label className="flex cursor-pointer items-center gap-3 rounded-xl border border-gray-200 bg-white p-4 transition hover:bg-gray-50">
      <input
        type="checkbox"
        name="isAvailable"
        defaultChecked={product.isAvailable}
        disabled={loading}
        className="h-4 w-4 accent-[#a68b5b]"
      />

      <span>
        <span className="block text-sm font-semibold text-gray-800">
          Produit disponible
        </span>

        <span className="mt-1 block text-xs text-gray-500">
          Le produit peut être commandé.
        </span>
      </span>
    </label>

    <label className="flex cursor-pointer items-center gap-3 rounded-xl border border-gray-200 bg-white p-4 transition hover:bg-gray-50">
      <input
        type="checkbox"
        name="isFeatured"
        defaultChecked={product.isFeatured}
        disabled={loading}
        className="h-4 w-4 accent-[#a68b5b]"
      />

      <span>
        <span className="block text-sm font-semibold text-gray-800">
          Mettre à la une
        </span>

        <span className="mt-1 block text-xs text-gray-500">
          Afficher le produit comme produit vedette.
        </span>
      </span>
    </label>
  </div>

  {/* MESSAGE */}
  {message && (
    <div
      className={`rounded-xl border px-4 py-3 text-sm font-medium ${
        message.includes("succès")
          ? "border-green-200 bg-green-50 text-green-700"
          : "border-red-200 bg-red-50 text-red-700"
      }`}
    >
      {message}
    </div>
  )}

  {/* ACTIONS */}
  <div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
    <button
      type="button"
      onClick={onCancel}
      disabled={loading}
      className="rounded-xl border border-gray-200 bg-white px-5 py-3 text-sm font-semibold text-gray-700 transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
    >
      Annuler
    </button>

    <button
      type="submit"
      disabled={loading}
      className="rounded-xl bg-[#a68b5b] px-5 py-3 text-sm font-semibold text-white transition hover:bg-[#92774c] disabled:cursor-not-allowed disabled:opacity-50"
    >
      {loading
        ? "Enregistrement..."
        : "Enregistrer les modifications"}
    </button>
  </div>
</form>

);
}
