"use client";

import { useState, useMemo } from "react";
import {
  Plus,
  Pencil,
  Trash2,
  Search,
  Mail,
  Phone,
  MapPin,
  Globe,
  Building2,
  UserPlus,
  X,
  Download,
  FileText,
} 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,
} from "@/shared/components/ui/dialog";
import type { AddressContact, ContactType, ContactPerson } from "../types";
import { useContacts } from "../hooks/use-contacts";
import { useTags } from "@/core/tagging";
import { downloadVCard } from "../services/vcard-export";
import { useRegistry } from "@/modules/registratura/hooks/use-registry";

const DEFAULT_TYPE_LABELS: Record<string, string> = {
  client: "Client",
  supplier: "Furnizor",
  institution: "Instituție",
  collaborator: "Colaborator",
  internal: "Intern",
};

/** Get a label for any contact type, including custom ones */
function getTypeLabel(type: string): string {
  return DEFAULT_TYPE_LABELS[type] ?? type;
}

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

export function AddressBookModule() {
  const {
    contacts,
    allContacts,
    loading,
    filters,
    updateFilter,
    addContact,
    updateContact,
    removeContact,
  } = useContacts();
  const [viewMode, setViewMode] = useState<ViewMode>("list");
  const [editingContact, setEditingContact] = useState<AddressContact | null>(
    null,
  );
  const [viewingContact, setViewingContact] = useState<AddressContact | null>(
    null,
  );

  // Collect all contact types (defaults + custom ones from existing contacts), sorted alphabetically by label
  const allTypes = useMemo(() => {
    const types: Record<string, string> = { ...DEFAULT_TYPE_LABELS };
    for (const c of allContacts) {
      if (c.type && !types[c.type]) {
        types[c.type] = c.type; // custom type — label is the type itself
      }
    }
    // Sort entries alphabetically by label
    const sorted: Record<string, string> = {};
    for (const [k, v] of Object.entries(types).sort((a, b) =>
      a[1].localeCompare(b[1], "ro"),
    )) {
      sorted[k] = v;
    }
    return sorted;
  }, [allContacts]);

  const handleSubmit = async (
    data: Omit<AddressContact, "id" | "createdAt" | "updatedAt">,
  ) => {
    if (viewMode === "edit" && editingContact) {
      await updateContact(editingContact.id, data);
    } else {
      await addContact(data);
    }
    setViewMode("list");
    setEditingContact(null);
  };

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-5">
        <Card>
          <CardContent className="p-4">
            <p className="text-xs text-muted-foreground">Total</p>
            <p className="text-2xl font-bold">{allContacts.length}</p>
          </CardContent>
        </Card>
        {Object.keys(DEFAULT_TYPE_LABELS)
          .slice(0, 4)
          .map((type) => (
            <Card key={type}>
              <CardContent className="p-4">
                <p className="text-xs text-muted-foreground">
                  {getTypeLabel(type)}
                </p>
                <p className="text-2xl font-bold">
                  {allContacts.filter((c) => c.type === type).length}
                </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ă contact..."
                value={filters.search}
                onChange={(e) => updateFilter("search", e.target.value)}
                className="pl-9"
              />
            </div>
            <Select
              value={filters.type}
              onValueChange={(v) =>
                updateFilter("type", v as ContactType | "all")
              }
            >
              <SelectTrigger className="w-[150px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Toate tipurile</SelectItem>
                {Object.keys(allTypes).map((t) => (
                  <SelectItem key={t} value={t}>
                    {allTypes[t]}
                  </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>
          ) : contacts.length === 0 ? (
            <p className="py-8 text-center text-sm text-muted-foreground">
              Niciun contact găsit.
            </p>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {contacts.map((contact) => (
                <ContactCard
                  key={contact.id}
                  contact={contact}
                  onEdit={() => {
                    setEditingContact(contact);
                    setViewMode("edit");
                  }}
                  onDelete={() => removeContact(contact.id)}
                  onViewDetail={() => setViewingContact(contact)}
                />
              ))}
            </div>
          )}
        </>
      )}

      {(viewMode === "add" || viewMode === "edit") && (
        <Card>
          <CardHeader>
            <CardTitle>
              {viewMode === "edit" ? "Editare contact" : "Contact nou"}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <ContactForm
              initial={editingContact ?? undefined}
              onSubmit={handleSubmit}
              onCancel={() => {
                setViewMode("list");
                setEditingContact(null);
              }}
            />
          </CardContent>
        </Card>
      )}

      {/* Contact Detail Dialog */}
      <ContactDetailDialog
        contact={viewingContact}
        onClose={() => setViewingContact(null)}
        onEdit={(c) => {
          setViewingContact(null);
          setEditingContact(c);
          setViewMode("edit");
        }}
      />
    </div>
  );
}

// ── Contact Card ──

function ContactCard({
  contact,
  onEdit,
  onDelete,
  onViewDetail,
}: {
  contact: AddressContact;
  onEdit: () => void;
  onDelete: () => void;
  onViewDetail: () => void;
}) {
  return (
    <Card className="group relative">
      <CardContent className="p-4">
        <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="Detalii"
            onClick={onViewDetail}
          >
            <FileText className="h-3.5 w-3.5" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7"
            title="Descarcă vCard"
            onClick={() => downloadVCard(contact)}
          >
            <Download 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>
        <div className="space-y-2">
          <div>
            <p className="font-medium">
              {contact.name || contact.company}
            </p>
            <div className="flex flex-wrap items-center gap-1.5">
              {contact.company && contact.name && (
                <p className="text-xs text-muted-foreground">
                  {contact.company}
                </p>
              )}
              <Badge variant="outline" className="text-[10px]">
                {getTypeLabel(contact.type)}
              </Badge>
              {contact.department && (
                <Badge variant="secondary" className="text-[10px]">
                  {contact.department}
                </Badge>
              )}
            </div>
            {contact.role && (
              <p className="text-xs text-muted-foreground italic">
                {contact.role}
              </p>
            )}
          </div>
          {contact.email && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Mail className="h-3 w-3 shrink-0" />
              <span className="truncate">{contact.email}</span>
            </div>
          )}
          {contact.email2 && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Mail className="h-3 w-3 shrink-0" />
              <span className="truncate">{contact.email2}</span>
            </div>
          )}
          {contact.phone && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Phone className="h-3 w-3 shrink-0" />
              <span>{contact.phone}</span>
            </div>
          )}
          {contact.phone2 && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Phone className="h-3 w-3 shrink-0" />
              <span>{contact.phone2}</span>
            </div>
          )}
          {contact.address && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <MapPin className="h-3 w-3 shrink-0" />
              <span className="truncate">{contact.address}</span>
            </div>
          )}
          {contact.website && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Globe className="h-3 w-3 shrink-0" />
              <span className="truncate">{contact.website}</span>
            </div>
          )}
          {(contact.contactPersons ?? []).length > 0 && (
            <div className="mt-1 border-t pt-1">
              <p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-1">
                Persoane de contact ({contact.contactPersons.length})
              </p>
              {contact.contactPersons.slice(0, 2).map((cp, i) => (
                <p key={i} className="text-xs text-muted-foreground">
                  {cp.name}
                  {cp.department ? ` · ${cp.department}` : ""}
                  {cp.role ? ` — ${cp.role}` : ""}
                </p>
              ))}
              {contact.contactPersons.length > 2 && (
                <p className="text-[10px] text-muted-foreground">
                  +{contact.contactPersons.length - 2} altele
                </p>
              )}
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
}

// ── Contact Detail Dialog (with Registratura reverse lookup) ──

const DIRECTION_LABELS: Record<string, string> = {
  intrat: "Intrat",
  iesit: "Ieșit",
};

function ContactDetailDialog({
  contact,
  onClose,
  onEdit,
}: {
  contact: AddressContact | null;
  onClose: () => void;
  onEdit: (c: AddressContact) => void;
}) {
  const { allEntries } = useRegistry();

  if (!contact) return null;

  // Find registratura entries linked to this contact (search all, ignoring active filters)
  const linkedEntries = allEntries.filter(
    (e) =>
      e.senderContactId === contact.id || e.recipientContactId === contact.id,
  );

  return (
    <Dialog
      open={contact !== null}
      onOpenChange={(open) => {
        if (!open) onClose();
      }}
    >
      <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-3">
            <span>{contact.name || contact.company}</span>
            <Badge variant="outline">{getTypeLabel(contact.type)}</Badge>
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* Contact info */}
          <div className="grid gap-2 text-sm">
            {contact.company && (
              <div className="flex items-center gap-2 text-muted-foreground">
                <Building2 className="h-4 w-4 shrink-0" />
                <span>
                  {contact.company}
                  {contact.department ? ` — ${contact.department}` : ""}
                </span>
              </div>
            )}
            {contact.role && (
              <p className="text-xs italic text-muted-foreground pl-6">
                {contact.role}
              </p>
            )}
            {contact.email && (
              <div className="flex items-center gap-2 text-muted-foreground">
                <Mail className="h-4 w-4 shrink-0" />
                <a
                  href={`mailto:${contact.email}`}
                  className="hover:text-foreground"
                >
                  {contact.email}
                </a>
              </div>
            )}
            {contact.email2 && (
              <div className="flex items-center gap-2 text-muted-foreground">
                <Mail className="h-4 w-4 shrink-0" />
                <a
                  href={`mailto:${contact.email2}`}
                  className="hover:text-foreground"
                >
                  {contact.email2}
                </a>
              </div>
            )}
            {contact.phone && (
              <div className="flex items-center gap-2 text-muted-foreground">
                <Phone className="h-4 w-4 shrink-0" />
                <span>{contact.phone}</span>
              </div>
            )}
            {contact.phone2 && (
              <div className="flex items-center gap-2 text-muted-foreground">
                <Phone className="h-4 w-4 shrink-0" />
                <span>{contact.phone2}</span>
              </div>
            )}
            {contact.address && (
              <div className="flex items-center gap-2 text-muted-foreground">
                <MapPin className="h-4 w-4 shrink-0" />
                <span>{contact.address}</span>
              </div>
            )}
            {contact.website && (
              <div className="flex items-center gap-2 text-muted-foreground">
                <Globe className="h-4 w-4 shrink-0" />
                <a
                  href={contact.website}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="hover:text-foreground truncate"
                >
                  {contact.website}
                </a>
              </div>
            )}
          </div>

          {/* Contact persons */}
          {contact.contactPersons && contact.contactPersons.length > 0 && (
            <div>
              <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-1.5">
                Persoane de contact
              </p>
              <div className="space-y-1">
                {contact.contactPersons.map((cp, i) => (
                  <div
                    key={i}
                    className="flex flex-wrap items-center gap-2 text-sm"
                  >
                    <span className="font-medium">{cp.name}</span>
                    {cp.department && (
                      <Badge variant="secondary" className="text-[10px]">
                        {cp.department}
                      </Badge>
                    )}
                    {cp.role && (
                      <span className="text-muted-foreground text-xs">
                        {cp.role}
                      </span>
                    )}
                    {cp.email && (
                      <a
                        href={`mailto:${cp.email}`}
                        className="text-xs text-muted-foreground hover:text-foreground"
                      >
                        {cp.email}
                      </a>
                    )}
                    {cp.phone && (
                      <span className="text-xs text-muted-foreground">
                        {cp.phone}
                      </span>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {contact.notes && (
            <div>
              <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-1">
                Note
              </p>
              <p className="text-sm text-muted-foreground whitespace-pre-wrap">
                {contact.notes}
              </p>
            </div>
          )}

          {/* Registratura reverse lookup */}
          <div>
            <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2">
              Registratură ({linkedEntries.length})
            </p>
            {linkedEntries.length === 0 ? (
              <p className="text-xs text-muted-foreground">
                Nicio înregistrare în registratură pentru acest contact.
              </p>
            ) : (
              <div className="space-y-1.5 max-h-52 overflow-y-auto pr-1">
                {linkedEntries.map((entry) => (
                  <div
                    key={entry.id}
                    className="flex items-center gap-3 rounded border p-2 text-xs"
                  >
                    <Badge variant="outline" className="shrink-0 text-[10px]">
                      {DIRECTION_LABELS[entry.direction] ?? entry.direction}
                    </Badge>
                    <span className="font-mono shrink-0 text-muted-foreground">
                      {entry.number}
                    </span>
                    <span className="flex-1 truncate font-medium">
                      {entry.subject}
                    </span>
                    <span className="shrink-0 text-muted-foreground">
                      {entry.date}
                    </span>
                    <Badge
                      variant={
                        entry.status === "deschis" ? "default" : "secondary"
                      }
                      className="shrink-0 text-[10px]"
                    >
                      {entry.status === "deschis" ? "Deschis" : "Închis"}
                    </Badge>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Actions */}
          <div className="flex justify-end gap-2 pt-2 border-t">
            <Button
              variant="outline"
              size="sm"
              onClick={() => downloadVCard(contact)}
            >
              <Download className="mr-1.5 h-3.5 w-3.5" /> Descarcă vCard
            </Button>
            <Button variant="outline" size="sm" onClick={() => onEdit(contact)}>
              <Pencil className="mr-1.5 h-3.5 w-3.5" /> Editează
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// ── Creatable Type Select ──

function CreatableTypeSelect({
  value,
  onChange,
}: {
  value: string;
  onChange: (v: string) => void;
}) {
  const [isCreating, setIsCreating] = useState(false);
  const [customValue, setCustomValue] = useState("");

  if (isCreating) {
    return (
      <div className="mt-1 flex gap-1.5">
        <Input
          value={customValue}
          onChange={(e) => setCustomValue(e.target.value)}
          placeholder="Tip nou (ex: Colaborator Extern)"
          className="flex-1"
          autoFocus
          onKeyDown={(e) => {
            if (e.key === "Enter" && customValue.trim()) {
              e.preventDefault();
              onChange(customValue.trim());
              setIsCreating(false);
              setCustomValue("");
            }
            if (e.key === "Escape") {
              setIsCreating(false);
              setCustomValue("");
            }
          }}
        />
        <Button
          type="button"
          size="sm"
          onClick={() => {
            if (customValue.trim()) {
              onChange(customValue.trim());
            }
            setIsCreating(false);
            setCustomValue("");
          }}
        >
          OK
        </Button>
        <Button
          type="button"
          variant="ghost"
          size="sm"
          onClick={() => {
            setIsCreating(false);
            setCustomValue("");
          }}
        >
          <X className="h-3.5 w-3.5" />
        </Button>
      </div>
    );
  }

  return (
    <div className="mt-1 flex gap-1.5">
      <Select value={value} onValueChange={onChange}>
        <SelectTrigger className="flex-1">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          {Object.entries(DEFAULT_TYPE_LABELS)
            .concat(
              value && !DEFAULT_TYPE_LABELS[value] ? [[value, value]] : [],
            )
            .sort((a, b) => a[1].localeCompare(b[1], "ro"))
            .map(([k, label]) => (
              <SelectItem key={k} value={k}>
                {label}
              </SelectItem>
            ))}
        </SelectContent>
      </Select>
      <Button
        type="button"
        variant="outline"
        size="icon"
        onClick={() => setIsCreating(true)}
        title="Adaugă tip nou"
      >
        <Plus className="h-3.5 w-3.5" />
      </Button>
    </div>
  );
}

// ── Contact Form ──

function ContactForm({
  initial,
  onSubmit,
  onCancel,
}: {
  initial?: AddressContact;
  onSubmit: (
    data: Omit<AddressContact, "id" | "createdAt" | "updatedAt">,
  ) => void;
  onCancel: () => void;
}) {
  const { tags: projectTags } = useTags("project");
  const [name, setName] = useState(initial?.name ?? "");
  const [company, setCompany] = useState(initial?.company ?? "");
  const [type, setType] = useState<ContactType>(initial?.type ?? "client");
  const [email, setEmail] = useState(initial?.email ?? "");
  const [email2, setEmail2] = useState(initial?.email2 ?? "");
  const [phone, setPhone] = useState(initial?.phone ?? "");
  const [phone2, setPhone2] = useState(initial?.phone2 ?? "");
  const [address, setAddress] = useState(initial?.address ?? "");
  const [department, setDepartment] = useState(initial?.department ?? "");
  const [role, setRole] = useState(initial?.role ?? "");
  const [website, setWebsite] = useState(initial?.website ?? "");
  const [notes, setNotes] = useState(initial?.notes ?? "");
  const [projectIds, setProjectIds] = useState<string[]>(
    initial?.projectIds ?? [],
  );
  const [contactPersons, setContactPersons] = useState<ContactPerson[]>(
    initial?.contactPersons ?? [],
  );

  const addContactPerson = () => {
    setContactPersons([
      ...contactPersons,
      { name: "", department: "", role: "", email: "", phone: "" },
    ]);
  };

  const updateContactPerson = (
    index: number,
    field: keyof ContactPerson,
    value: string,
  ) => {
    setContactPersons(
      contactPersons.map((cp, i) =>
        i === index ? { ...cp, [field]: value } : cp,
      ),
    );
  };

  const removeContactPerson = (index: number) => {
    setContactPersons(contactPersons.filter((_, i) => i !== index));
  };

  const toggleProject = (projectId: string) => {
    setProjectIds((prev) =>
      prev.includes(projectId)
        ? prev.filter((id) => id !== projectId)
        : [...prev, projectId],
    );
  };

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        if (!name.trim() && !company.trim()) return;
        onSubmit({
          name,
          company,
          type,
          email,
          email2,
          phone,
          phone2,
          address,
          department,
          role,
          website,
          notes,
          projectIds,
          contactPersons: contactPersons.filter((cp) => cp.name.trim()),
          tags: initial?.tags ?? [],
          visibility: initial?.visibility ?? "all",
        });
      }}
      className="space-y-4"
    >
      {/* Row 1: Name + Company + Type */}
      {!name.trim() && !company.trim() && (
        <p className="text-xs text-destructive">
          Completează cel puțin Numele sau Compania/Organizația.
        </p>
      )}
      <div className="grid gap-4 sm:grid-cols-3">
        <div>
          <Label>Nume {!company.trim() ? "*" : ""}</Label>
          <Input
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="mt-1"
            required={!company.trim()}
          />
        </div>
        <div>
          <Label>Companie/Organizație {!name.trim() ? "*" : ""}</Label>
          <Input
            value={company}
            onChange={(e) => setCompany(e.target.value)}
            className="mt-1"
            required={!name.trim()}
          />
        </div>
        <div>
          <Label>Tip</Label>
          <CreatableTypeSelect value={type} onChange={(v) => setType(v)} />
        </div>
      </div>

      {/* Row 2: Department + Role + Website */}
      <div className="grid gap-4 sm:grid-cols-3">
        <div>
          <Label>Departament</Label>
          <Input
            value={department}
            onChange={(e) => setDepartment(e.target.value)}
            className="mt-1"
          />
        </div>
        <div>
          <Label>Funcție/Rol</Label>
          <Input
            value={role}
            onChange={(e) => setRole(e.target.value)}
            className="mt-1"
          />
        </div>
        <div>
          <Label>Website</Label>
          <Input
            type="url"
            value={website}
            onChange={(e) => setWebsite(e.target.value)}
            className="mt-1"
            placeholder="https://"
          />
        </div>
      </div>

      {/* Row 3: Emails + Phones */}
      <div className="grid gap-4 sm:grid-cols-2">
        <div className="grid gap-2">
          <div>
            <Label>Email principal</Label>
            <Input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="mt-1"
            />
          </div>
          <div>
            <Label>Email secundar</Label>
            <Input
              type="email"
              value={email2}
              onChange={(e) => setEmail2(e.target.value)}
              className="mt-1"
            />
          </div>
        </div>
        <div className="grid gap-2">
          <div>
            <Label>Telefon principal</Label>
            <Input
              type="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              className="mt-1"
            />
          </div>
          <div>
            <Label>Telefon secundar</Label>
            <Input
              type="tel"
              value={phone2}
              onChange={(e) => setPhone2(e.target.value)}
              className="mt-1"
            />
          </div>
        </div>
      </div>

      {/* Address */}
      <div>
        <Label>Adresă</Label>
        <Input
          value={address}
          onChange={(e) => setAddress(e.target.value)}
          className="mt-1"
        />
      </div>

      {/* Project links */}
      {projectTags.length > 0 && (
        <div>
          <Label>Proiecte asociate</Label>
          <div className="mt-1.5 flex flex-wrap gap-1.5">
            {projectTags.map((pt) => (
              <button
                key={pt.id}
                type="button"
                onClick={() => toggleProject(pt.id)}
                className={`rounded-full border px-2.5 py-0.5 text-xs transition-colors ${
                  projectIds.includes(pt.id)
                    ? "border-primary bg-primary/10 text-primary"
                    : "border-muted-foreground/30 text-muted-foreground hover:border-primary/50"
                }`}
              >
                {pt.projectCode ? `${pt.projectCode} ` : ""}
                {pt.label}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Contact Persons */}
      <div>
        <div className="flex items-center justify-between">
          <Label>Persoane de contact</Label>
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={addContactPerson}
          >
            <UserPlus className="mr-1 h-3.5 w-3.5" /> Adaugă persoană
          </Button>
        </div>
        {contactPersons.length > 0 && (
          <div className="mt-2 space-y-2">
            {contactPersons.map((cp, i) => (
              <div
                key={i}
                className="flex flex-wrap items-start gap-2 rounded border p-2"
              >
                <Input
                  placeholder="Nume"
                  value={cp.name}
                  onChange={(e) =>
                    updateContactPerson(i, "name", e.target.value)
                  }
                  className="min-w-[150px] flex-1 text-sm"
                />
                <Input
                  placeholder="Departament"
                  value={cp.department ?? ""}
                  onChange={(e) =>
                    updateContactPerson(i, "department", e.target.value)
                  }
                  className="w-[140px] text-sm"
                />
                <Input
                  placeholder="Funcție"
                  value={cp.role}
                  onChange={(e) =>
                    updateContactPerson(i, "role", e.target.value)
                  }
                  className="w-[140px] text-sm"
                />
                <Input
                  placeholder="Email"
                  value={cp.email}
                  onChange={(e) =>
                    updateContactPerson(i, "email", e.target.value)
                  }
                  className="w-[180px] text-sm"
                />
                <Input
                  placeholder="Telefon"
                  value={cp.phone}
                  onChange={(e) =>
                    updateContactPerson(i, "phone", e.target.value)
                  }
                  className="w-[140px] text-sm"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8 shrink-0 text-destructive"
                  onClick={() => removeContactPerson(i)}
                >
                  <X className="h-3.5 w-3.5" />
                </Button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Notes */}
      <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>
  );
}
