"use client";

import React, { useState, useTransition, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { Upload, X, Trash2, Plus, ArrowLeft } from "lucide-react";
import { saveProduct } from "@/app/admin/actions";

interface Category {
  id: string;
  name: string;
}

interface Series {
  id: string;
  name: string;
  categoryId: string;
}

interface ProductImage {
  id?: string;
  url: string;
  alt: string | null;
  order: number;
}

interface ProductData {
  id?: string;
  name: string;
  nameTr: string | null;
  nameEn: string | null;
  nameRu: string | null;
  slug: string;
  sku: string | null;
  categoryId: string;
  seriesId: string | null;
  widthCm: number | null;
  surface: string | null;
  burnerCount: number | null;
  description: string | null;
  descriptionTr: string | null;
  descriptionEn: string | null;
  descriptionRu: string | null;
  features: string[];
  featuresTr: string[];
  featuresEn: string[];
  featuresRu: string[];
  options: string[];
  optionsTr: string[];
  optionsEn: string[];
  optionsRu: string[];
  accessories: string[];
  accessoriesTr: string[];
  accessoriesEn: string[];
  accessoriesRu: string[];
  images: ProductImage[];
  status: string;
}

interface ProductFormProps {
  product?: ProductData;
  categories: Category[];
  series: Series[];
  permissions: {
    canPublish: boolean;
    canUpload: boolean;
  };
}

function slugify(text: string): string {
  const trMap: Record<string, string> = {
    ç: "c", Ç: "C", ğ: "g", Ğ: "G", ı: "i", I: "I", İ: "i", ö: "o", Ö: "O", ş: "s", Ş: "S", ü: "u", Ü: "U"
  };
  let slug = text;
  for (const key in trMap) {
    slug = slug.replace(new RegExp(key, "g"), trMap[key]);
  }
  return slug
    .toLowerCase()
    .replace(/[^-a-zA-Z0-9\s]/g, "")
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-")
    .trim();
}

function linesToList(value: string): string[] {
  return value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean);
}

export default function ProductForm({ product, categories, series, permissions }: ProductFormProps) {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [name, setName] = useState(product?.nameTr || product?.name || "");
  const [nameEn, setNameEn] = useState(product?.nameEn || "");
  const [nameRu, setNameRu] = useState(product?.nameRu || "");
  const [slug, setSlug] = useState(product?.slug || "");
  const [sku, setSku] = useState(product?.sku || "");
  const [categoryId, setCategoryId] = useState(product?.categoryId || categories[0]?.id || "");
  const [seriesId, setSeriesId] = useState(product?.seriesId || "");
  const [widthCm, setWidthCm] = useState<number | "">(product?.widthCm || "");
  const [surface, setSurface] = useState(product?.surface || "");
  const [burnerCount, setBurnerCount] = useState<number | "">(product?.burnerCount || "");
  const [description, setDescription] = useState(product?.descriptionTr || product?.description || "");
  const [descriptionEn, setDescriptionEn] = useState(product?.descriptionEn || "");
  const [descriptionRu, setDescriptionRu] = useState(product?.descriptionRu || "");

  const [features, setFeatures] = useState<string[]>(product?.featuresTr || product?.features || []);
  const [options, setOptions] = useState<string[]>(product?.optionsTr || product?.options || []);
  const [accessories, setAccessories] = useState<string[]>(product?.accessoriesTr || product?.accessories || []);
  const [featuresEn, setFeaturesEn] = useState((product?.featuresEn || []).join("\n"));
  const [featuresRu, setFeaturesRu] = useState((product?.featuresRu || []).join("\n"));
  const [optionsEn, setOptionsEn] = useState((product?.optionsEn || []).join("\n"));
  const [optionsRu, setOptionsRu] = useState((product?.optionsRu || []).join("\n"));
  const [accessoriesEn, setAccessoriesEn] = useState((product?.accessoriesEn || []).join("\n"));
  const [accessoriesRu, setAccessoriesRu] = useState((product?.accessoriesRu || []).join("\n"));

  const [images, setImages] = useState<ProductImage[]>(product?.images || []);
  const [status, setStatus] = useState(product?.status || "draft");

  const [featureInput, setFeatureInput] = useState("");
  const [optionInput, setOptionInput] = useState("");
  const [accessoryInput, setAccessoryInput] = useState("");

  const [isPending, startTransition] = useTransition();
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [isUploading, setIsUploading] = useState(false);

  const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value;
    setName(val);
    if (!product?.id) {
      setSlug(slugify(val));
    }
  };

  const filteredSeries = useMemo(() => {
    return series.filter((s) => s.categoryId === categoryId);
  }, [series, categoryId]);

  const handleCategoryChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const nextCat = e.target.value;
    setCategoryId(nextCat);
    setSeriesId("");
  };

  const addFeature = () => {
    if (featureInput.trim()) {
      setFeatures([...features, featureInput.trim()]);
      setFeatureInput("");
    }
  };

  const addOption = () => {
    if (optionInput.trim()) {
      setOptions([...options, optionInput.trim()]);
      setOptionInput("");
    }
  };

  const addAccessory = () => {
    if (accessoryInput.trim()) {
      setAccessories([...accessories, accessoryInput.trim()]);
      setAccessoryInput("");
    }
  };

  const removeListItem = (listName: "features" | "options" | "accessories", idx: number) => {
    if (listName === "features") setFeatures(features.filter((_, i) => i !== idx));
    if (listName === "options") setOptions(options.filter((_, i) => i !== idx));
    if (listName === "accessories") setAccessories(accessories.filter((_, i) => i !== idx));
  };

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setIsUploading(true);
    setErrorMsg(null);

    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
      formData.append("files", files[i]);
    }
    formData.append("module", "products");

    try {
      const res = await fetch("/api/admin/upload", {
        method: "POST",
        body: formData,
      });

      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.error || "Görsel yüklenirken bir hata oluştu.");
      }

      if (data.urls && data.urls.length > 0) {
        const nextOrder = images.length;
        const newImages: ProductImage[] = data.urls.map((url: string, index: number) => ({
          url,
          alt: `${name} Görseli`,
          order: nextOrder + index,
        }));
        setImages([...images, ...newImages]);
      }
    } catch (err: unknown) {
      setErrorMsg(err instanceof Error ? err.message : "Dosyalar yüklenemedi.");
    } finally {
      setIsUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  };

  const removeImage = (idx: number) => {
    setImages(images.filter((_, i) => i !== idx));
  };

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

    const productPayload = {
      id: product?.id,
      name,
      nameTr: name,
      nameEn: nameEn || null,
      nameRu: nameRu || null,
      slug,
      sku: sku || null,
      categoryId,
      seriesId: seriesId || null,
      widthCm: widthCm === "" ? null : Number(widthCm),
      surface: surface || null,
      burnerCount: burnerCount === "" ? null : Number(burnerCount),
      description,
      descriptionTr: description,
      descriptionEn: descriptionEn || null,
      descriptionRu: descriptionRu || null,
      features,
      featuresTr: features,
      featuresEn: linesToList(featuresEn),
      featuresRu: linesToList(featuresRu),
      options,
      optionsTr: options,
      optionsEn: linesToList(optionsEn),
      optionsRu: linesToList(optionsRu),
      accessories,
      accessoriesTr: accessories,
      accessoriesEn: linesToList(accessoriesEn),
      accessoriesRu: linesToList(accessoriesRu),
      images,
      status,
    };

    startTransition(async () => {
      const res = await saveProduct(productPayload);
      if (res.success) {
        router.push("/admin/dashboard");
        router.refresh();
      } else if (res.error) {
        setErrorMsg(res.error);
      }
    });
  };

  const inputStyle: React.CSSProperties = {
    background: "rgba(128,128,160,0.06)",
    border: "1px solid var(--border)",
    color: "var(--fg-primary)",
  };

  const labelStyle: React.CSSProperties = {
    fontFamily: "var(--font-ibm-plex-mono)",
    fontSize: "10px",
    textTransform: "uppercase" as const,
    letterSpacing: "0.14em",
    color: "var(--fg-muted)",
  };

  return (
    <div
      className="flex w-full max-w-6xl flex-col gap-8"
    >
      <div className="flex flex-col gap-2">
        <Link
          href="/admin/dashboard"
          className="inline-flex items-center gap-2 text-xs font-mono tracking-wider hover:text-ember transition-colors"
          style={{ color: "var(--fg-muted)" }}
        >
          <ArrowLeft size={14} /> Dashboard&apos;a Dön
        </Link>
        <h1 className="font-serif text-3xl font-light">
          {product?.id ? `${product.name} Düzenle` : "Yeni Ürün Ekle"}
        </h1>
      </div>

      {errorMsg && (
        <div className="p-4 rounded-2xl text-xs font-mono" style={{ background: "rgba(239,68,68,0.1)", color: "#EF4444", border: "1px solid rgba(239,68,68,0.2)" }}>
          {errorMsg}
        </div>
      )}

      <form onSubmit={handleSubmit} className="flex flex-col gap-8">
        {/* Basic Information Section */}
        <div className="liquid-glass p-8 rounded-3xl flex flex-col gap-6" style={{ border: "1px solid var(--border)" }}>
          <h2 className="text-xs font-mono uppercase tracking-widest" style={{ color: "var(--ember)" }}>Temel Bilgiler</h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
            <div className="flex flex-col gap-2">
              <label style={labelStyle}>Ürün Adı · Türkçe *</label>
              <input
                type="text"
                required
                value={name}
                onChange={handleNameChange}
                placeholder="Örn: Elite 90G"
                className="w-full px-4 py-3 rounded-full text-xs focus:outline-none"
                style={inputStyle}
              />
            </div>

            <div className="flex flex-col gap-2">
              <label style={labelStyle}>URL Linki (Slug) *</label>
              <input
                type="text"
                required
                value={slug}
                onChange={(e) => setSlug(slugify(e.target.value))}
                placeholder="Örn: elite-90g"
                className="w-full px-4 py-3 rounded-full text-xs focus:outline-none font-mono"
                style={inputStyle}
              />
            </div>

            <div className="flex flex-col gap-2">
              <label style={labelStyle}>Model Kodu (SKU)</label>
              <input
                type="text"
                value={sku}
                onChange={(e) => setSku(e.target.value)}
                placeholder="Örn: ND5-BLG-TS3C"
                className="w-full px-4 py-3 rounded-full text-xs focus:outline-none font-mono"
                style={inputStyle}
              />
            </div>

            <div className="flex flex-col gap-2">
              <label style={labelStyle}>Kategori *</label>
              <select
                value={categoryId}
                onChange={handleCategoryChange}
                className="w-full px-4 py-3 rounded-full text-xs focus:outline-none cursor-pointer"
                style={inputStyle}
              >
                {categories.map((cat) => (
                  <option key={cat.id} value={cat.id}>
                    {cat.name}
                  </option>
                ))}
              </select>
            </div>

            <div className="flex flex-col gap-2">
              <label style={labelStyle}>Seri (Varsa)</label>
              <select
                value={seriesId}
                onChange={(e) => setSeriesId(e.target.value)}
                className="w-full px-4 py-3 rounded-full text-xs focus:outline-none cursor-pointer"
                style={inputStyle}
              >
                <option value="">Seri Seçilmedi</option>
                {filteredSeries.map((ser) => (
                  <option key={ser.id} value={ser.id}>
                    {ser.name}
                  </option>
                ))}
              </select>
            </div>

            <div className="flex flex-col gap-2">
              <label style={labelStyle}>Yayın Durumu</label>
              {permissions.canPublish ? (
                <select
                  value={status}
                  onChange={(e) => setStatus(e.target.value)}
                  className="w-full px-4 py-3 rounded-full text-xs focus:outline-none cursor-pointer"
                  style={inputStyle}
                >
                  <option value="draft">Taslak</option>
                  <option value="published">Yayında</option>
                </select>
              ) : <div className="w-full rounded-full px-4 py-3 text-xs" style={inputStyle}>{status === "published" ? "Yayında · değiştirme yetkiniz yok" : "Taslak"}</div>}
            </div>
          </div>
        </div>

        {/* Technical Specs Section */}
        <div className="liquid-glass p-8 rounded-3xl flex flex-col gap-6" style={{ border: "1px solid var(--border)" }}>
          <h2 className="text-xs font-mono uppercase tracking-widest" style={{ color: "var(--ember)" }}>Teknik Ölçü ve Detaylar</h2>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
            <div className="flex flex-col gap-2">
              <label style={labelStyle}>Genişlik (cm)</label>
              <input
                type="number"
                value={widthCm}
                onChange={(e) => setWidthCm(e.target.value === "" ? "" : Number(e.target.value))}
                placeholder="Örn: 90"
                className="w-full px-4 py-3 rounded-full text-xs focus:outline-none font-mono"
                style={inputStyle}
              />
            </div>

            <div className="flex flex-col gap-2">
              <label style={labelStyle}>Yüzey Tipi</label>
              <input
                type="text"
                value={surface}
                onChange={(e) => setSurface(e.target.value)}
                placeholder="Örn: Siyah Temperli Cam"
                className="w-full px-4 py-3 rounded-full text-xs focus:outline-none"
                style={inputStyle}
              />
            </div>

            <div className="flex flex-col gap-2">
              <label style={labelStyle}>Gazlı Göz Sayısı</label>
              <input
                type="number"
                value={burnerCount}
                onChange={(e) => setBurnerCount(e.target.value === "" ? "" : Number(e.target.value))}
                placeholder="Örn: 5"
                className="w-full px-4 py-3 rounded-full text-xs focus:outline-none font-mono"
                style={inputStyle}
              />
            </div>
          </div>

          <div className="flex flex-col gap-2">
            <label style={labelStyle}>Ürün Açıklaması · Türkçe</label>
            <textarea
              rows={4}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Ürünün detaylı açıklamasını girin..."
              className="w-full p-4 rounded-2xl text-xs focus:outline-none resize-none"
              style={inputStyle}
            />
          </div>
        </div>

        {/* Feature Lists Section */}
        <div className="liquid-glass p-8 rounded-3xl flex flex-col gap-6" style={{ border: "1px solid var(--border)" }}>
          <div>
            <h2 className="text-xs font-mono uppercase tracking-widest" style={{ color: "var(--ember)" }}>Özellik ve Opsiyon Listeleri · Türkçe</h2>
            <p className="mt-2 text-xs leading-relaxed" style={{ color: "var(--fg-muted)" }}>Türkçe ana katalog içeriğidir. İngilizce veya Rusça alan boş bırakılırsa vitrin mevcut güvenli çeviri metnini kullanır.</p>
          </div>

          <div className="flex flex-col gap-6">
            {/* Features */}
            <div className="flex flex-col gap-3">
              <label style={labelStyle}>Öne Çıkan Özellikler</label>
              <div className="flex gap-2">
                <input
                  type="text"
                  value={featureInput}
                  onChange={(e) => setFeatureInput(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addFeature(); } }}
                  placeholder="Yeni özellik ekle ve Enter'a bas..."
                  className="flex-grow px-4 py-2.5 rounded-full text-xs focus:outline-none"
                  style={inputStyle}
                />
                <button
                  type="button"
                  onClick={addFeature}
                  className="px-4 py-2.5 rounded-full text-xs font-mono uppercase tracking-wider font-semibold"
                  style={{ background: "var(--ember)", color: "var(--surface-0)" }}
                >
                  <Plus size={14} />
                </button>
              </div>
              <div className="flex flex-wrap gap-2">
                {features.map((item, idx) => (
                  <span
                    key={idx}
                    className="px-3 py-1.5 rounded-full text-xs flex items-center gap-2"
                    style={{ background: "rgba(128,128,160,0.08)", border: "1px solid var(--border)" }}
                  >
                    <span>{item}</span>
                    <button type="button" onClick={() => removeListItem("features", idx)} className="hover:text-red-400">
                      <X size={12} />
                    </button>
                  </span>
                ))}
              </div>
            </div>

            {/* Options */}
            <div className="flex flex-col gap-3">
              <label style={labelStyle}>Opsiyonlar</label>
              <div className="flex gap-2">
                <input
                  type="text"
                  value={optionInput}
                  onChange={(e) => setOptionInput(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addOption(); } }}
                  placeholder="Yeni opsiyon ekle..."
                  className="flex-grow px-4 py-2.5 rounded-full text-xs focus:outline-none"
                  style={inputStyle}
                />
                <button
                  type="button"
                  onClick={addOption}
                  className="px-4 py-2.5 rounded-full text-xs font-mono uppercase tracking-wider font-semibold"
                  style={{ background: "var(--ember)", color: "var(--surface-0)" }}
                >
                  <Plus size={14} />
                </button>
              </div>
              <div className="flex flex-wrap gap-2">
                {options.map((item, idx) => (
                  <span
                    key={idx}
                    className="px-3 py-1.5 rounded-full text-xs flex items-center gap-2"
                    style={{ background: "rgba(128,128,160,0.08)", border: "1px solid var(--border)" }}
                  >
                    <span>{item}</span>
                    <button type="button" onClick={() => removeListItem("options", idx)} className="hover:text-red-400">
                      <X size={12} />
                    </button>
                  </span>
                ))}
              </div>
            </div>

            {/* Accessories */}
            <div className="flex flex-col gap-3">
              <label style={labelStyle}>Aksesuarlar</label>
              <div className="flex gap-2">
                <input
                  type="text"
                  value={accessoryInput}
                  onChange={(e) => setAccessoryInput(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addAccessory(); } }}
                  placeholder="Yeni aksesuar ekle..."
                  className="flex-grow px-4 py-2.5 rounded-full text-xs focus:outline-none"
                  style={inputStyle}
                />
                <button
                  type="button"
                  onClick={addAccessory}
                  className="px-4 py-2.5 rounded-full text-xs font-mono uppercase tracking-wider font-semibold"
                  style={{ background: "var(--ember)", color: "var(--surface-0)" }}
                >
                  <Plus size={14} />
                </button>
              </div>
              <div className="flex flex-wrap gap-2">
                {accessories.map((item, idx) => (
                  <span
                    key={idx}
                    className="px-3 py-1.5 rounded-full text-xs flex items-center gap-2"
                    style={{ background: "rgba(128,128,160,0.08)", border: "1px solid var(--border)" }}
                  >
                    <span>{item}</span>
                    <button type="button" onClick={() => removeListItem("accessories", idx)} className="hover:text-red-400">
                      <X size={12} />
                    </button>
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Localized catalogue copy */}
        <div className="liquid-glass p-8 rounded-3xl flex flex-col gap-7" style={{ border: "1px solid var(--border)" }}>
          <div>
            <h2 className="text-xs font-mono uppercase tracking-widest" style={{ color: "var(--ember)" }}>İngilizce ve Rusça Katalog Metinleri</h2>
            <p className="mt-2 text-xs leading-relaxed" style={{ color: "var(--fg-muted)" }}>Her liste öğesini ayrı satıra yazın. Girilen metin sitede aynen yayınlanır; boş alanlar otomatik geri dönüşle tamamlanır.</p>
          </div>

          {[
            { code: "EN", nameValue: nameEn, setNameValue: setNameEn, descriptionValue: descriptionEn, setDescriptionValue: setDescriptionEn, featuresValue: featuresEn, setFeaturesValue: setFeaturesEn, optionsValue: optionsEn, setOptionsValue: setOptionsEn, accessoriesValue: accessoriesEn, setAccessoriesValue: setAccessoriesEn },
            { code: "RU", nameValue: nameRu, setNameValue: setNameRu, descriptionValue: descriptionRu, setDescriptionValue: setDescriptionRu, featuresValue: featuresRu, setFeaturesValue: setFeaturesRu, optionsValue: optionsRu, setOptionsValue: setOptionsRu, accessoriesValue: accessoriesRu, setAccessoriesValue: setAccessoriesRu },
          ].map((language) => (
            <section key={language.code} className="rounded-3xl border p-5 md:p-6" style={{ borderColor: "var(--border)", background: "rgba(128,128,160,0.035)" }}>
              <div className="mb-5 flex items-center justify-between gap-4">
                <h3 className="font-mono text-xs font-semibold tracking-[.18em]" style={{ color: "var(--ember)" }}>{language.code}</h3>
                <span className="font-mono text-[9px] uppercase tracking-[.13em]" style={{ color: "var(--fg-muted)" }}>Boşsa otomatik geri dönüş</span>
              </div>
              <div className="grid grid-cols-1 gap-5 md:grid-cols-2">
                <div className="flex flex-col gap-2">
                  <label style={labelStyle}>Ürün adı</label>
                  <input type="text" value={language.nameValue} onChange={(event) => language.setNameValue(event.target.value)} className="w-full rounded-full px-4 py-3 text-xs focus:outline-none" style={inputStyle} />
                </div>
                <div className="flex flex-col gap-2 md:row-span-2">
                  <label style={labelStyle}>Açıklama</label>
                  <textarea rows={6} value={language.descriptionValue} onChange={(event) => language.setDescriptionValue(event.target.value)} className="w-full resize-y rounded-2xl p-4 text-xs focus:outline-none" style={inputStyle} />
                </div>
                <div className="flex flex-col gap-2">
                  <label style={labelStyle}>Özellikler · satır başına bir öğe</label>
                  <textarea rows={5} value={language.featuresValue} onChange={(event) => language.setFeaturesValue(event.target.value)} className="w-full resize-y rounded-2xl p-4 text-xs focus:outline-none" style={inputStyle} />
                </div>
                <div className="flex flex-col gap-2">
                  <label style={labelStyle}>Opsiyonlar · satır başına bir öğe</label>
                  <textarea rows={5} value={language.optionsValue} onChange={(event) => language.setOptionsValue(event.target.value)} className="w-full resize-y rounded-2xl p-4 text-xs focus:outline-none" style={inputStyle} />
                </div>
                <div className="flex flex-col gap-2">
                  <label style={labelStyle}>Aksesuarlar · satır başına bir öğe</label>
                  <textarea rows={5} value={language.accessoriesValue} onChange={(event) => language.setAccessoriesValue(event.target.value)} className="w-full resize-y rounded-2xl p-4 text-xs focus:outline-none" style={inputStyle} />
                </div>
              </div>
            </section>
          ))}
        </div>

        {/* Product Images Section */}
        <div className="liquid-glass p-8 rounded-3xl flex flex-col gap-6" style={{ border: "1px solid var(--border)" }}>
          <div className="flex items-center justify-between">
            <h2 className="text-xs font-mono uppercase tracking-widest" style={{ color: "var(--ember)" }}>Ürün Görselleri</h2>
            {permissions.canUpload ? <>
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                multiple
                onChange={handleImageUpload}
                className="hidden"
              />
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                disabled={isUploading}
                className="glass-pill px-5 py-2.5 rounded-full text-xs font-mono uppercase tracking-widest flex items-center gap-2 cursor-pointer"
                style={{ color: "var(--ember)" }}
              >
                <Upload size={14} />
                {isUploading ? "Yükleniyor..." : "Görsel Yükle"}
              </button>
            </> : <span className="text-xs text-fg-muted">Dosya yükleme yetkiniz yok</span>}
          </div>

          <div className="grid grid-cols-2 sm:grid-cols-4 md:grid-cols-5 gap-4">
            {images.map((img, idx) => (
              <div
                key={idx}
                className="relative aspect-square rounded-2xl overflow-hidden border group"
                style={{ background: "var(--surface-1)", borderColor: "var(--border)" }}
              >
                <Image
                  src={img.url}
                  alt={img.alt || name}
                  fill
                  className="object-contain p-2"
                  sizes="150px"
                />
                <button
                  type="button"
                  onClick={() => removeImage(idx)}
                  className="absolute top-2 right-2 p-1.5 rounded-full bg-red-500/80 text-white opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  <Trash2 size={13} />
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Submit Actions */}
        <div className="flex items-center justify-end gap-4">
          <Link
            href="/admin/dashboard"
            className="px-6 py-3.5 rounded-full text-xs font-mono uppercase tracking-widest"
            style={{ border: "1px solid var(--border)", color: "var(--fg-secondary)" }}
          >
            İptal
          </Link>
          <button
            type="submit"
            disabled={isPending}
            className="px-8 py-3.5 rounded-full text-xs font-mono uppercase tracking-widest font-semibold cursor-pointer shadow-lg hover:scale-105 transition-all"
            style={{ background: "var(--ember)", color: "var(--surface-0)" }}
          >
            {isPending ? "Kaydediliyor..." : "Ürünü Kaydet"}
          </button>
        </div>
      </form>
    </div>
  );
}
