"use client";

import { useState, useRef, useMemo } from "react";
import {
  Plus,
  Pencil,
  Trash2,
  Search,
  PenTool,
  Stamp,
  History,
  Upload,
  X,
  Download,
  FileText,
  FileDown,
  ChevronDown,
} from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import { Badge } from "@/shared/components/ui/badge";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu";
import type { CompanyId } from "@/core/auth/types";
import type { SignatureAsset, SignatureAssetType } from "../types";
import { DEFAULT_SUBCATEGORIES } from "../types";
import { useSignatures } from "../hooks/use-signatures";

// --------------- constants ---------------

const TYPE_LABELS: Record<SignatureAssetType, string> = {
  signature: "Semnătură",
  stamp: "Ștampilă",
};

const TYPE_ICONS: Record<SignatureAssetType, typeof PenTool> = {
  signature: PenTool,
  stamp: Stamp,
};

// --------------- TIFF -> PNG preview ---------------

async function decodeTiffToPreview(file: File): Promise<string> {
  const UTIF = await import("utif2");
  const buffer = await file.arrayBuffer();
  const ifds = UTIF.decode(buffer);
  if (ifds.length === 0) throw new Error("TIFF gol");
  const page = ifds[0]!;
  UTIF.decodeImage(buffer, page);
  const rgba = UTIF.toRGBA8(page);

  const canvas = document.createElement("canvas");
  canvas.width = page.width;
  canvas.height = page.height;
  const ctx = canvas.getContext("2d")!;
  const imageData = ctx.createImageData(page.width, page.height);
  imageData.data.set(rgba);
  ctx.putImageData(imageData, 0, 0);
  return canvas.toDataURL("image/png");
}

// --------------- download helpers ---------------

function triggerDownload(url: string, filename: string) {
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

function downloadOriginal(asset: SignatureAsset) {
  const dataUrl = asset.originalFileData || asset.imageUrl;
  if (!dataUrl) return;
  const name = asset.originalFileName || `${asset.label}.png`;
  triggerDownload(dataUrl, name);
}

async function downloadAsWord(asset: SignatureAsset) {
  const { Document, Packer, Paragraph, ImageRun } = await import("docx");

  // Use preview (PNG/JPG) for Word since TIFF is not supported
  const dataUrl = asset.imageUrl;
  if (!dataUrl) return;

  const base64 = dataUrl.split(",")[1];
  if (!base64) return;
  const binary = atob(base64);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);

  // Load image to get natural dimensions
  const img = new Image();
  await new Promise<void>((resolve) => {
    img.onload = () => resolve();
    img.onerror = () => resolve();
    img.src = dataUrl;
  });

  const maxW = 400;
  const ratio = img.naturalHeight / (img.naturalWidth || 1);
  const w = Math.min(maxW, img.naturalWidth || 200);
  const h = Math.round(w * ratio);

  const doc = new Document({
    sections: [
      {
        children: [
          new Paragraph({
            children: [
              new ImageRun({
                data: bytes,
                transformation: { width: w, height: h },
                type: dataUrl.includes("image/png") ? "png" : "jpg",
              }),
            ],
          }),
        ],
      },
    ],
  });

  const blob = await Packer.toBlob(doc);
  const objUrl = URL.createObjectURL(blob);
  triggerDownload(objUrl, `${asset.label}.docx`);
  URL.revokeObjectURL(objUrl);
}

async function downloadAsPdf(asset: SignatureAsset) {
  const { jsPDF } = await import("jspdf");

  const dataUrl = asset.imageUrl;
  if (!dataUrl) return;

  // Load image to get natural dimensions
  const img = new Image();
  await new Promise<void>((resolve) => {
    img.onload = () => resolve();
    img.onerror = () => resolve();
    img.src = dataUrl;
  });

  const doc = new jsPDF();
  const pageW = doc.internal.pageSize.getWidth();
  const maxW = pageW - 40;
  const ratio = img.naturalHeight / (img.naturalWidth || 1);
  const w = Math.min(maxW, 120);
  const h = w * ratio;

  const format = dataUrl.includes("image/png") ? "PNG" : "JPEG";
  doc.addImage(dataUrl, format, 20, 20, w, h);
  doc.save(`${asset.label}.pdf`);
}

// --------------- main module ---------------

type ViewMode = "list" | "add" | "edit";

export function DigitalSignaturesModule() {
  const {
    assets,
    allAssets,
    loading,
    filters,
    updateFilter,
    addAsset,
    updateAsset,
    addVersion,
    removeAsset,
  } = useSignatures();
  const [viewMode, setViewMode] = useState<ViewMode>("list");
  const [editingAsset, setEditingAsset] = useState<SignatureAsset | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [versionAsset, setVersionAsset] = useState<SignatureAsset | null>(null);

  // Collect unique subcategories from all assets + defaults
  const allSubcategories = useMemo(() => {
    const set = new Set<string>(DEFAULT_SUBCATEGORIES);
    for (const a of allAssets) {
      if (a.subcategory) set.add(a.subcategory);
    }
    return Array.from(set).sort();
  }, [allAssets]);

  // Group filtered assets by subcategory
  const groupedAssets = useMemo(() => {
    const groups = new Map<string, SignatureAsset[]>();
    for (const a of assets) {
      const key = a.subcategory || "Fără subcategorie";
      const list = groups.get(key) ?? [];
      list.push(a);
      groups.set(key, list);
    }
    // Sort groups alphabetically, "Fara subcategorie" last
    return Array.from(groups.entries()).sort((a, b) => {
      if (a[0] === "Fără subcategorie") return 1;
      if (b[0] === "Fără subcategorie") return -1;
      return a[0].localeCompare(b[0]);
    });
  }, [assets]);

  const handleSubmit = async (
    data: Omit<SignatureAsset, "id" | "createdAt" | "updatedAt">,
  ) => {
    if (viewMode === "edit" && editingAsset) {
      await updateAsset(editingAsset.id, data);
    } else {
      await addAsset(data);
    }
    setViewMode("list");
    setEditingAsset(null);
  };

  const handleDeleteConfirm = async () => {
    if (deletingId) {
      await removeAsset(deletingId);
      setDeletingId(null);
    }
  };

  const handleAddVersion = async (imageUrl: string, notes: string) => {
    if (versionAsset) {
      await addVersion(versionAsset.id, imageUrl, notes);
      setVersionAsset(null);
    }
  };

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
        <Card>
          <CardContent className="p-4">
            <p className="text-xs text-muted-foreground">Total</p>
            <p className="text-2xl font-bold">{allAssets.length}</p>
          </CardContent>
        </Card>
        {(Object.keys(TYPE_LABELS) as SignatureAssetType[]).map((type) => (
          <Card key={type}>
            <CardContent className="p-4">
              <p className="text-xs text-muted-foreground">
                {TYPE_LABELS[type]}
              </p>
              <p className="text-2xl font-bold">
                {allAssets.filter((a) => a.type === type).length}
              </p>
            </CardContent>
          </Card>
        ))}
      </div>

      {viewMode === "list" && (
        <>
          {/* Filters */}
          <div className="flex flex-wrap items-center gap-3">
            <div className="relative min-w-[200px] flex-1">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Caută..."
                value={filters.search}
                onChange={(e) => updateFilter("search", e.target.value)}
                className="pl-9"
              />
            </div>
            <Select
              value={filters.type}
              onValueChange={(v) =>
                updateFilter("type", v as SignatureAssetType | "all")
              }
            >
              <SelectTrigger className="w-[150px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Toate tipurile</SelectItem>
                {(Object.keys(TYPE_LABELS) as SignatureAssetType[]).map((t) => (
                  <SelectItem key={t} value={t}>
                    {TYPE_LABELS[t]}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select
              value={filters.subcategory || "__all__"}
              onValueChange={(v) =>
                updateFilter("subcategory", v === "__all__" ? "" : v)
              }
            >
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="Subcategorie" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="__all__">Toate subcategoriile</SelectItem>
                {allSubcategories.map((s) => (
                  <SelectItem key={s} value={s}>
                    {s}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Button onClick={() => setViewMode("add")} className="shrink-0">
              <Plus className="mr-1.5 h-4 w-4" /> Adaugă
            </Button>
          </div>

          {/* Asset list grouped by subcategory */}
          {loading ? (
            <p className="py-8 text-center text-sm text-muted-foreground">
              Se încarcă...
            </p>
          ) : assets.length === 0 ? (
            <p className="py-8 text-center text-sm text-muted-foreground">
              Niciun element găsit. Adaugă o semnătură sau ștampilă.
            </p>
          ) : (
            <div className="space-y-6">
              {groupedAssets.map(([group, items]) => (
                <div key={group}>
                  <h3 className="mb-3 text-sm font-medium text-muted-foreground">
                    {group} <span className="text-xs">({items.length})</span>
                  </h3>
                  <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                    {items.map((asset) => (
                      <AssetCard
                        key={asset.id}
                        asset={asset}
                        onEdit={() => {
                          setEditingAsset(asset);
                          setViewMode("edit");
                        }}
                        onDelete={() => setDeletingId(asset.id)}
                        onVersion={() => setVersionAsset(asset)}
                      />
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </>
      )}

      {(viewMode === "add" || viewMode === "edit") && (
        <Card>
          <CardHeader>
            <CardTitle>
              {viewMode === "edit" ? "Editare" : "Element nou"}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <AssetForm
              initial={editingAsset ?? undefined}
              allSubcategories={allSubcategories}
              onSubmit={handleSubmit}
              onCancel={() => {
                setViewMode("list");
                setEditingAsset(null);
              }}
            />
          </CardContent>
        </Card>
      )}

      {/* Delete confirmation */}
      <Dialog
        open={deletingId !== null}
        onOpenChange={(open) => {
          if (!open) setDeletingId(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Confirmare ștergere</DialogTitle>
          </DialogHeader>
          <p className="text-sm">
            Ești sigur că vrei să ștergi acest element? Acțiunea este
            ireversibilă.
          </p>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeletingId(null)}>
              Anulează
            </Button>
            <Button variant="destructive" onClick={handleDeleteConfirm}>
              Șterge
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Add version dialog */}
      <Dialog
        open={versionAsset !== null}
        onOpenChange={(open) => {
          if (!open) setVersionAsset(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Versiune nouă — {versionAsset?.label}</DialogTitle>
          </DialogHeader>
          <AddVersionForm
            onSubmit={handleAddVersion}
            onCancel={() => setVersionAsset(null)}
            history={versionAsset?.versions ?? []}
          />
        </DialogContent>
      </Dialog>
    </div>
  );
}

// --------------- asset card ---------------

function AssetCard({
  asset,
  onEdit,
  onDelete,
  onVersion,
}: {
  asset: SignatureAsset;
  onEdit: () => void;
  onDelete: () => void;
  onVersion: () => void;
}) {
  const Icon = TYPE_ICONS[asset.type];

  return (
    <Card className="group relative">
      <CardContent className="p-4">
        {/* Hover actions */}
        <div className="absolute right-2 top-2 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7"
            title="Versiune nouă"
            onClick={onVersion}
          >
            <History className="h-3.5 w-3.5" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7"
            onClick={onEdit}
          >
            <Pencil className="h-3.5 w-3.5" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7 text-destructive"
            onClick={onDelete}
          >
            <Trash2 className="h-3.5 w-3.5" />
          </Button>
        </div>

        {/* Image + label */}
        <div className="flex items-center gap-3">
          <div className="flex h-12 w-12 items-center justify-center rounded-lg border bg-muted/30">
            {asset.imageUrl ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={asset.imageUrl}
                alt={asset.label}
                className="max-h-10 max-w-10 object-contain"
              />
            ) : (
              <Icon className="h-6 w-6 text-muted-foreground" />
            )}
          </div>
          <div className="min-w-0 flex-1">
            <p className="font-medium">{asset.label}</p>
            <div className="flex flex-wrap items-center gap-1">
              <Badge variant="outline" className="text-[10px]">
                {TYPE_LABELS[asset.type]}
              </Badge>
              <span className="text-xs text-muted-foreground">
                {asset.owner}
              </span>
            </div>
          </div>
        </div>

        {/* Metadata */}
        <div className="mt-2 space-y-1">
          {(asset.versions ?? []).length > 0 && (
            <p className="text-xs text-muted-foreground">
              Versiuni: {(asset.versions ?? []).length + 1}
            </p>
          )}
        </div>

        {/* Download buttons */}
        {asset.imageUrl && (
          <div className="mt-3 border-t pt-2">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="outline"
                  size="sm"
                  className="h-7 w-full text-xs"
                >
                  <Download className="mr-1.5 h-3 w-3" />
                  Descarcă
                  <ChevronDown className="ml-auto h-3 w-3" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="start">
                <DropdownMenuItem onClick={() => downloadOriginal(asset)}>
                  <FileDown className="mr-2 h-4 w-4" />
                  <span>Original</span>
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => void downloadAsWord(asset)}>
                  <FileText className="mr-2 h-4 w-4" />
                  <span>Word (.docx)</span>
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => void downloadAsPdf(asset)}>
                  <FileDown className="mr-2 h-4 w-4" />
                  <span>PDF (.pdf)</span>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

// --------------- image upload (TIFF support) ---------------

function ImageUploadField({
  value,
  onChange,
  onOriginalFile,
}: {
  value: string;
  onChange: (previewUrl: string) => void;
  onOriginalFile?: (dataUrl: string, fileName: string) => void;
}) {
  const fileRef = useRef<HTMLInputElement>(null);
  const [processing, setProcessing] = useState(false);

  const handleFile = async (file: File) => {
    const isTiff = file.type === "image/tiff" || /\.tiff?$/i.test(file.name);

    if (isTiff) {
      setProcessing(true);
      try {
        const previewUrl = await decodeTiffToPreview(file);
        onChange(previewUrl);

        // Also store original TIFF
        if (onOriginalFile) {
          const reader = new FileReader();
          reader.onload = (e) =>
            onOriginalFile(e.target?.result as string, file.name);
          reader.readAsDataURL(file);
        }
      } catch {
        // Fallback: try as regular image
        const reader = new FileReader();
        reader.onload = (e) => {
          const url = e.target?.result as string;
          onChange(url);
          if (onOriginalFile) onOriginalFile(url, file.name);
        };
        reader.readAsDataURL(file);
      } finally {
        setProcessing(false);
      }
    } else if (file.type.startsWith("image/")) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const url = e.target?.result as string;
        onChange(url);
        if (onOriginalFile) onOriginalFile(url, file.name);
      };
      reader.readAsDataURL(file);
    }
  };

  return (
    <div className="space-y-2">
      <div
        className="flex min-h-[100px] cursor-pointer flex-col items-center justify-center gap-2 rounded-md border-2 border-dashed p-3 text-sm text-muted-foreground transition-colors hover:border-primary/50"
        onClick={() => fileRef.current?.click()}
        onDragOver={(e) => e.preventDefault()}
        onDrop={(e) => {
          e.preventDefault();
          const f = e.dataTransfer.files[0];
          if (f) void handleFile(f);
        }}
      >
        {processing ? (
          <span className="animate-pulse">Se procesează TIFF...</span>
        ) : value ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={value}
            alt="preview"
            className="max-h-24 max-w-full object-contain"
          />
        ) : (
          <>
            <Upload className="h-6 w-6" />
            <span>Trage imaginea aici sau apasă pentru a selecta</span>
            <span className="text-xs text-muted-foreground/60">
              PNG, JPG, TIFF
            </span>
          </>
        )}
      </div>
      <input
        ref={fileRef}
        type="file"
        accept="image/*,.tif,.tiff"
        className="hidden"
        onChange={(e) => {
          const f = e.target.files?.[0];
          if (f) void handleFile(f);
        }}
      />
      {value && (
        <Button
          type="button"
          variant="ghost"
          size="sm"
          className="text-xs text-muted-foreground"
          onClick={() => {
            onChange("");
            if (onOriginalFile) onOriginalFile("", "");
          }}
        >
          <X className="mr-1 h-3 w-3" /> Elimină imaginea
        </Button>
      )}
    </div>
  );
}

// --------------- add version form ---------------

function AddVersionForm({
  onSubmit,
  onCancel,
  history,
}: {
  onSubmit: (imageUrl: string, notes: string) => void;
  onCancel: () => void;
  history: Array<{
    id: string;
    imageUrl: string;
    notes: string;
    createdAt: string;
  }>;
}) {
  const [imageUrl, setImageUrl] = useState("");
  const [notes, setNotes] = useState("");

  return (
    <div className="space-y-4">
      {history.length > 0 && (
        <div className="max-h-32 space-y-1 overflow-y-auto rounded border p-2">
          <p className="text-xs font-medium text-muted-foreground">
            Istoric versiuni
          </p>
          {history.map((v) => (
            <div
              key={v.id}
              className="flex items-center justify-between text-xs"
            >
              <span className="truncate text-muted-foreground">
                {v.notes || "Fără note"}
              </span>
              <span className="shrink-0 text-muted-foreground">
                {v.createdAt.slice(0, 10)}
              </span>
            </div>
          ))}
        </div>
      )}
      <div>
        <Label>Imagine nouă</Label>
        <div className="mt-1">
          <ImageUploadField value={imageUrl} onChange={setImageUrl} />
        </div>
      </div>
      <div>
        <Label>Note versiune</Label>
        <Input
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          className="mt-1"
          placeholder="Ce s-a schimbat..."
        />
      </div>
      <div className="flex justify-end gap-2">
        <Button variant="outline" onClick={onCancel}>
          Anulează
        </Button>
        <Button
          onClick={() => {
            if (imageUrl.trim()) onSubmit(imageUrl, notes);
          }}
          disabled={!imageUrl.trim()}
        >
          Salvează versiune
        </Button>
      </div>
    </div>
  );
}

// --------------- asset form ---------------

function AssetForm({
  initial,
  allSubcategories,
  onSubmit,
  onCancel,
}: {
  initial?: SignatureAsset;
  allSubcategories: string[];
  onSubmit: (
    data: Omit<SignatureAsset, "id" | "createdAt" | "updatedAt">,
  ) => void;
  onCancel: () => void;
}) {
  const [label, setLabel] = useState(initial?.label ?? "");
  const [type, setType] = useState<SignatureAssetType>(
    initial?.type ?? "signature",
  );
  const [imageUrl, setImageUrl] = useState(initial?.imageUrl ?? "");
  const [originalFileData, setOriginalFileData] = useState(
    initial?.originalFileData ?? "",
  );
  const [originalFileName, setOriginalFileName] = useState(
    initial?.originalFileName ?? "",
  );
  const [owner, setOwner] = useState(initial?.owner ?? "");
  const [company, setCompany] = useState<CompanyId>(
    initial?.company ?? "beletage",
  );
  const [subcategory, setSubcategory] = useState(initial?.subcategory ?? "");
  const [tags, setTags] = useState<string[]>(initial?.tags ?? []);
  const [tagInput, setTagInput] = useState("");

  const addTag = (raw: string) => {
    const t = raw.trim().toLowerCase();
    if (t && !tags.includes(t)) setTags((prev) => [...prev, t]);
    setTagInput("");
  };

  const handleTagKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter" || e.key === ",") {
      e.preventDefault();
      addTag(tagInput);
    }
    if (e.key === "Backspace" && tagInput === "" && tags.length > 0)
      setTags((prev) => prev.slice(0, -1));
  };

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        onSubmit({
          label,
          type,
          imageUrl,
          originalFileData: originalFileData || undefined,
          originalFileName: originalFileName || undefined,
          owner,
          company,
          subcategory,
          versions: initial?.versions ?? [],
          tags,
          visibility: initial?.visibility ?? "all",
        });
      }}
      className="space-y-4"
    >
      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label>Denumire *</Label>
          <Input
            value={label}
            onChange={(e) => setLabel(e.target.value)}
            className="mt-1"
            required
          />
        </div>
        <div>
          <Label>Tip</Label>
          <Select
            value={type}
            onValueChange={(v) => setType(v as SignatureAssetType)}
          >
            <SelectTrigger className="mt-1">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="signature">Semnătură</SelectItem>
              <SelectItem value="stamp">Ștampilă</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>
      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label>Proprietar</Label>
          <Input
            value={owner}
            onChange={(e) => setOwner(e.target.value)}
            className="mt-1"
          />
        </div>
        <div>
          <Label>Companie</Label>
          <Select
            value={company}
            onValueChange={(v) => setCompany(v as CompanyId)}
          >
            <SelectTrigger className="mt-1">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="beletage">Beletage</SelectItem>
              <SelectItem value="urban-switch">Urban Switch</SelectItem>
              <SelectItem value="studii-de-teren">Studii de Teren</SelectItem>
              <SelectItem value="group">Grup</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>
      <div>
        <Label>Subcategorie</Label>
        <div className="mt-1">
          <Input
            list="ds-subcategories"
            value={subcategory}
            onChange={(e) => setSubcategory(e.target.value)}
            placeholder="Selectează sau scrie o subcategorie..."
          />
          <datalist id="ds-subcategories">
            {allSubcategories.map((s) => (
              <option key={s} value={s} />
            ))}
          </datalist>
        </div>
      </div>
      <div>
        <Label>Imagine</Label>
        <div className="mt-1">
          <ImageUploadField
            value={imageUrl}
            onChange={setImageUrl}
            onOriginalFile={(data, name) => {
              setOriginalFileData(data);
              setOriginalFileName(name);
            }}
          />
        </div>
      </div>
      <div>
        <Label>Etichete</Label>
        <div className="mt-1 flex min-h-[38px] flex-wrap items-center gap-1.5 rounded-md border bg-background px-2 py-1.5 focus-within:ring-1 focus-within:ring-ring">
          {tags.map((tag) => (
            <span
              key={tag}
              className="flex items-center gap-0.5 rounded-full border bg-muted px-2 py-0.5 text-xs"
            >
              {tag}
              <button
                type="button"
                onClick={() => setTags((t) => t.filter((x) => x !== tag))}
                className="ml-0.5 opacity-60 hover:opacity-100"
              >
                <X className="h-2.5 w-2.5" />
              </button>
            </span>
          ))}
          <input
            value={tagInput}
            onChange={(e) => setTagInput(e.target.value)}
            onKeyDown={handleTagKeyDown}
            onBlur={() => {
              if (tagInput.trim()) addTag(tagInput);
            }}
            placeholder={
              tags.length === 0 ? "Adaugă etichete (Enter sau virgulă)..." : ""
            }
            className="min-w-[120px] flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
          />
        </div>
      </div>
      <div className="flex justify-end gap-2 pt-2">
        <Button type="button" variant="outline" onClick={onCancel}>
          Anulează
        </Button>
        <Button type="submit">{initial ? "Actualizează" : "Adaugă"}</Button>
      </div>
    </form>
  );
}
