"use client";

import { useEffect, useMemo, useState } from "react";
import {
  LuPlus,
  LuSearch,
  LuPencil,
  LuTrash2,
  LuX,
  LuPackage,
  LuChevronDown,
} from "react-icons/lu";

const API_URL = "http://localhost:5000";

type Category = {
  id: number;
  name: string;
  slug: string;
};

type Subcategory = {
  id: number;
  category_id: number;
  name: string;
  slug: string;
};

type Product = {
  id: number;
  category_id: number;
  subcategory_id: number | null;
  name: string;
  description: string | null;
  short_description: string | null;
  slug: string;
  sku: string | null;
  brand: string | null;
  manufacturer: string | null;
  barcode: string | null;
  buying_price: number;
  regular_price: number;
  sale_price: number | null;
  stock_quantity: number;
  prescription_required: number;
  image: string | null;
  status: "active" | "inactive";
  category_name: string | null;
  subcategory_name: string | null;
  is_top_rated: number;
  is_top_selling: number;
  is_trending: number;
};

type FormData = {
  category_id: string;
  subcategory_id: string;
  name: string;
  description: string;
  short_description: string;
  slug: string;
  sku: string;
  brand: string;
  manufacturer: string;
  barcode: string;
  buying_price: string;
  regular_price: string;
  sale_price: string;
  stock_quantity: string;
  prescription_required: boolean;
  image: string;
  status: "active" | "inactive";
  is_top_rated: boolean;
  is_top_selling: boolean;
  is_trending: boolean;
};

const emptyForm: FormData = {
  category_id: "",
  subcategory_id: "",
  name: "",
  description: "",
  short_description: "",
  slug: "",
  sku: "",
  brand: "",
  manufacturer: "",
  barcode: "",
  buying_price: "",
  regular_price: "",
  sale_price: "",
  stock_quantity: "0",
  prescription_required: false,
  image: "",
  status: "active",
  is_top_rated: false,
  is_top_selling: false,
  is_trending: false,
};

function createSlug(value: string) {
  return value
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

export default function ProductsPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [subcategories, setSubcategories] = useState<Subcategory[]>([]);

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const [search, setSearch] = useState("");
  const [showModal, setShowModal] = useState(false);

  const [editingId, setEditingId] = useState<number | null>(null);
  const [form, setForm] = useState<FormData>(emptyForm);

  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  async function fetchData() {
    try {
      setLoading(true);

      const [productsResponse, categoriesResponse, subcategoriesResponse] =
        await Promise.all([
          fetch(`${API_URL}/api/products`),
          fetch(`${API_URL}/api/categories`),
          fetch(`${API_URL}/api/subcategories`),
        ]);

      if (!productsResponse.ok) {
        throw new Error("Failed to fetch products");
      }

      if (!categoriesResponse.ok) {
        throw new Error("Failed to fetch categories");
      }

      if (!subcategoriesResponse.ok) {
        throw new Error("Failed to fetch subcategories");
      }

      const productsData = await productsResponse.json();
      const categoriesData = await categoriesResponse.json();
      const subcategoriesData = await subcategoriesResponse.json();

      setProducts(productsData);
      setCategories(categoriesData);
      setSubcategories(subcategoriesData);
    } catch (err) {
      console.error(err);
      setError("Failed to load product data.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchData();
  }, []);

  const filteredSubcategories = useMemo(() => {
    if (!form.category_id) {
      return [];
    }

    return subcategories.filter(
      (subcategory) =>
        subcategory.category_id === Number(form.category_id)
    );
  }, [form.category_id, subcategories]);

  const filteredProducts = useMemo(() => {
    const searchValue = search.toLowerCase().trim();

    if (!searchValue) {
      return products;
    }

    return products.filter((product) => {
      return (
        product.name.toLowerCase().includes(searchValue) ||
        product.slug.toLowerCase().includes(searchValue) ||
        (product.sku || "").toLowerCase().includes(searchValue) ||
        (product.brand || "").toLowerCase().includes(searchValue) ||
        (product.category_name || "").toLowerCase().includes(searchValue)
      );
    });
  }, [products, search]);

  function updateField<K extends keyof FormData>(
    field: K,
    value: FormData[K]
  ) {
    setForm((previous) => ({
      ...previous,
      [field]: value,
    }));
  }

  function handleNameChange(value: string) {
    setForm((previous) => ({
      ...previous,
      name: value,
      ...(editingId === null && {
        slug: createSlug(value),
      }),
    }));
  }

  function handleCategoryChange(value: string) {
    setForm((previous) => ({
      ...previous,
      category_id: value,
      subcategory_id: "",
    }));
  }

  function openAddModal() {
    setEditingId(null);
    setForm(emptyForm);
    setError("");
    setSuccess("");
    setShowModal(true);
  }

  async function openEditModal(product: Product) {
    setEditingId(product.id);
    setError("");
    setSuccess("");

    try {
      const response = await fetch(
        `${API_URL}/api/products/${product.id}`
      );

      if (!response.ok) {
        throw new Error("Failed to fetch product");
      }

      const data: Product = await response.json();

      setForm({
        category_id: String(data.category_id),
        subcategory_id: data.subcategory_id
          ? String(data.subcategory_id)
          : "",
        name: data.name || "",
        description: data.description || "",
        short_description: data.short_description || "",
        slug: data.slug || "",
        sku: data.sku || "",
        brand: data.brand || "",
        manufacturer: data.manufacturer || "",
        barcode: data.barcode || "",
        buying_price:
          data.buying_price !== null &&
          data.buying_price !== undefined
            ? String(data.buying_price)
            : "",
        regular_price:
          data.regular_price !== null &&
          data.regular_price !== undefined
            ? String(data.regular_price)
            : "",
        sale_price:
          data.sale_price !== null &&
          data.sale_price !== undefined
            ? String(data.sale_price)
            : "",
        stock_quantity:
          data.stock_quantity !== null &&
          data.stock_quantity !== undefined
            ? String(data.stock_quantity)
            : "0",
        prescription_required: Boolean(data.prescription_required),
        image: data.image || "",
        status: data.status || "active",

        is_top_rated: Boolean(data.is_top_rated),
        is_top_selling: Boolean(data.is_top_selling),
        is_trending: Boolean(data.is_trending),
      });

      setShowModal(true);
    } catch (err) {
      console.error(err);
      setError("Failed to load product details.");
    }
  }

  function closeModal() {
    if (saving) return;

    setShowModal(false);
    setEditingId(null);
    setForm(emptyForm);
    setError("");
  }

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();

    setError("");
    setSuccess("");

    if (!form.category_id) {
      setError("Please select a category.");
      return;
    }

    if (!form.name.trim()) {
      setError("Product name is required.");
      return;
    }

    if (!form.slug.trim()) {
      setError("Product slug is required.");
      return;
    }

    const regularPrice = Number(form.regular_price || 0);

    const salePrice =
      form.sale_price.trim() === ""
        ? null
        : Number(form.sale_price);

    if (regularPrice < 0) {
      setError("Regular price cannot be negative.");
      return;
    }

    if (salePrice !== null && salePrice < 0) {
      setError("Sale price cannot be negative.");
      return;
    }

    if (salePrice !== null && salePrice > regularPrice) {
      setError("Sale price cannot be higher than regular price.");
      return;
    }

    const payload = {
      category_id: Number(form.category_id),

      subcategory_id: form.subcategory_id
        ? Number(form.subcategory_id)
        : null,

      name: form.name.trim(),

      description:
        form.description.trim() || null,

      short_description:
        form.short_description.trim() || null,

      slug: form.slug.trim(),

      sku:
        form.sku.trim() || null,

      brand:
        form.brand.trim() || null,

      manufacturer:
        form.manufacturer.trim() || null,

      barcode:
        form.barcode.trim() || null,

      buying_price:
        Number(form.buying_price || 0),

      regular_price:
        regularPrice,

      sale_price:
        salePrice,

      stock_quantity:
        Number(form.stock_quantity || 0),

      prescription_required:
        form.prescription_required,

      image:
        form.image.trim() || null,

      status:
        form.status,

      is_top_rated:
        form.is_top_rated,

      is_top_selling:
        form.is_top_selling,

      is_trending:
        form.is_trending,
    };

    try {
      setSaving(true);

      const url = editingId
        ? `${API_URL}/api/products/${editingId}`
        : `${API_URL}/api/products`;

      const method = editingId ? "PUT" : "POST";
console.log("UPDATE URL:", url);
console.log("UPDATE PAYLOAD:", payload);
      const response = await fetch(url, {
        
        method,
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      });

      const data = await response.json();
      
      if (!response.ok) {
        throw new Error(
          data.message || "Failed to save product"
        );
      }

      setSuccess(
        editingId
          ? "Product updated successfully."
          : "Product created successfully."
      );

      await fetchData();

      setTimeout(() => {
        setShowModal(false);
        setEditingId(null);
        setForm(emptyForm);
        setSuccess("");
      }, 700);
    } catch (err) {
      console.error(err);

      setError(
        err instanceof Error
          ? err.message
          : "Failed to save product."
      );
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete(id: number) {
    const confirmed = window.confirm(
      "Are you sure you want to delete this product?"
    );

    if (!confirmed) return;

    try {
      const response = await fetch(
        `${API_URL}/api/products/${id}`,
        {
          method: "DELETE",
        }
      );

      const data = await response.json();

      if (!response.ok) {
        throw new Error(
          data.message || "Failed to delete product"
        );
      }

      setSuccess("Product deleted successfully.");

      await fetchData();

      setTimeout(() => {
        setSuccess("");
      }, 2000);
    } catch (err) {
      console.error(err);

      setError(
        err instanceof Error
          ? err.message
          : "Failed to delete product."
      );
    }
  }

  const regularPrice = Number(form.regular_price || 0);

  const salePrice =
    form.sale_price.trim() === ""
      ? null
      : Number(form.sale_price);

  const discountPercentage =
    salePrice !== null &&
    regularPrice > 0 &&
    salePrice < regularPrice
      ? Math.round(
          ((regularPrice - salePrice) / regularPrice) * 100
        )
      : 0;

  function formatPrice(value: number | string | null) {
    if (
      value === null ||
      value === undefined ||
      value === ""
    ) {
      return "—";
    }

    return `AED ${Number(value).toFixed(2)}`;
  }

  return (
    <div className="p-6">
      {/* Page Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-6">
        <div>
          <h1 className="text-2xl font-semibold text-gray-800">
            Products
          </h1>

          <p className="text-sm text-gray-500 mt-1">
            Manage your pharmacy products, pricing and inventory.
          </p>
        </div>

        <button
          type="button"
          onClick={openAddModal}
          className="inline-flex items-center justify-center gap-2 rounded-lg bg-[#B570D4] px-5 py-3 text-sm font-medium text-white hover:opacity-90 transition"
        >
          <LuPlus size={18} />
          Add Product
        </button>
      </div>

      {/* Messages */}
      {error && !showModal && (
        <div className="mb-5 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-600">
          {error}
        </div>
      )}

      {success && !showModal && (
        <div className="mb-5 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-600">
          {success}
        </div>
      )}

      {/* Search */}
      <div className="bg-white border border-gray-100 rounded-xl shadow-sm p-4 mb-5">
        <div className="relative max-w-md">
          <LuSearch
            size={18}
            className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"
          />

          <input
            type="text"
            value={search}
            onChange={(event) =>
              setSearch(event.target.value)
            }
            placeholder="Search products..."
            className="w-full rounded-lg border border-gray-200 bg-white py-2.5 pl-10 pr-4 text-sm outline-none focus:border-[#B570D4]"
          />
        </div>
      </div>

      {/* Products Table */}
      <div className="bg-white border border-gray-100 rounded-xl shadow-sm overflow-hidden">
        {loading ? (
          <div className="flex justify-center py-16">
            <p className="text-sm text-gray-400">
              Loading products...
            </p>
          </div>
        ) : filteredProducts.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16">
            <div className="flex h-14 w-14 items-center justify-center rounded-full bg-gray-50">
              <LuPackage
                size={26}
                className="text-gray-400"
              />
            </div>

            <h3 className="mt-4 text-base font-medium text-gray-700">
              No products found
            </h3>

            <p className="mt-1 text-sm text-gray-400">
              {search
                ? "Try changing your search."
                : "Add your first pharmacy product."}
            </p>

            {!search && (
              <button
                type="button"
                onClick={openAddModal}
                className="mt-5 inline-flex items-center gap-2 rounded-lg bg-[#B570D4] px-4 py-2.5 text-sm font-medium text-white"
              >
                <LuPlus size={17} />
                Add Product
              </button>
            )}
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[1100px]">
              <thead>
                <tr className="border-b border-gray-100 bg-gray-50/70">
                  <th className="px-5 py-4 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
                    Product
                  </th>

                  <th className="px-5 py-4 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
                    Category
                  </th>

                  <th className="px-5 py-4 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
                    SKU
                  </th>

                  <th className="px-5 py-4 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
                    Price
                  </th>

                  <th className="px-5 py-4 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
                    Stock
                  </th>

                  <th className="px-5 py-4 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
                    Status
                  </th>

                  <th className="px-5 py-4 text-right text-xs font-semibold uppercase tracking-wide text-gray-500">
                    Actions
                  </th>
                </tr>
              </thead>

              <tbody>
                {filteredProducts.map((product) => {
                  const hasSale =
                    product.sale_price !== null &&
                    Number(product.sale_price) <
                      Number(product.regular_price);

                  return (
                    <tr
                      key={product.id}
                      className="border-b border-gray-100 last:border-0 hover:bg-gray-50/50"
                    >
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-3">
                          <div className="h-12 w-12 shrink-0 overflow-hidden rounded-lg bg-gray-100">
                            {product.image ? (
                              <img
                                src={product.image}
                                alt={product.name}
                                className="h-full w-full object-cover"
                              />
                            ) : (
                              <div className="flex h-full w-full items-center justify-center">
                                <LuPackage
                                  size={21}
                                  className="text-gray-400"
                                />
                              </div>
                            )}
                          </div>

                          <div className="min-w-0">
                            <p className="font-medium text-gray-700 truncate max-w-[260px]">
                              {product.name}
                            </p>

                            {product.brand && (
                              <p className="text-xs text-gray-400 mt-1">
                                {product.brand}
                              </p>
                            )}
                          </div>
                        </div>
                      </td>

                      <td className="px-5 py-4">
                        <p className="text-sm text-gray-600">
                          {product.category_name || "—"}
                        </p>

                        {product.subcategory_name && (
                          <p className="text-xs text-gray-400 mt-1">
                            {product.subcategory_name}
                          </p>
                        )}
                      </td>

                      <td className="px-5 py-4">
                        <span className="text-sm text-gray-500">
                          {product.sku || "—"}
                        </span>
                      </td>

                      <td className="px-5 py-4">
                        {hasSale ? (
                          <div>
                            <p className="text-sm font-semibold text-gray-700">
                              {formatPrice(product.sale_price)}
                            </p>

                            <p className="text-xs text-gray-400 line-through">
                              {formatPrice(product.regular_price)}
                            </p>
                          </div>
                        ) : (
                          <p className="text-sm font-semibold text-gray-700">
                            {formatPrice(product.regular_price)}
                          </p>
                        )}
                      </td>

                      <td className="px-5 py-4">
                        <span
                          className={`text-sm font-medium ${
                            Number(product.stock_quantity) <= 0
                              ? "text-red-500"
                              : Number(product.stock_quantity) <= 10
                              ? "text-orange-500"
                              : "text-green-600"
                          }`}
                        >
                          {product.stock_quantity}
                        </span>
                      </td>

                      <td className="px-5 py-4">
                        <span
                          className={`inline-flex rounded-full px-2.5 py-1 text-xs font-medium ${
                            product.status === "active"
                              ? "bg-green-50 text-green-600"
                              : "bg-gray-100 text-gray-500"
                          }`}
                        >
                          {product.status === "active"
                            ? "Active"
                            : "Inactive"}
                        </span>
                      </td>

                      <td className="px-5 py-4">
                        <div className="flex justify-end gap-2">
                          <button
                            type="button"
                            onClick={() =>
                              openEditModal(product)
                            }
                            className="flex h-9 w-9 items-center justify-center rounded-lg border border-gray-200 text-gray-500 hover:border-[#B570D4] hover:text-[#B570D4] transition"
                            title="Edit"
                          >
                            <LuPencil size={16} />
                          </button>

                          <button
                            type="button"
                            onClick={() =>
                              handleDelete(product.id)
                            }
                            className="flex h-9 w-9 items-center justify-center rounded-lg border border-gray-200 text-gray-500 hover:border-red-300 hover:text-red-500 transition"
                            title="Delete"
                          >
                            <LuTrash2 size={16} />
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Add/Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
          <div className="flex max-h-[95vh] w-full max-w-5xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl">

            {/* Modal Header */}
            <div className="flex items-center justify-between border-b border-gray-100 px-6 py-5">
              <div>
                <h2 className="text-xl font-semibold text-gray-800">
                  {editingId
                    ? "Edit Product"
                    : "Add Product"}
                </h2>

                <p className="mt-1 text-sm text-gray-400">
                  {editingId
                    ? "Update product information."
                    : "Add a new product to your pharmacy."}
                </p>
              </div>

              <button
                type="button"
                onClick={closeModal}
                className="flex h-9 w-9 items-center justify-center rounded-lg text-gray-400 hover:bg-gray-100 hover:text-gray-600"
              >
                <LuX size={20} />
              </button>
            </div>

            {/* Modal Body */}
            <form
              onSubmit={handleSubmit}
              className="overflow-y-auto px-6 py-6"
            >
              {error && (
                <div className="mb-5 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-600">
                  {error}
                </div>
              )}

              {success && (
                <div className="mb-5 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-600">
                  {success}
                </div>
              )}

              <div className="grid grid-cols-1 gap-5 lg:grid-cols-2">

                {/* Product Name */}
                <div className="lg:col-span-2">
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Product Name{" "}
                    <span className="text-red-500">*</span>
                  </label>

                  <input
                    type="text"
                    value={form.name}
                    onChange={(event) =>
                      handleNameChange(event.target.value)
                    }
                    placeholder="e.g. Panadol Advance 500mg"
                    className="w-full rounded-lg border border-gray-200 px-4 py-3 text-sm outline-none focus:border-[#B570D4]"
                    required
                  />
                </div>

                {/* Category */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Category{" "}
                    <span className="text-red-500">*</span>
                  </label>

                  <div className="relative">
                    <select
                      value={form.category_id}
                      onChange={(event) =>
                        handleCategoryChange(
                          event.target.value
                        )
                      }
                      className="w-full appearance-none rounded-lg border border-gray-200 bg-white px-4 py-3 pr-10 text-sm outline-none focus:border-[#B570D4]"
                      required
                    >
                      <option value="">
                        Select category
                      </option>

                      {categories.map((category) => (
                        <option
                          key={category.id}
                          value={category.id}
                        >
                          {category.name}
                        </option>
                      ))}
                    </select>

                    <LuChevronDown
                      size={17}
                      className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"
                    />
                  </div>
                </div>

                {/* Subcategory */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Subcategory
                  </label>

                  <div className="relative">
                    <select
                      value={form.subcategory_id}
                      onChange={(event) =>
                        updateField(
                          "subcategory_id",
                          event.target.value
                        )
                      }
                      disabled={!form.category_id}
                      className="w-full appearance-none rounded-lg border border-gray-200 bg-white px-4 py-3 pr-10 text-sm outline-none focus:border-[#B570D4] disabled:bg-gray-50 disabled:text-gray-400"
                    >
                      <option value="">
                        {form.category_id
                          ? "Select subcategory"
                          : "Select category first"}
                      </option>

                      {filteredSubcategories.map(
                        (subcategory) => (
                          <option
                            key={subcategory.id}
                            value={subcategory.id}
                          >
                            {subcategory.name}
                          </option>
                        )
                      )}
                    </select>

                    <LuChevronDown
                      size={17}
                      className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"
                    />
                  </div>
                </div>

                {/* Slug */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Slug{" "}
                    <span className="text-red-500">*</span>
                  </label>

                  <input
                    type="text"
                    value={form.slug}
                    onChange={(event) =>
                      updateField(
                        "slug",
                        event.target.value
                      )
                    }
                    placeholder="panadol-advance-500mg"
                    className="w-full rounded-lg border border-gray-200 px-4 py-3 text-sm outline-none focus:border-[#B570D4]"
                    required
                  />
                </div>

                {/* SKU */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    SKU
                  </label>

                  <input
                    type="text"
                    value={form.sku}
                    onChange={(event) =>
                      updateField(
                        "sku",
                        event.target.value
                      )
                    }
                    placeholder="PAN-500-001"
                    className="w-full rounded-lg border border-gray-200 px-4 py-3 text-sm outline-none focus:border-[#B570D4]"
                  />
                </div>

                {/* Brand */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Brand
                  </label>

                  <input
                    type="text"
                    value={form.brand}
                    onChange={(event) =>
                      updateField(
                        "brand",
                        event.target.value
                      )
                    }
                    placeholder="Panadol"
                    className="w-full rounded-lg border border-gray-200 px-4 py-3 text-sm outline-none focus:border-[#B570D4]"
                  />
                </div>

                {/* Manufacturer */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Manufacturer
                  </label>

                  <input
                    type="text"
                    value={form.manufacturer}
                    onChange={(event) =>
                      updateField(
                        "manufacturer",
                        event.target.value
                      )
                    }
                    placeholder="Manufacturer name"
                    className="w-full rounded-lg border border-gray-200 px-4 py-3 text-sm outline-none focus:border-[#B570D4]"
                  />
                </div>

                {/* Barcode */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Barcode
                  </label>

                  <input
                    type="text"
                    value={form.barcode}
                    onChange={(event) =>
                      updateField(
                        "barcode",
                        event.target.value
                      )
                    }
                    placeholder="6291234567890"
                    className="w-full rounded-lg border border-gray-200 px-4 py-3 text-sm outline-none focus:border-[#B570D4]"
                  />
                </div>

                {/* Stock */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Stock Quantity
                  </label>

                  <input
                    type="number"
                    min="0"
                    value={form.stock_quantity}
                    onChange={(event) =>
                      updateField(
                        "stock_quantity",
                        event.target.value
                      )
                    }
                    className="w-full rounded-lg border border-gray-200 px-4 py-3 text-sm outline-none focus:border-[#B570D4]"
                  />
                </div>

                {/* Buying Price */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Buying Price

                    <span className="ml-2 text-xs font-normal text-gray-400">
                      Admin only
                    </span>
                  </label>

                  <div className="relative">
                    <span className="absolute left-4 top-1/2 -translate-y-1/2 text-sm text-gray-400">
                      AED
                    </span>

                    <input
                      type="number"
                      min="0"
                      step="0.01"
                      value={form.buying_price}
                      onChange={(event) =>
                        updateField(
                          "buying_price",
                          event.target.value
                        )
                      }
                      placeholder="0.00"
                      className="w-full rounded-lg border border-gray-200 py-3 pl-14 pr-4 text-sm outline-none focus:border-[#B570D4]"
                    />
                  </div>
                </div>

                {/* Regular Price */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Regular Price
                  </label>

                  <div className="relative">
                    <span className="absolute left-4 top-1/2 -translate-y-1/2 text-sm text-gray-400">
                      AED
                    </span>

                    <input
                      type="number"
                      min="0"
                      step="0.01"
                      value={form.regular_price}
                      onChange={(event) =>
                        updateField(
                          "regular_price",
                          event.target.value
                        )
                      }
                      placeholder="0.00"
                      className="w-full rounded-lg border border-gray-200 py-3 pl-14 pr-4 text-sm outline-none focus:border-[#B570D4]"
                    />
                  </div>
                </div>

                {/* Sale Price */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Sale Price

                    <span className="ml-2 text-xs font-normal text-gray-400">
                      Optional
                    </span>
                  </label>

                  <div className="relative">
                    <span className="absolute left-4 top-1/2 -translate-y-1/2 text-sm text-gray-400">
                      AED
                    </span>

                    <input
                      type="number"
                      min="0"
                      step="0.01"
                      value={form.sale_price}
                      onChange={(event) =>
                        updateField(
                          "sale_price",
                          event.target.value
                        )
                      }
                      placeholder="Leave empty for no discount"
                      className="w-full rounded-lg border border-gray-200 py-3 pl-14 pr-4 text-sm outline-none focus:border-[#B570D4]"
                    />
                  </div>

                  {discountPercentage > 0 && (
                    <p className="mt-2 text-sm font-medium text-green-600">
                      {discountPercentage}% OFF
                    </p>
                  )}
                </div>

                {/* Image */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Product Image
                  </label>

                  <input
                    type="text"
                    value={form.image}
                    onChange={(event) =>
                      updateField(
                        "image",
                        event.target.value
                      )
                    }
                    placeholder="/images/products/panadol.jpg"
                    className="w-full rounded-lg border border-gray-200 px-4 py-3 text-sm outline-none focus:border-[#B570D4]"
                  />

                  <p className="mt-1.5 text-xs text-gray-400">
                    Enter the image URL or image path.
                  </p>
                </div>

                {/* Status */}
                <div>
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Status
                  </label>

                  <div className="relative">
                    <select
                      value={form.status}
                      onChange={(event) =>
                        updateField(
                          "status",
                          event.target.value as
                            | "active"
                            | "inactive"
                        )
                      }
                      className="w-full appearance-none rounded-lg border border-gray-200 bg-white px-4 py-3 pr-10 text-sm outline-none focus:border-[#B570D4]"
                    >
                      <option value="active">
                        Active
                      </option>

                      <option value="inactive">
                        Inactive
                      </option>
                    </select>

                    <LuChevronDown
                      size={17}
                      className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"
                    />
                  </div>
                </div>

                {/* Homepage Sections */}
                <div className="lg:col-span-2">
                  <label className="mb-3 block text-sm font-medium text-gray-700">
                    Homepage Sections
                  </label>

                  <div className="grid grid-cols-1 gap-3 md:grid-cols-3">

                    {/* Top Rated */}
                    <label className="flex cursor-pointer items-center gap-3 rounded-lg border border-gray-200 px-4 py-3 hover:bg-gray-50">
                      <input
                        type="checkbox"
                        checked={form.is_top_rated}
                        onChange={(event) =>
                          updateField(
                            "is_top_rated",
                            event.target.checked
                          )
                        }
                        className="h-4 w-4 accent-[#B570D4]"
                      />

                      <span className="text-sm font-medium text-gray-700">
                        Top Rated
                      </span>
                    </label>

                    {/* Top Selling */}
                    <label className="flex cursor-pointer items-center gap-3 rounded-lg border border-gray-200 px-4 py-3 hover:bg-gray-50">
                      <input
                        type="checkbox"
                        checked={form.is_top_selling}
                        onChange={(event) =>
                          updateField(
                            "is_top_selling",
                            event.target.checked
                          )
                        }
                        className="h-4 w-4 accent-[#B570D4]"
                      />

                      <span className="text-sm font-medium text-gray-700">
                        Top Selling
                      </span>
                    </label>

                    {/* Trending */}
                    <label className="flex cursor-pointer items-center gap-3 rounded-lg border border-gray-200 px-4 py-3 hover:bg-gray-50">
                      <input
                        type="checkbox"
                        checked={form.is_trending}
                        onChange={(event) =>
                          updateField(
                            "is_trending",
                            event.target.checked
                          )
                        }
                        className="h-4 w-4 accent-[#B570D4]"
                      />

                      <span className="text-sm font-medium text-gray-700">
                        Trending
                      </span>
                    </label>

                  </div>
                </div>

                {/* Prescription */}
                <div className="lg:col-span-2">
                  <label className="flex cursor-pointer items-center gap-3 rounded-lg border border-gray-200 px-4 py-3">
                    <input
                      type="checkbox"
                      checked={form.prescription_required}
                      onChange={(event) =>
                        updateField(
                          "prescription_required",
                          event.target.checked
                        )
                      }
                      className="h-4 w-4 accent-[#B570D4]"
                    />

                    <span>
                      <span className="block text-sm font-medium text-gray-700">
                        Prescription Required
                      </span>

                      <span className="block text-xs text-gray-400 mt-0.5">
                        Customers will need a prescription for this
                        product.
                      </span>
                    </span>
                  </label>
                </div>

                {/* Short Description */}
                <div className="lg:col-span-2">
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Short Description
                  </label>

                  <input
                    type="text"
                    value={form.short_description}
                    onChange={(event) =>
                      updateField(
                        "short_description",
                        event.target.value
                      )
                    }
                    placeholder="A short summary of the product"
                    className="w-full rounded-lg border border-gray-200 px-4 py-3 text-sm outline-none focus:border-[#B570D4]"
                  />
                </div>

                {/* Description */}
                <div className="lg:col-span-2">
                  <label className="mb-2 block text-sm font-medium text-gray-700">
                    Description
                  </label>

                  <textarea
                    value={form.description}
                    onChange={(event) =>
                      updateField(
                        "description",
                        event.target.value
                      )
                    }
                    rows={5}
                    placeholder="Enter the full product description..."
                    className="w-full resize-none rounded-lg border border-gray-200 px-4 py-3 text-sm outline-none focus:border-[#B570D4]"
                  />
                </div>

              </div>

              {/* Footer */}
              <div className="mt-7 flex justify-end gap-3 border-t border-gray-100 pt-5">
                <button
                  type="button"
                  onClick={closeModal}
                  disabled={saving}
                  className="rounded-lg border border-gray-200 px-5 py-2.5 text-sm font-medium text-gray-600 hover:bg-gray-50 disabled:opacity-50"
                >
                  Cancel
                </button>

                <button
                  type="submit"
                  disabled={saving}
                  className="rounded-lg bg-[#B570D4] px-6 py-2.5 text-sm font-medium text-white hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60"
                >
                  {saving
                    ? "Saving..."
                    : editingId
                    ? "Update Product"
                    : "Create Product"}
                </button>
              </div>

            </form>
          </div>
        </div>
      )}
    </div>
  );
}