"use client";

import * as React from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Plus,
  Trash2,
  GripVertical,
  ChevronDown,
  ChevronUp,
  ChevronLeft,
  ChevronRight,
  ImagePlus,
  Loader2,
} from "lucide-react";
import { deleteUpload, uploadImages } from "@/lib/actions/uploads";
import {
  IMAGE_ACCEPT,
  IMAGE_EXT_BY_MIME,
  UPLOAD_MAX_BYTES,
  formatBytes,
} from "@/lib/upload-config";
import { FormField } from "./FormField";
import type {
  ProductSpecification,
  ProductFAQ,
  ProductFeature,
  ProductTag,
  ProductImage,
} from "../../types/product-form";

// ============================================================================
// Specification Fields
// ============================================================================

interface SpecificationFieldsProps {
  specifications: ProductSpecification[];
  onChange: (specs: ProductSpecification[]) => void;
  specificationGroups?: string[];
}

export function SpecificationFields({
  specifications,
  onChange,
  specificationGroups = [
    "General",
    "Processor",
    "Memory",
    "Storage",
    "Graphics",
    "Display",
    "Connectivity",
    "Audio",
    "Power",
    "Physical",
    "Other",
  ],
}: SpecificationFieldsProps) {
  const [expandedIds, setExpandedIds] = React.useState<Set<string>>(new Set());

  const addSpecification = () => {
    const newSpec: ProductSpecification = {
      id: `spec-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      name: "",
      value: "",
      group: specificationGroups[0],
      sortOrder: specifications.length,
    };
    onChange([...specifications, newSpec]);
    // Auto-expand the new specification
    setExpandedIds((prev) => new Set([...prev, newSpec.id]));
  };

  const removeSpecification = (id: string) => {
    onChange(specifications.filter((s) => s.id !== id));
    setExpandedIds((prev) => {
      const next = new Set(prev);
      next.delete(id);
      return next;
    });
  };

  const updateSpecification = (
    id: string,
    field: keyof ProductSpecification,
    value: string | number,
  ) => {
    onChange(
      specifications.map((s) => (s.id === id ? { ...s, [field]: value } : s)),
    );
  };

  const toggleExpanded = (id: string) => {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  const moveSpecification = (index: number, direction: "up" | "down") => {
    const newSpecs = [...specifications];
    const targetIndex = direction === "up" ? index - 1 : index + 1;
    if (targetIndex < 0 || targetIndex >= newSpecs.length) return;
    [newSpecs[index], newSpecs[targetIndex]] = [
      newSpecs[targetIndex],
      newSpecs[index],
    ];
    // Update sortOrder
    newSpecs.forEach((s, i) => (s.sortOrder = i));
    onChange(newSpecs);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium text-foreground">
          Technical Specifications
        </h3>
        <Button variant="outline" size="sm" onClick={addSpecification}>
          <Plus className="h-4 w-4 mr-1.5" />
          Add Specification
        </Button>
      </div>

      {specifications.length === 0 ? (
        <div className="text-center py-8 text-muted-foreground border-2 border-dashed border-border rounded-xl">
          <p className="text-sm">No specifications added yet.</p>
          <p className="text-xs mt-1">
            Click &quot;Add Specification&quot; to start adding technical
            details.
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {specifications.map((spec, index) => {
            const isExpanded = expandedIds.has(spec.id);
            return (
              <div
                key={spec.id}
                className="rounded-xl border border-border bg-card p-4 transition-all"
              >
                <div className="flex items-start gap-3">
                  <button
                    type="button"
                    className="p-1 text-muted-foreground hover:text-foreground transition-colors"
                    onClick={() => toggleExpanded(spec.id)}
                    aria-label={isExpanded ? "Collapse" : "Expand"}
                  >
                    {isExpanded ? (
                      <ChevronUp className="h-5 w-5" />
                    ) : (
                      <ChevronDown className="h-5 w-5" />
                    )}
                  </button>

                  <div className="flex-1 min-w-0 space-y-3">
                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                      <FormField
                        label="Group"
                        required
                        htmlFor={`${spec.id}-group`}
                      >
                        <Select
                          items={specificationGroups.map((group) => ({
                            value: group,
                            label: group,
                          }))}
                          value={spec.group || specificationGroups[0] || ""}
                          onValueChange={(v) =>
                            updateSpecification(spec.id, "group", v ?? "")
                          }
                        >
                          <SelectTrigger
                            className="w-full"
                            id={`${spec.id}-group`}
                          >
                            <SelectValue placeholder="Select group" />
                          </SelectTrigger>
                          <SelectContent>
                            {specificationGroups.map((group) => (
                              <SelectItem key={group} value={group}>
                                {group}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </FormField>

                      <FormField
                        label="Name"
                        required
                        htmlFor={`${spec.id}-name`}
                      >
                        <Input
                          id={`${spec.id}-name`}
                          value={spec.name}
                          onChange={(e) =>
                            updateSpecification(spec.id, "name", e.target.value)
                          }
                          placeholder="e.g., Processor Socket"
                        />
                      </FormField>

                      <FormField
                        label="Value"
                        required
                        htmlFor={`${spec.id}-value`}
                      >
                        <Input
                          id={`${spec.id}-value`}
                          value={spec.value}
                          onChange={(e) =>
                            updateSpecification(
                              spec.id,
                              "value",
                              e.target.value,
                            )
                          }
                          placeholder="e.g., Socket AM5"
                        />
                      </FormField>
                    </div>

                    {isExpanded && (
                      <div className="flex items-center justify-end gap-2 pt-2 border-t border-border">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => moveSpecification(index, "up")}
                          disabled={index === 0}
                        >
                          <GripVertical className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => moveSpecification(index, "down")}
                          disabled={index === specifications.length - 1}
                        >
                          <GripVertical className="h-4 w-4 rotate-180" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="text-destructive hover:text-destructive hover:bg-destructive/10"
                          onClick={() => removeSpecification(spec.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ============================================================================
// FAQ Fields
// ============================================================================

interface FAQFieldsProps {
  faqs: ProductFAQ[];
  onChange: (faqs: ProductFAQ[]) => void;
}

export function FAQFields({ faqs, onChange }: FAQFieldsProps) {
  const [expandedIds, setExpandedIds] = React.useState<Set<string>>(new Set());

  const addFAQ = () => {
    const newFAQ: ProductFAQ = {
      id: `faq-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      question: "",
      answer: "",
      sortOrder: faqs.length,
    };
    onChange([...faqs, newFAQ]);
    setExpandedIds((prev) => new Set([...prev, newFAQ.id]));
  };

  const removeFAQ = (id: string) => {
    onChange(faqs.filter((f) => f.id !== id));
    setExpandedIds((prev) => {
      const next = new Set(prev);
      next.delete(id);
      return next;
    });
  };

  const updateFAQ = (
    id: string,
    field: keyof ProductFAQ,
    value: string | number,
  ) => {
    onChange(faqs.map((f) => (f.id === id ? { ...f, [field]: value } : f)));
  };

  const toggleExpanded = (id: string) => {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  const moveFAQ = (index: number, direction: "up" | "down") => {
    const newFAQs = [...faqs];
    const targetIndex = direction === "up" ? index - 1 : index + 1;
    if (targetIndex < 0 || targetIndex >= newFAQs.length) return;
    [newFAQs[index], newFAQs[targetIndex]] = [
      newFAQs[targetIndex],
      newFAQs[index],
    ];
    newFAQs.forEach((f, i) => (f.sortOrder = i));
    onChange(newFAQs);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium text-foreground">
          Frequently Asked Questions
        </h3>
        <Button variant="outline" size="sm" onClick={addFAQ}>
          <Plus className="h-4 w-4 mr-1.5" />
          Add FAQ
        </Button>
      </div>

      {faqs.length === 0 ? (
        <div className="text-center py-8 text-muted-foreground border-2 border-dashed border-border rounded-xl">
          <p className="text-sm">No FAQs added yet.</p>
          <p className="text-xs mt-1">
            Click &quot;Add FAQ&quot; to start adding common questions and
            answers.
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {faqs.map((faq, index) => {
            const isExpanded = expandedIds.has(faq.id);
            return (
              <div
                key={faq.id}
                className="rounded-xl border border-border bg-card p-4 transition-all"
              >
                <div className="flex items-start gap-3">
                  <button
                    type="button"
                    className="p-1 text-muted-foreground hover:text-foreground transition-colors"
                    onClick={() => toggleExpanded(faq.id)}
                    aria-label={isExpanded ? "Collapse" : "Expand"}
                  >
                    {isExpanded ? (
                      <ChevronUp className="h-5 w-5" />
                    ) : (
                      <ChevronDown className="h-5 w-5" />
                    )}
                  </button>

                  <div className="flex-1 min-w-0 space-y-3">
                    <FormField
                      label="Question"
                      required
                      htmlFor={`${faq.id}-question`}
                    >
                      <Input
                        id={`${faq.id}-question`}
                        value={faq.question}
                        onChange={(e) =>
                          updateFAQ(faq.id, "question", e.target.value)
                        }
                        placeholder="e.g., What is the warranty period?"
                      />
                    </FormField>

                    <FormField
                      label="Answer"
                      required
                      htmlFor={`${faq.id}-answer`}
                    >
                      <Textarea
                        id={`${faq.id}-answer`}
                        value={faq.answer}
                        onChange={(e) =>
                          updateFAQ(faq.id, "answer", e.target.value)
                        }
                        placeholder="Provide a detailed answer..."
                        rows={3}
                      />
                    </FormField>

                    {isExpanded && (
                      <div className="flex items-center justify-end gap-2 pt-2 border-t border-border">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => moveFAQ(index, "up")}
                          disabled={index === 0}
                        >
                          <GripVertical className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => moveFAQ(index, "down")}
                          disabled={index === faqs.length - 1}
                        >
                          <GripVertical className="h-4 w-4 rotate-180" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="text-destructive hover:text-destructive hover:bg-destructive/10"
                          onClick={() => removeFAQ(faq.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ============================================================================
// Feature Fields
// ============================================================================

interface FeatureFieldsProps {
  features: ProductFeature[];
  onChange: (features: ProductFeature[]) => void;
}

export function FeatureFields({ features, onChange }: FeatureFieldsProps) {
  const [expandedIds, setExpandedIds] = React.useState<Set<string>>(new Set());

  const addFeature = () => {
    const newFeature: ProductFeature = {
      id: `feature-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      title: "",
      description: "",
      sortOrder: features.length,
    };
    onChange([...features, newFeature]);
    setExpandedIds((prev) => new Set([...prev, newFeature.id]));
  };

  const removeFeature = (id: string) => {
    onChange(features.filter((f) => f.id !== id));
    setExpandedIds((prev) => {
      const next = new Set(prev);
      next.delete(id);
      return next;
    });
  };

  const updateFeature = (
    id: string,
    field: keyof ProductFeature,
    value: string | number,
  ) => {
    onChange(features.map((f) => (f.id === id ? { ...f, [field]: value } : f)));
  };

  const toggleExpanded = (id: string) => {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  const moveFeature = (index: number, direction: "up" | "down") => {
    const newFeatures = [...features];
    const targetIndex = direction === "up" ? index - 1 : index + 1;
    if (targetIndex < 0 || targetIndex >= newFeatures.length) return;
    [newFeatures[index], newFeatures[targetIndex]] = [
      newFeatures[targetIndex],
      newFeatures[index],
    ];
    newFeatures.forEach((f, i) => (f.sortOrder = i));
    onChange(newFeatures);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium text-foreground">Key Features</h3>
        <Button variant="outline" size="sm" onClick={addFeature}>
          <Plus className="h-4 w-4 mr-1.5" />
          Add Feature
        </Button>
      </div>

      {features.length === 0 ? (
        <div className="text-center py-8 text-muted-foreground border-2 border-dashed border-border rounded-xl">
          <p className="text-sm">No features added yet.</p>
          <p className="text-xs mt-1">
            Click &quot;Add Feature&quot; to highlight key product features.
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {features.map((feature, index) => {
            const isExpanded = expandedIds.has(feature.id);
            return (
              <div
                key={feature.id}
                className="rounded-xl border border-border bg-card p-4 transition-all"
              >
                <div className="flex items-start gap-3">
                  <button
                    type="button"
                    className="p-1 text-muted-foreground hover:text-foreground transition-colors"
                    onClick={() => toggleExpanded(feature.id)}
                    aria-label={isExpanded ? "Collapse" : "Expand"}
                  >
                    {isExpanded ? (
                      <ChevronUp className="h-5 w-5" />
                    ) : (
                      <ChevronDown className="h-5 w-5" />
                    )}
                  </button>

                  <div className="flex-1 min-w-0 space-y-3">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <FormField
                        label="Feature Title"
                        required
                        htmlFor={`${feature.id}-title`}
                      >
                        <Input
                          id={`${feature.id}-title`}
                          value={feature.title}
                          onChange={(e) =>
                            updateFeature(feature.id, "title", e.target.value)
                          }
                          placeholder="e.g., 16-Core Performance"
                        />
                      </FormField>

                      <FormField
                        label="Icon (optional)"
                        htmlFor={`${feature.id}-icon`}
                      >
                        <Input
                          id={`${feature.id}-icon`}
                          value={feature.icon || ""}
                          onChange={(e) =>
                            updateFeature(feature.id, "icon", e.target.value)
                          }
                          placeholder="e.g., cpu, memory, graphics"
                        />
                      </FormField>
                    </div>

                    <FormField
                      label="Description"
                      htmlFor={`${feature.id}-description`}
                    >
                      <Textarea
                        id={`${feature.id}-description`}
                        value={feature.description}
                        onChange={(e) =>
                          updateFeature(
                            feature.id,
                            "description",
                            e.target.value,
                          )
                        }
                        placeholder="Describe this feature in detail..."
                        rows={2}
                      />
                    </FormField>

                    {isExpanded && (
                      <div className="flex items-center justify-end gap-2 pt-2 border-t border-border">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => moveFeature(index, "up")}
                          disabled={index === 0}
                        >
                          <GripVertical className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => moveFeature(index, "down")}
                          disabled={index === features.length - 1}
                        >
                          <GripVertical className="h-4 w-4 rotate-180" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="text-destructive hover:text-destructive hover:bg-destructive/10"
                          onClick={() => removeFeature(feature.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ============================================================================
// Tag Fields
// ============================================================================

interface TagFieldsProps {
  tags: string[]; // Tag names/IDs
  onChange: (tags: string[]) => void;
  availableTags?: ProductTag[];
  allowCreate?: boolean;
}

export function TagFields({
  tags,
  onChange,
  availableTags = [],
  allowCreate = true,
}: TagFieldsProps) {
  const [newTag, setNewTag] = React.useState("");

  const handleAddTag = (e?: React.FormEvent) => {
    e?.preventDefault();
    const tag = newTag.trim();
    if (tag && !tags.includes(tag)) {
      onChange([...tags, tag]);
      setNewTag("");
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      handleAddTag(e);
    } else if (e.key === ",") {
      handleAddTag(e);
    }
  };

  const removeTag = (tag: string) => {
    onChange(tags.filter((t) => t !== tag));
  };

  const selectSuggestedTag = (tag: string) => {
    if (!tags.includes(tag)) {
      onChange([...tags, tag]);
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium text-foreground">Product Tags</h3>
      </div>

      <FormField label="Tags" description="Press Enter or comma to add tags">
        <div className="flex flex-wrap gap-2">
          {tags.map((tag) => (
            <span
              key={tag}
              className="inline-flex items-center gap-1.5 rounded-full bg-primary/10 text-primary px-2.5 py-1 text-sm"
            >
              {tag}
              <button
                type="button"
                onClick={() => removeTag(tag)}
                className="p-0.5 rounded-full hover:bg-primary/20 transition-colors"
                aria-label={`Remove tag: ${tag}`}
              >
                <Trash2 className="h-3 w-3" />
              </button>
            </span>
          ))}

          <div className="flex items-center gap-2">
            <Input
              type="text"
              value={newTag}
              onChange={(e) => setNewTag(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder={
                allowCreate
                  ? "Type tag, press Enter..."
                  : "Select from suggestions"
              }
              className="w-full"
              disabled={!allowCreate && availableTags.length === 0}
            />
            {allowCreate && (
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={handleAddTag}
                disabled={!newTag.trim() || tags.includes(newTag.trim())}
              >
                Add
              </Button>
            )}
          </div>
        </div>
      </FormField>

      {availableTags.length > 0 && (
        <div className="space-y-2">
          <p className="text-xs text-muted-foreground">Suggested tags:</p>
          <div className="flex flex-wrap gap-2">
            {availableTags
              .filter((t) => !tags.includes(t.name))
              .map((tag) => (
                <Button
                  key={tag.id}
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => selectSuggestedTag(tag.name)}
                  className={
                    tag.color
                      ? `border-${tag.color} text-${tag.color}`
                      : undefined
                  }
                >
                  {tag.name}
                </Button>
              ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ============================================================================
// Image Upload Fields
// ============================================================================

interface ProductImageFieldsProps {
  images: ProductImage[];
  onChange: (images: ProductImage[]) => void;
  maxImages?: number;
}

export function ProductImageFields({
  images,
  onChange,
  maxImages = 10,
}: ProductImageFieldsProps) {
  const fileInputRef = React.useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = React.useState(false);
  const [uploadError, setUploadError] = React.useState<string | null>(null);
  // Paths added during this session — when one is dropped from the form it is
  // deleted immediately so a file that never got saved cannot linger in
  // /upload/. Pre-existing (saved) images are pruned server-side on save.
  const sessionUploaded = React.useRef(new Set<string>());

  async function handleFiles(files: FileList | null) {
    const picked = Array.from(files ?? []);
    if (!picked.length) return;

    if (picked.some((f) => !(f.type in IMAGE_EXT_BY_MIME))) {
      setUploadError("Only JPG, PNG, WebP or GIF images are supported.");
      return;
    }
    if (picked.some((f) => f.size > UPLOAD_MAX_BYTES)) {
      setUploadError(
        `Each image must be smaller than ${formatBytes(UPLOAD_MAX_BYTES)}.`,
      );
      return;
    }
    if (images.length + picked.length > maxImages) {
      setUploadError(`You can add up to ${maxImages} images.`);
      return;
    }

    setUploading(true);
    setUploadError(null);
    const formData = new FormData();
    picked.forEach((f) => formData.append("file", f));
    const result = await uploadImages(formData, "products");
    if (fileInputRef.current) fileInputRef.current.value = "";
    setUploading(false);
    if (!result.ok) {
      setUploadError(result.error);
      return;
    }
    const paths = result.data?.paths ?? [];
    paths.forEach((p) => sessionUploaded.current.add(p));
    const added: ProductImage[] = paths.map((url, i) => ({
      id: `img-${Date.now()}-${Math.random().toString(36).slice(2, 9)}-${i}`,
      url,
      alt: "",
      isPrimary: images.length === 0 && i === 0,
      sortOrder: images.length + i,
    }));
    onChange([...images, ...added]);
  }

  const removeImage = async (id: string, url: string) => {
    if (sessionUploaded.current.has(url)) {
      await deleteUpload(url).catch(() => {});
      sessionUploaded.current.delete(url);
    }
    const newImages = images.filter((img) => img.id !== id);
    // If removing primary, make the first remaining image primary.
    const hasPrimary = newImages.some((img) => img.isPrimary);
    if (!hasPrimary && newImages.length > 0) {
      newImages[0].isPrimary = true;
    }
    onChange(newImages);
  };

  const setPrimaryImage = (id: string) => {
    onChange(
      images.map((img) => ({
        ...img,
        isPrimary: img.id === id,
      })),
    );
  };

  const moveImage = (index: number, direction: "up" | "down") => {
    const newImages = [...images];
    const targetIndex = direction === "up" ? index - 1 : index + 1;
    if (targetIndex < 0 || targetIndex >= newImages.length) return;
    [newImages[index], newImages[targetIndex]] = [
      newImages[targetIndex],
      newImages[index],
    ];
    newImages.forEach((img, i) => (img.sortOrder = i));
    onChange(newImages);
  };

  const primaryImage = images.find((img) => img.isPrimary) || images[0];

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium text-foreground">Product Images</h3>
        <span className="text-sm text-muted-foreground">
          {images.length}/{maxImages}
        </span>
      </div>

      <input
        ref={fileInputRef}
        type="file"
        accept={IMAGE_ACCEPT}
        multiple
        className="sr-only"
        onChange={(e) => handleFiles(e.target.files)}
        disabled={uploading}
      />

      {primaryImage && (
        <div className="relative aspect-square max-w-xs rounded-xl overflow-hidden border border-border bg-muted">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={primaryImage.url}
            alt={primaryImage.alt || "Primary product image"}
            className="w-full h-full object-cover"
          />
          {images.length > 1 && (
            <div className="absolute bottom-2 right-2">
              <span className="rounded-full bg-background/80 px-2 py-1 text-xs font-medium backdrop-blur-sm">
                +{images.length - 1} more
              </span>
            </div>
          )}
          {images.length > 0 && (
            <div className="absolute top-2 left-2">
              <span className="rounded-full bg-green-500/90 px-2 py-0.5 text-xs font-medium text-white">
                Primary
              </span>
            </div>
          )}
        </div>
      )}

      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
        {images.map((image, index) => (
          <div key={image.id} className="relative group">
            <div className="relative aspect-square rounded-lg overflow-hidden border border-border bg-muted">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={image.url}
                alt={image.alt || `Product image ${index + 1}`}
                className="w-full h-full object-cover"
              />
              <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
                {!image.isPrimary && (
                  <Button
                    variant="ghost"
                    size="icon-sm"
                    className="text-white hover:bg-white/20"
                    onClick={() => setPrimaryImage(image.id)}
                  >
                    <span className="sr-only">Set as primary</span>⭐
                  </Button>
                )}
                <Button
                  variant="ghost"
                  size="icon-sm"
                  className="text-white hover:bg-white/20"
                  onClick={() => removeImage(image.id, image.url)}
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
              {image.isPrimary && (
                <div className="absolute top-1 left-1">
                  <span className="rounded-full bg-green-500/90 px-1.5 py-0.5 text-[10px] font-medium text-white">
                    Primary
                  </span>
                </div>
              )}
            </div>
            <Input
              type="text"
              value={image.alt}
              onChange={(e) =>
                onChange(
                  images.map((img) =>
                    img.id === image.id ? { ...img, alt: e.target.value } : img,
                  ),
                )
              }
              placeholder="Alt text"
              className="mt-1.5 text-xs"
            />
          </div>
        ))}

        {images.length < maxImages && (
          <button
            type="button"
            onClick={() => fileInputRef.current?.click()}
            disabled={uploading}
            className="relative aspect-square rounded-lg border-2 border-dashed border-border bg-muted/50 flex flex-col items-center justify-center gap-2 p-4 transition-colors hover:border-primary hover:bg-primary/5 disabled:pointer-events-none disabled:opacity-60"
          >
            {uploading ? (
              <Loader2 className="h-6 w-6 text-muted-foreground animate-spin" />
            ) : (
              <ImagePlus className="h-6 w-6 text-muted-foreground" />
            )}
            <span className="text-xs text-muted-foreground">
              {uploading ? "Uploading…" : "Add images"}
            </span>
          </button>
        )}
      </div>

      {uploadError && (
        <p className="text-sm text-destructive" role="alert">
          {uploadError}
        </p>
      )}

      {images.length > 1 && (
        <div className="space-y-2">
          <p className="text-xs text-muted-foreground">
            Reorder with the arrows (first image is featured):
          </p>
          <div className="flex flex-wrap gap-2">
            {images.map((image, index) => (
              <div
                key={image.id}
                className="flex items-center gap-0.5 rounded-lg border border-border bg-card py-1 pl-2 pr-1 text-sm"
              >
                <button
                  type="button"
                  onClick={() => moveImage(index, "up")}
                  disabled={index === 0}
                  aria-label="Move image earlier"
                  className="rounded p-1 text-muted-foreground transition-colors hover:text-foreground hover:bg-muted disabled:opacity-40"
                >
                  <ChevronLeft className="h-4 w-4" />
                </button>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={image.url}
                  alt=""
                  className="h-5 w-5 rounded object-cover"
                />
                <span className="mx-1 truncate max-w-[110px]">
                  {image.alt || `Image ${index + 1}`}
                </span>
                <button
                  type="button"
                  onClick={() => moveImage(index, "down")}
                  disabled={index === images.length - 1}
                  aria-label="Move image later"
                  className="rounded p-1 text-muted-foreground transition-colors hover:text-foreground hover:bg-muted disabled:opacity-40"
                >
                  <ChevronRight className="h-4 w-4" />
                </button>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
