"use client";

import { useState, useMemo, useEffect, useRef } from "react";
import {
  Plus,
  Pencil,
  Trash2,
  Search,
  Eye,
  EyeOff,
  Copy,
  ExternalLink,
  KeyRound,
  X,
  Globe,
  Mail,
  Wifi,
  Building2,
  FileCheck2,
  Fingerprint,
  Monitor,
  HardDrive,
  MoreHorizontal,
  QrCode,
  Users,
  UserPlus,
  ChevronDown,
  ChevronUp,
} 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 { Textarea } from "@/shared/components/ui/textarea";
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 { Switch } from "@/shared/components/ui/switch";
import type { CompanyId } from "@/core/auth/types";
import type { VaultEntry, VaultEntryCategory, CustomField, VaultUser } from "../types";
import { useVault } from "../hooks/use-vault";

// Category definitions with icons

interface CategoryDef {
  id: VaultEntryCategory;
  label: string;
  icon: React.ComponentType<{ className?: string }>;
  description: string;
}

const CATEGORY_DEFS: CategoryDef[] = [
  {
    id: "web",
    label: "Web",
    icon: Globe as unknown as React.ComponentType<{ className?: string }>,
    description: "Conturi web și platforme online",
  },
  {
    id: "email",
    label: "Email",
    icon: Mail as unknown as React.ComponentType<{ className?: string }>,
    description: "Conturi de email",
  },
  {
    id: "wifi",
    label: "WiFi",
    icon: Wifi as unknown as React.ComponentType<{ className?: string }>,
    description: "Rețele WiFi și parole de acces",
  },
  {
    id: "portale-primarii",
    label: "Portale Primării",
    icon: Building2 as unknown as React.ComponentType<{ className?: string }>,
    description: "Conturi portal urbanism",
  },
  {
    id: "avize-online",
    label: "Avize Online",
    icon: FileCheck2 as unknown as React.ComponentType<{ className?: string }>,
    description: "Platforme solicitare avize",
  },
  {
    id: "pin-semnatura",
    label: "PIN Semnătură",
    icon: Fingerprint as unknown as React.ComponentType<{ className?: string }>,
    description: "PIN-uri semnătură electronică",
  },
  {
    id: "software",
    label: "Software",
    icon: Monitor as unknown as React.ComponentType<{ className?: string }>,
    description: "Conturi software (ArchiCAD, Twinmotion etc.)",
  },
  {
    id: "hardware",
    label: "Echipament HW",
    icon: HardDrive as unknown as React.ComponentType<{ className?: string }>,
    description: "iDRAC, PCoIP, VM, ZeroClient",
  },
  {
    id: "other",
    label: "Altele",
    icon: MoreHorizontal as unknown as React.ComponentType<{
      className?: string;
    }>,
    description: "Alte credențiale",
  },
];

const CATEGORY_MAP = new Map(CATEGORY_DEFS.map((c) => [c.id, c]));

function getCategoryDef(id: string): CategoryDef {
  return (
    CATEGORY_MAP.get(id as VaultEntryCategory) ??
    CATEGORY_DEFS[CATEGORY_DEFS.length - 1]!
  );
}

const COMPANY_LABELS: Record<CompanyId, string> = {
  beletage: "Beletage",
  "urban-switch": "Urban Switch",
  "studii-de-teren": "Studii de Teren",
  group: "Grup",
};

/** Calculate password strength: 0-3 (weak, medium, strong, very strong) */
function getPasswordStrength(pwd: string): {
  level: 0 | 1 | 2 | 3;
  label: string;
  color: string;
} {
  if (!pwd) return { level: 0, label: "Nicio parolă", color: "bg-gray-300" };
  const len = pwd.length;
  const hasUpper = /[A-Z]/.test(pwd);
  const hasLower = /[a-z]/.test(pwd);
  const hasDigit = /\d/.test(pwd);
  const hasSymbol = /[!@#$%^&*()\-_=+\[\]{}|;:,.<>?]/.test(pwd);
  const varietyScore =
    (hasUpper ? 1 : 0) +
    (hasLower ? 1 : 0) +
    (hasDigit ? 1 : 0) +
    (hasSymbol ? 1 : 0);
  const score = len + varietyScore * 2;
  if (score < 8) return { level: 0, label: "Slabă", color: "bg-red-500" };
  if (score < 16) return { level: 1, label: "Medie", color: "bg-yellow-500" };
  if (score < 24)
    return { level: 2, label: "Puternică", color: "bg-green-500" };
  return { level: 3, label: "Foarte puternică", color: "bg-emerald-600" };
}

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

/** Generate a random password */
function generatePassword(
  length: number,
  options: {
    upper: boolean;
    lower: boolean;
    digits: boolean;
    symbols: boolean;
  },
): string {
  let chars = "";
  if (options.upper) chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  if (options.lower) chars += "abcdefghijklmnopqrstuvwxyz";
  if (options.digits) chars += "0123456789";
  if (options.symbols) chars += "!@#$%^&*()-_=+[]{}|;:,.<>?";
  if (!chars)
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let result = "";
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

export function PasswordVaultModule() {
  const {
    entries,
    allEntries,
    loading,
    filters,
    updateFilter,
    addEntry,
    updateEntry,
    removeEntry,
  } = useVault();
  const [viewMode, setViewMode] = useState<ViewMode>("list");
  const [editingEntry, setEditingEntry] = useState<VaultEntry | null>(null);
  const [visiblePasswords, setVisiblePasswords] = useState<Set<string>>(
    new Set(),
  );
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [qrEntry, setQrEntry] = useState<VaultEntry | null>(null);

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

  const handleCopy = async (text: string, id: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedId(id);
      setTimeout(() => setCopiedId(null), 2000);
    } catch {
      /* silent */
    }
  };

  const handleSubmit = async (
    data: Omit<VaultEntry, "id" | "createdAt" | "updatedAt">,
  ) => {
    if (viewMode === "edit" && editingEntry) {
      await updateEntry(editingEntry.id, data);
    } else {
      await addEntry(data);
    }
    setViewMode("list");
    setEditingEntry(null);
    updateFilter("category", "all");
    updateFilter("search", "");
  };

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

  // Group entries by category for stats
  const categoryStats = useMemo(() => {
    const stats = new Map<string, number>();
    for (const e of allEntries)
      stats.set(e.category, (stats.get(e.category) ?? 0) + 1);
    return stats;
  }, [allEntries]);

  // Top 3 categories for stat cards
  const topCategories = useMemo(() => {
    const sorted = [...categoryStats.entries()]
      .sort((a, b) => b[1] - a[1])
      .slice(0, 3);
    return sorted;
  }, [categoryStats]);

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <Card>
          <CardContent className="p-4">
            <p className="text-xs text-muted-foreground">Total</p>
            <p className="text-2xl font-bold">{allEntries.length}</p>
          </CardContent>
        </Card>
        {topCategories.map(([catId, count]) => {
          const def = getCategoryDef(catId);
          const Icon = def.icon;
          return (
            <Card key={catId}>
              <CardContent className="p-4">
                <p className="text-xs text-muted-foreground flex items-center gap-1">
                  <Icon className="h-3 w-3" />
                  {def.label}
                </p>
                <p className="text-2xl font-bold">{count}</p>
              </CardContent>
            </Card>
          );
        })}
      </div>

      {viewMode === "list" && (
        <>
          <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.category}
              onValueChange={(v) =>
                updateFilter("category", v as VaultEntryCategory | "all")
              }
            >
              <SelectTrigger className="w-[180px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Toate categoriile</SelectItem>
                {CATEGORY_DEFS.map((c) => {
                  const Icon = c.icon;
                  return (
                    <SelectItem key={c.id} value={c.id}>
                      <span className="flex items-center gap-1.5">
                        <Icon className="h-3.5 w-3.5" />
                        {c.label}
                      </span>
                    </SelectItem>
                  );
                })}
              </SelectContent>
            </Select>
            <Button onClick={() => setViewMode("add")} className="shrink-0">
              <Plus className="mr-1.5 h-4 w-4" /> Adaugă
            </Button>
          </div>

          {loading ? (
            <p className="py-8 text-center text-sm text-muted-foreground">
              Se încarcă...
            </p>
          ) : entries.length === 0 ? (
            <p className="py-8 text-center text-sm text-muted-foreground">
              Nicio intrare găsită.
            </p>
          ) : (
            <div className="space-y-2">
              {entries.map((entry) => {
                const catDef = getCategoryDef(entry.category);
                const CatIcon = catDef.icon;
                return (
                  <Card key={entry.id} className="group">
                    <CardContent className="flex items-center gap-4 p-4">
                      {/* Category icon */}
                      <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-muted shrink-0">
                        <CatIcon className="h-4.5 w-4.5 text-muted-foreground" />
                      </div>

                      <div className="min-w-0 flex-1 space-y-1">
                        <div className="flex items-center gap-2">
                          <p className="font-medium">{entry.label}</p>
                          <Badge variant="outline" className="text-[10px]">
                            {catDef.label}
                          </Badge>
                        </div>
                        <p className="text-xs text-muted-foreground">
                          {entry.username}
                          {entry.email && (
                            <span className="ml-2 text-muted-foreground/70">
                              ({entry.email})
                            </span>
                          )}
                        </p>
                        <div className="flex items-center gap-2">
                          <code className="text-xs">
                            {visiblePasswords.has(entry.id)
                              ? entry.password
                              : String.fromCharCode(8226).repeat(10)}
                          </code>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-5 w-5"
                            onClick={() => togglePassword(entry.id)}
                          >
                            {visiblePasswords.has(entry.id) ? (
                              <EyeOff className="h-3 w-3" />
                            ) : (
                              <Eye className="h-3 w-3" />
                            )}
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-5 w-5"
                            onClick={() => handleCopy(entry.password, entry.id)}
                          >
                            <Copy className="h-3 w-3" />
                          </Button>
                          {copiedId === entry.id && (
                            <span className="text-[10px] text-green-500">
                              Copiat!
                            </span>
                          )}
                        </div>
                        {entry.url && (
                          <a
                            href={
                              entry.url.startsWith("http")
                                ? entry.url
                                : `https://${entry.url}`
                            }
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center gap-1 text-xs text-primary hover:underline"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <ExternalLink className="h-3 w-3" /> {entry.url}
                          </a>
                        )}
                        {entry.customFields &&
                          entry.customFields.length > 0 && (
                            <div className="mt-1 flex flex-wrap gap-1">
                              {entry.customFields.map((cf, i) => (
                                <Badge
                                  key={i}
                                  variant="secondary"
                                  className="text-[10px]"
                                >
                                  {cf.key}: {cf.value}
                                </Badge>
                              ))}
                            </div>
                          )}
                        {entry.additionalUsers &&
                          entry.additionalUsers.length > 0 && (
                            <Badge
                              variant="outline"
                              className="text-[10px] gap-1"
                            >
                              <Users className="h-2.5 w-2.5" />
                              +{entry.additionalUsers.length} utilizator
                              {entry.additionalUsers.length > 1 ? "i" : ""}
                            </Badge>
                          )}
                      </div>
                      <div className="flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
                        {/* WiFi QR button */}
                        {entry.category === "wifi" && entry.password && (
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-7 w-7"
                            onClick={() => setQrEntry(entry)}
                            title="QR Code WiFi"
                          >
                            <QrCode className="h-3.5 w-3.5" />
                          </Button>
                        )}
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-7 w-7"
                          onClick={() => {
                            setEditingEntry(entry);
                            setViewMode("edit");
                          }}
                        >
                          <Pencil className="h-3.5 w-3.5" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-7 w-7 text-destructive"
                          onClick={() => setDeletingId(entry.id)}
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}
        </>
      )}

      {(viewMode === "add" || viewMode === "edit") && (
        <Card>
          <CardHeader>
            <CardTitle>
              {viewMode === "edit" ? "Editare" : "Intrare nouă"}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <VaultForm
              initial={editingEntry ?? undefined}
              onSubmit={handleSubmit}
              onCancel={() => {
                setViewMode("list");
                setEditingEntry(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 această intrare? Acțiunea este
            ireversibilă.
          </p>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeletingId(null)}>
              Anulează
            </Button>
            <Button variant="destructive" onClick={handleDeleteConfirm}>
              Șterge
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* WiFi QR Dialog */}
      <Dialog
        open={qrEntry !== null}
        onOpenChange={(open) => {
          if (!open) setQrEntry(null);
        }}
      >
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <QrCode className="h-5 w-5" />
              QR Code WiFi {qrEntry ? `\u2014 ${qrEntry.label}` : ""}
            </DialogTitle>
          </DialogHeader>
          {qrEntry && (
            <WifiQrDisplay
              ssid={qrEntry.label}
              password={qrEntry.password}
              onCopy={(text) => handleCopy(text, "qr-" + qrEntry.id)}
            />
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setQrEntry(null)}>
              Închide
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

// WiFi QR Code Display
function WifiQrDisplay({
  ssid,
  password,
  onCopy,
}: {
  ssid: string;
  password: string;
  onCopy: (text: string) => void;
}) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);

  // Build WIFI connection string
  const wifiString = useMemo(() => {
    const escaped = (s: string) => s.replace(/[\\;,"`:]/g, (c) => `\\${c}`);
    return `WIFI:T:WPA;S:${escaped(ssid)};P:${escaped(password)};;`;
  }, [ssid, password]);

  // Generate QR code on canvas
  useEffect(() => {
    let cancelled = false;
    async function render() {
      const QRCode = (await import("qrcode")).default;
      const canvas = canvasRef.current;
      if (!canvas || cancelled) return;
      await QRCode.toCanvas(canvas, wifiString, {
        width: 280,
        margin: 2,
        color: { dark: "#000000", light: "#ffffff" },
      });
      // Also store as data URL for copy/download
      const url = canvas.toDataURL("image/png");
      if (!cancelled) setQrDataUrl(url);
    }
    render();
    return () => {
      cancelled = true;
    };
  }, [wifiString]);

  const handleDownload = () => {
    if (!qrDataUrl) return;
    const a = document.createElement("a");
    a.href = qrDataUrl;
    a.download = `WiFi-${ssid}.png`;
    a.click();
  };

  const handleCopyImage = async () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    try {
      const blob = await new Promise<Blob | null>((res) =>
        canvas.toBlob(res, "image/png"),
      );
      if (blob) {
        await navigator.clipboard.write([
          new ClipboardItem({ "image/png": blob }),
        ]);
        onCopy("__image__");
      }
    } catch {
      // Fallback: copy the wifi string instead
      onCopy(wifiString);
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-col items-center gap-4">
        {/* QR Code canvas */}
        <div className="rounded-lg border bg-white p-4 flex flex-col items-center gap-3">
          <canvas ref={canvasRef} className="rounded" />
          <div className="text-center">
            <p className="font-medium text-base text-gray-900">{ssid}</p>
            <p className="text-xs text-gray-500 mt-0.5">
              Scanează cu telefonul pentru conectare
            </p>
          </div>
        </div>

        {/* Action buttons */}
        <div className="flex gap-2 w-full">
          <Button
            variant="outline"
            className="flex-1"
            onClick={handleCopyImage}
          >
            <Copy className="mr-1.5 h-4 w-4" /> Copiază imaginea
          </Button>
          <Button variant="outline" className="flex-1" onClick={handleDownload}>
            <ExternalLink className="mr-1.5 h-4 w-4" /> Descarcă PNG
          </Button>
        </div>

        {/* Password for quick copy */}
        <div className="w-full space-y-1">
          <Label className="text-xs text-muted-foreground">Parolă WiFi</Label>
          <div className="flex gap-2">
            <Input
              value={password}
              readOnly
              className="flex-1 font-mono text-sm"
            />
            <Button
              variant="outline"
              size="icon"
              className="shrink-0"
              onClick={() => onCopy(password)}
            >
              <Copy className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

// Vault Form
function VaultForm({
  initial,
  onSubmit,
  onCancel,
}: {
  initial?: VaultEntry;
  onSubmit: (data: Omit<VaultEntry, "id" | "createdAt" | "updatedAt">) => void;
  onCancel: () => void;
}) {
  const [label, setLabel] = useState(initial?.label ?? "");
  const [username, setUsername] = useState(initial?.username ?? "");
  const [email, setEmail] = useState(initial?.email ?? "");
  const [password, setPassword] = useState(initial?.password ?? "");
  const [url, setUrl] = useState(initial?.url ?? "");
  const [category, setCategory] = useState<VaultEntryCategory>(
    initial?.category ?? "web",
  );
  const [company, setCompany] = useState<CompanyId>(
    initial?.company ?? "beletage",
  );
  const [notes, setNotes] = useState(initial?.notes ?? "");
  const [customFields, setCustomFields] = useState<CustomField[]>(
    initial?.customFields ?? [],
  );
  const [additionalUsers, setAdditionalUsers] = useState<VaultUser[]>(
    initial?.additionalUsers ?? [],
  );
  const [showAdditionalUsers, setShowAdditionalUsers] = useState(
    (initial?.additionalUsers?.length ?? 0) > 0,
  );

  // Password generator state
  const [genLength, setGenLength] = useState(16);
  const [genUpper, setGenUpper] = useState(true);
  const [genLower, setGenLower] = useState(true);
  const [genDigits, setGenDigits] = useState(true);
  const [genSymbols, setGenSymbols] = useState(true);

  const strength = getPasswordStrength(password);

  const handleGenerate = () => {
    setPassword(
      generatePassword(genLength, {
        upper: genUpper,
        lower: genLower,
        digits: genDigits,
        symbols: genSymbols,
      }),
    );
  };

  const addCustomField = () => {
    setCustomFields([...customFields, { key: "", value: "" }]);
  };

  const updateCustomField = (
    index: number,
    field: keyof CustomField,
    value: string,
  ) => {
    setCustomFields(
      customFields.map((cf, i) =>
        i === index ? { ...cf, [field]: value } : cf,
      ),
    );
  };

  const removeCustomField = (index: number) => {
    setCustomFields(customFields.filter((_, i) => i !== index));
  };

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        onSubmit({
          label,
          username,
          email,
          password,
          url,
          category,
          company,
          notes,
          customFields: customFields.filter((cf) => cf.key.trim()),
          additionalUsers: additionalUsers.filter((u) => u.username.trim() || u.password.trim()),
          tags: initial?.tags ?? [],
          visibility: initial?.visibility ?? "admin",
        });
      }}
      className="space-y-4"
    >
      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label>Nume/Etichetă *</Label>
          <Input
            value={label}
            onChange={(e) => setLabel(e.target.value)}
            className="mt-1"
            required
            placeholder={category === "wifi" ? "Nume rețea (SSID)" : ""}
          />
        </div>
        <div>
          <Label>Categorie</Label>
          <Select
            value={category}
            onValueChange={(v) => setCategory(v as VaultEntryCategory)}
          >
            <SelectTrigger className="mt-1">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {CATEGORY_DEFS.map((c) => {
                const Icon = c.icon;
                return (
                  <SelectItem key={c.id} value={c.id}>
                    <span className="flex items-center gap-1.5">
                      <Icon className="h-3.5 w-3.5" />
                      {c.label}
                    </span>
                  </SelectItem>
                );
              })}
            </SelectContent>
          </Select>
          {CATEGORY_DEFS.find((c) => c.id === category) && (
            <p className="text-[10px] text-muted-foreground mt-0.5">
              {CATEGORY_DEFS.find((c) => c.id === category)?.description}
            </p>
          )}
        </div>
      </div>
      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label>Companie</Label>
          <Select
            value={company}
            onValueChange={(v) => setCompany(v as CompanyId)}
          >
            <SelectTrigger className="mt-1">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {(Object.keys(COMPANY_LABELS) as CompanyId[]).map((c) => (
                <SelectItem key={c} value={c}>
                  {COMPANY_LABELS[c]}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div>
          <Label>
            {category === "pin-semnatura" ? "Titular" : "Utilizator"}
          </Label>
          <Input
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            className="mt-1"
            placeholder={
              category === "pin-semnatura" ? "Numele titularului" : ""
            }
          />
        </div>
      </div>
      {category !== "wifi" && category !== "pin-semnatura" && (
        <div>
          <Label>Email</Label>
          <Input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="mt-1"
            placeholder="utilizator@exemplu.ro"
          />
        </div>
      )}
      <div>
        <Label>{category === "pin-semnatura" ? "PIN" : "Parolă"}</Label>
        <div className="mt-1 flex gap-1.5">
          <Input
            type="text"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="flex-1 font-mono text-sm"
            placeholder={
              category === "pin-semnatura" ? "PIN semnatura electronica" : ""
            }
          />
          {category !== "pin-semnatura" && (
            <Button
              type="button"
              variant="outline"
              size="icon"
              onClick={handleGenerate}
              title="Generează parolă"
            >
              <KeyRound className="h-4 w-4" />
            </Button>
          )}
        </div>
        {password && (
          <div className="mt-2 space-y-1">
            <div className="flex items-center justify-between text-xs">
              <span className="text-muted-foreground">Forță:</span>
              <span
                className={
                  strength.level === 3
                    ? "text-emerald-600 font-medium"
                    : strength.level === 2
                      ? "text-green-600 font-medium"
                      : strength.level === 1
                        ? "text-yellow-600 font-medium"
                        : "text-red-600 font-medium"
                }
              >
                {strength.label}
              </span>
            </div>
            <div className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
              <div
                className={`h-full ${strength.color} transition-all`}
                style={{ width: `${(strength.level + 1) * 25}%` }}
              />
            </div>
          </div>
        )}
      </div>

      {/* Password generator options - hide for PIN */}
      {category !== "pin-semnatura" && (
        <div className="rounded border p-3 space-y-2">
          <p className="text-xs font-medium text-muted-foreground">
            Generator parolă
          </p>
          <div className="flex flex-wrap items-center gap-4">
            <div className="flex items-center gap-2">
              <Label className="text-xs">Lungime:</Label>
              <Input
                type="number"
                value={genLength}
                onChange={(e) =>
                  setGenLength(parseInt(e.target.value, 10) || 8)
                }
                className="w-16 text-sm"
                min={4}
                max={64}
              />
            </div>
            <div className="flex items-center gap-1.5">
              <Switch
                checked={genUpper}
                onCheckedChange={setGenUpper}
                id="gen-upper"
              />
              <Label htmlFor="gen-upper" className="text-xs cursor-pointer">
                A-Z
              </Label>
            </div>
            <div className="flex items-center gap-1.5">
              <Switch
                checked={genLower}
                onCheckedChange={setGenLower}
                id="gen-lower"
              />
              <Label htmlFor="gen-lower" className="text-xs cursor-pointer">
                a-z
              </Label>
            </div>
            <div className="flex items-center gap-1.5">
              <Switch
                checked={genDigits}
                onCheckedChange={setGenDigits}
                id="gen-digits"
              />
              <Label htmlFor="gen-digits" className="text-xs cursor-pointer">
                0-9
              </Label>
            </div>
            <div className="flex items-center gap-1.5">
              <Switch
                checked={genSymbols}
                onCheckedChange={setGenSymbols}
                id="gen-symbols"
              />
              <Label htmlFor="gen-symbols" className="text-xs cursor-pointer">
                !@#$
              </Label>
            </div>
            <Button
              type="button"
              variant="secondary"
              size="sm"
              onClick={handleGenerate}
            >
              <KeyRound className="mr-1 h-3 w-3" /> Generează
            </Button>
          </div>
        </div>
      )}

      {category !== "wifi" && (
        <div>
          <Label>URL</Label>
          <Input
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            className="mt-1"
            placeholder="https://..."
          />
        </div>
      )}

      {/* Custom fields */}
      <div>
        <div className="flex items-center justify-between">
          <Label>Câmpuri personalizate</Label>
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={addCustomField}
          >
            <Plus className="mr-1 h-3 w-3" /> Adaugă câmp
          </Button>
        </div>
        {customFields.length > 0 && (
          <div className="mt-2 space-y-1.5">
            {customFields.map((cf, i) => (
              <div key={i} className="flex items-center gap-2">
                <Input
                  placeholder="Cheie"
                  value={cf.key}
                  onChange={(e) => updateCustomField(i, "key", e.target.value)}
                  className="w-[140px] text-sm"
                />
                <Input
                  placeholder="Valoare"
                  value={cf.value}
                  onChange={(e) =>
                    updateCustomField(i, "value", e.target.value)
                  }
                  className="flex-1 text-sm"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="h-7 w-7 text-destructive"
                  onClick={() => removeCustomField(i)}
                >
                  <X className="h-3.5 w-3.5" />
                </Button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Additional users */}
      <div>
        <button
          type="button"
          className="flex items-center gap-1.5 text-sm font-medium hover:text-primary transition-colors"
          onClick={() => setShowAdditionalUsers((v) => !v)}
        >
          <Users className="h-3.5 w-3.5" />
          Utilizatori suplimentari
          {additionalUsers.length > 0 && (
            <Badge variant="secondary" className="text-[10px] ml-1">
              {additionalUsers.length}
            </Badge>
          )}
          {showAdditionalUsers ? (
            <ChevronUp className="h-3.5 w-3.5 ml-auto" />
          ) : (
            <ChevronDown className="h-3.5 w-3.5 ml-auto" />
          )}
        </button>
        {showAdditionalUsers && (
          <div className="mt-2 space-y-2 rounded border p-3">
            <p className="text-[11px] text-muted-foreground">
              Adaugă credențiale suplimentare pentru același cont (ex: mai mulți angajați cu acces).
            </p>
            {additionalUsers.map((u, i) => (
              <div key={i} className="space-y-1.5 rounded-sm border p-2 relative">
                <button
                  type="button"
                  className="absolute right-1 top-1 text-destructive hover:opacity-80"
                  onClick={() =>
                    setAdditionalUsers((prev) => prev.filter((_, idx) => idx !== i))
                  }
                >
                  <X className="h-3.5 w-3.5" />
                </button>
                <p className="text-xs font-medium text-muted-foreground">
                  Utilizator {i + 1}
                </p>
                <div className="grid gap-1.5 sm:grid-cols-2">
                  <div>
                    <Label className="text-xs">Utilizator / Titular</Label>
                    <Input
                      value={u.username}
                      onChange={(e) =>
                        setAdditionalUsers((prev) =>
                          prev.map((x, idx) =>
                            idx === i ? { ...x, username: e.target.value } : x,
                          ),
                        )
                      }
                      className="mt-0.5 text-sm h-8"
                      placeholder="nume_utilizator"
                    />
                  </div>
                  <div>
                    <Label className="text-xs">Email (opțional)</Label>
                    <Input
                      type="email"
                      value={u.email ?? ""}
                      onChange={(e) =>
                        setAdditionalUsers((prev) =>
                          prev.map((x, idx) =>
                            idx === i ? { ...x, email: e.target.value } : x,
                          ),
                        )
                      }
                      className="mt-0.5 text-sm h-8"
                      placeholder="email@exemplu.ro"
                    />
                  </div>
                </div>
                <div>
                  <Label className="text-xs">Parolă</Label>
                  <Input
                    value={u.password}
                    onChange={(e) =>
                      setAdditionalUsers((prev) =>
                        prev.map((x, idx) =>
                          idx === i ? { ...x, password: e.target.value } : x,
                        ),
                      )
                    }
                    className="mt-0.5 text-sm font-mono h-8"
                    placeholder="parolă"
                  />
                </div>
                <div>
                  <Label className="text-xs">Note (opțional)</Label>
                  <Input
                    value={u.notes ?? ""}
                    onChange={(e) =>
                      setAdditionalUsers((prev) =>
                        prev.map((x, idx) =>
                          idx === i ? { ...x, notes: e.target.value } : x,
                        ),
                      )
                    }
                    className="mt-0.5 text-sm h-8"
                    placeholder="ex: contul lui Mihai"
                  />
                </div>
              </div>
            ))}
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() =>
                setAdditionalUsers((prev) => [
                  ...prev,
                  { username: "", password: "", email: "", notes: "" },
                ])
              }
            >
              <UserPlus className="mr-1 h-3 w-3" /> Adaugă utilizator
            </Button>
          </div>
        )}
      </div>

      <div>
        <Label>Note</Label>
        <Textarea
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          rows={2}
          className="mt-1"
        />
      </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>
  );
}
