"use client";

import { useMemo, useState, useTransition } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";

import { AdminConfirmDialog } from "@/components/admin/common/AdminConfirmDialog";
import {
  getSalesInquiryContextChips,
  getSalesInquiryTypeLabel,
} from "@/lib/sales-inquiry";
import {
  getSalesPipelineStageLabel,
  getSalesPriorityLabel,
  SALES_PIPELINE_STAGES,
  SALES_PRIORITIES,
  type SalesPipelineStage,
  type SalesPriority,
} from "@/lib/sales-crm";

type SalesInquiryRow = {
  id: string;
  invoiceId: string | null;
  status: "NEW" | "IN_REVIEW" | "RESPONDED" | "CLOSED";
  pipelineStage: string;
  priority: string;
  locale: string;
  inquiryType: string;
  contactName: string;
  companyName: string | null;
  email: string;
  phone: string | null;
  cityName: string | null;
  categoryName: string | null;
  preferredPlan: string | null;
  preferredModule: string | null;
  placementLabel: string | null;
  budgetLabel: string | null;
  slot: string | null;
  pageType: string | null;
  moduleType: string | null;
  sourceLabel: string | null;
  sourcePath: string | null;
  message: string;
  responseNote: string | null;
  internalNotes: string | null;
  nextStep: string | null;
  ownerName: string | null;
  estimatedValue: number | null;
  probability: number | null;
  followUpAt: Date | string | null;
  closedAt: Date | string | null;
  respondedAt: Date | string | null;
  createdAt: Date | string;
  updatedAt: Date | string;
  invoice: {
    id: string;
    number: string;
    status: string;
    totalAmount: number;
  } | null;
};

type SalesCrmReport = {
  total: number;
  open: number;
  won: number;
  lost: number;
  overdue: number;
  dueSoon: number;
  openPipelineValue: number;
  weightedPipelineValue: number;
  byStage: Record<string, { count: number; value: number }>;
  byPriority: Record<string, number>;
};

type EditableFields = {
  pipelineStage: SalesPipelineStage;
  priority: SalesPriority;
  responseNote: string;
  internalNotes: string;
  nextStep: string;
  ownerName: string;
  estimatedValue: string;
  probability: string;
  followUpAt: string;
};

function formatDate(value?: Date | string | null) {
  if (!value) {
    return "Bez datuma";
  }

  return new Intl.DateTimeFormat("sr-Latn-RS", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(new Date(value));
}

function formatDateInput(value?: Date | string | null) {
  if (!value) {
    return "";
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return "";
  }

  const offset = date.getTimezoneOffset();
  const local = new Date(date.getTime() - offset * 60_000);
  return local.toISOString().slice(0, 16);
}

function toIsoDateTime(value: string) {
  if (!value) {
    return null;
  }

  return new Date(value).toISOString();
}

function formatCurrency(value: number) {
  return new Intl.NumberFormat("sr-Latn-RS", {
    style: "currency",
    currency: "RSD",
    maximumFractionDigits: 0,
  }).format(value);
}

function normalizeStage(value?: string | null): SalesPipelineStage {
  return SALES_PIPELINE_STAGES.includes(value as SalesPipelineStage)
    ? (value as SalesPipelineStage)
    : "NEW_LEAD";
}

function normalizePriority(value?: string | null): SalesPriority {
  return SALES_PRIORITIES.includes(value as SalesPriority)
    ? (value as SalesPriority)
    : "MEDIUM";
}

function getStageTone(stage: string) {
  return {
    NEW_LEAD: "border-secondary/18 bg-secondary/10 text-primary",
    CONTACTED: "border-sky-500/18 bg-sky-500/10 text-sky-700",
    QUALIFIED: "border-emerald-500/18 bg-emerald-500/10 text-emerald-700",
    PROPOSAL_SENT: "border-violet-500/18 bg-violet-500/10 text-violet-700",
    NEGOTIATION: "border-amber-500/18 bg-amber-500/10 text-amber-700",
    WON: "border-success/18 bg-success/10 text-success",
    LOST: "border-border bg-muted/70 text-muted-foreground",
  }[stage] ?? "border-border bg-muted/70 text-muted-foreground";
}

function getPriorityTone(priority: string) {
  return {
    LOW: "border-border bg-muted/60 text-muted-foreground",
    MEDIUM: "border-sky-500/18 bg-sky-500/10 text-sky-700",
    HIGH: "border-amber-500/18 bg-amber-500/10 text-amber-700",
    URGENT: "border-red-500/18 bg-red-500/10 text-red-700",
  }[priority] ?? "border-border bg-muted/60 text-muted-foreground";
}

function isOverdue(item: SalesInquiryRow) {
  return (
    item.followUpAt &&
    !["WON", "LOST"].includes(item.pipelineStage) &&
    new Date(item.followUpAt).getTime() < Date.now()
  );
}

function buildEditable(item: SalesInquiryRow): EditableFields {
  return {
    pipelineStage: normalizeStage(item.pipelineStage),
    priority: normalizePriority(item.priority),
    responseNote: item.responseNote ?? "",
    internalNotes: item.internalNotes ?? "",
    nextStep: item.nextStep ?? "",
    ownerName: item.ownerName ?? "",
    estimatedValue: item.estimatedValue?.toString() ?? "",
    probability: item.probability?.toString() ?? "",
    followUpAt: formatDateInput(item.followUpAt),
  };
}

function TrashIcon() {
  return (
    <svg viewBox="0 0 20 20" fill="none" aria-hidden="true">
      <path
        d="M7.75 3.75H12.25M3.75 5.5H16.25M6 5.5L6.65 14.28C6.73 15.31 7.58 16.11 8.61 16.11H11.39C12.42 16.11 13.27 15.31 13.35 14.28L14 5.5M8.5 8.25V12.5M11.5 8.25V12.5"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function SalesInquiryListManager({
  items: initialItems,
  report,
}: {
  items: SalesInquiryRow[];
  report: SalesCrmReport;
}) {
  const router = useRouter();
  const [items, setItems] = useState(initialItems);
  const [edits, setEdits] = useState<Record<string, EditableFields>>(() =>
    Object.fromEntries(initialItems.map((item) => [item.id, buildEditable(item)])),
  );
  const [message, setMessage] = useState<string | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<SalesInquiryRow | null>(null);
  const [activeStage, setActiveStage] = useState<"ALL" | SalesPipelineStage>("ALL");
  const [isPending, startTransition] = useTransition();

  const filteredItems = useMemo(
    () =>
      activeStage === "ALL"
        ? items
        : items.filter((item) => normalizeStage(item.pipelineStage) === activeStage),
    [activeStage, items],
  );
  const attentionItems = items
    .filter((item) => isOverdue(item))
    .sort(
      (left, right) =>
        new Date(left.followUpAt || 0).getTime() - new Date(right.followUpAt || 0).getTime(),
    )
    .slice(0, 4);

  function updateEdit(id: string, patch: Partial<EditableFields>) {
    setEdits((current) => ({
      ...current,
      [id]: {
        ...(current[id] ?? buildEditable(items.find((item) => item.id === id)!)),
        ...patch,
      },
    }));
  }

  function saveInquiry(id: string) {
    const edit = edits[id];
    if (!edit) {
      return;
    }

    startTransition(async () => {
      try {
        const response = await fetch(`/api/admin/sales-inquiries/${id}`, {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            status: "IN_REVIEW",
            pipelineStage: edit.pipelineStage,
            priority: edit.priority,
            responseNote: edit.responseNote || undefined,
            internalNotes: edit.internalNotes || undefined,
            nextStep: edit.nextStep || undefined,
            ownerName: edit.ownerName || undefined,
            estimatedValue: edit.estimatedValue ? Number(edit.estimatedValue) : null,
            probability: edit.probability ? Number(edit.probability) : null,
            followUpAt: toIsoDateTime(edit.followUpAt),
          }),
        });

        const result = (await response.json()) as {
          item?: SalesInquiryRow;
          message?: string;
        };

        if (!response.ok || !result.item) {
          throw new Error(result.message || "Ažuriranje CRM prilike nije uspelo.");
        }

        setItems((current) =>
          current.map((item) => (item.id === result.item!.id ? result.item! : item)),
        );
        setEdits((current) => ({
          ...current,
          [result.item!.id]: buildEditable(result.item!),
        }));
        setMessage(`CRM prilika je ažurirana: ${getSalesPipelineStageLabel(edit.pipelineStage)}.`);
        router.refresh();
      } catch (error) {
        setMessage(
          error instanceof Error ? error.message : "Ažuriranje CRM prilike nije uspelo.",
        );
      }
    });
  }

  function createInvoice(id: string, sendEmail = false) {
    startTransition(async () => {
      try {
        const response = await fetch(`/api/admin/sales-inquiries/${id}/invoice`, {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ sendEmail }),
        });

        const result = (await response.json()) as {
          item?: {
            id: string;
            number: string;
            status: string;
            totalAmount: number;
          };
          message?: string;
        };

        if (!response.ok || !result.item) {
          throw new Error(result.message || "Kreiranje predračuna nije uspelo.");
        }

        setItems((current) =>
          current.map((item) =>
            item.id === id
              ? {
                  ...item,
                  invoiceId: result.item!.id,
                  invoice: result.item!,
                  pipelineStage: "PROPOSAL_SENT",
                  status: "RESPONDED",
                  probability: item.probability ?? 60,
                  nextStep: item.nextStep || "Pratiti reakciju na poslati predračun.",
                }
              : item,
          ),
        );
        setEdits((current) => ({
          ...current,
          [id]: {
            ...(current[id] ?? buildEditable(items.find((item) => item.id === id)!)),
            pipelineStage: "PROPOSAL_SENT",
            probability: current[id]?.probability || "60",
            nextStep:
              current[id]?.nextStep || "Pratiti reakciju na poslati predračun.",
          },
        }));
        setMessage(
          sendEmail
            ? `Predračun ${result.item.number} je kreiran i poslat.`
            : `Predračun ${result.item.number} je kreiran iz CRM prilike.`,
        );
        router.refresh();
      } catch (error) {
        setMessage(error instanceof Error ? error.message : "Kreiranje predračuna nije uspelo.");
      }
    });
  }

  function handleDelete(id: string) {
    startTransition(async () => {
      try {
        const response = await fetch(`/api/admin/sales-inquiries/${id}`, {
          method: "DELETE",
        });

        const result = (await response.json()) as {
          item?: SalesInquiryRow;
          message?: string;
        };

        if (!response.ok || !result.item) {
          throw new Error(result.message || "Brisanje komercijalnog upita nije uspelo.");
        }

        setItems((current) => current.filter((item) => item.id !== result.item!.id));
        setDeleteTarget(null);
        setMessage("Komercijalni upit je obrisan.");
        router.refresh();
      } catch (error) {
        setMessage(
          error instanceof Error
            ? error.message
            : "Brisanje komercijalnog upita nije uspelo.",
        );
      }
    });
  }

  return (
    <section className="admin-command-shell">
      <div className="admin-command-header border-b border-border/80 pb-5">
        <div>
          <p className="eyebrow">Sales CRM</p>
          <h2 className="mt-2 admin-panel-heading !text-[2rem]">
            Pipeline za pakete, isticanja i oglase
          </h2>
          <p className="mt-2 text-sm text-muted-foreground">
            Svaki javni upit ovde postaje prodajna prilika sa vlasnikom, narednim korakom,
            procenjenom vrednošću i follow-up datumom.
          </p>
        </div>
        <div className="admin-kpi-grid sm:max-w-[760px]">
          <div className="admin-kpi-card">
            <div className="admin-kpi-label">Otvoreno</div>
            <div className="admin-kpi-value">{report.open}</div>
          </div>
          <div className="admin-kpi-card">
            <div className="admin-kpi-label">Pipeline</div>
            <div className="admin-kpi-value">{formatCurrency(report.openPipelineValue)}</div>
          </div>
          <div className="admin-kpi-card">
            <div className="admin-kpi-label">Weighted</div>
            <div className="admin-kpi-value">{formatCurrency(report.weightedPipelineValue)}</div>
          </div>
          <div className="admin-kpi-card">
            <div className="admin-kpi-label">Kasni</div>
            <div className="admin-kpi-value">{report.overdue}</div>
          </div>
          <div className="admin-kpi-card">
            <div className="admin-kpi-label">7 dana</div>
            <div className="admin-kpi-value">{report.dueSoon}</div>
          </div>
        </div>
      </div>

      <div className="mt-5 grid gap-4 xl:grid-cols-[1.25fr_0.75fr]">
        <div className="rounded-[1.5rem] border border-border bg-white/62 p-4">
          <div className="flex flex-wrap gap-2">
            <button
              type="button"
              className={`ghost-button px-4 py-2 text-sm ${activeStage === "ALL" ? "!border-primary/30 !text-primary" : ""}`}
              onClick={() => setActiveStage("ALL")}
            >
              Sve ({items.length})
            </button>
            {SALES_PIPELINE_STAGES.map((stage) => (
              <button
                key={stage}
                type="button"
                className={`ghost-button px-4 py-2 text-sm ${activeStage === stage ? "!border-primary/30 !text-primary" : ""}`}
                onClick={() => setActiveStage(stage)}
              >
                {getSalesPipelineStageLabel(stage)} ({report.byStage[stage]?.count ?? 0})
              </button>
            ))}
          </div>
        </div>

        <div className="rounded-[1.5rem] border border-amber-500/18 bg-amber-500/8 p-4">
          <p className="text-sm font-bold text-amber-800">Follow-up koji kasni</p>
          {attentionItems.length ? (
            <div className="mt-3 space-y-2">
              {attentionItems.map((item) => (
                <button
                  key={item.id}
                  type="button"
                  onClick={() => setActiveStage("ALL")}
                  className="w-full rounded-[1rem] border border-amber-500/14 bg-white/70 px-3 py-2 text-left text-sm"
                >
                  <span className="font-semibold text-foreground">
                    {item.companyName || item.contactName}
                  </span>
                  <span className="mt-1 block text-xs text-amber-800">
                    {formatDate(item.followUpAt)} · {item.nextStep || "Nema narednog koraka"}
                  </span>
                </button>
              ))}
            </div>
          ) : (
            <p className="mt-2 text-sm text-muted-foreground">Nema zakasnelih follow-upova.</p>
          )}
        </div>
      </div>

      {message ? (
        <div className="mt-5 rounded-[1.2rem] border border-secondary/16 bg-accent/55 px-4 py-3 text-sm font-medium text-primary">
          {message}
        </div>
      ) : null}

      <div className="mt-5 divide-y divide-border overflow-hidden rounded-[1.5rem] border border-border bg-white/62">
        {filteredItems.length ? (
          filteredItems.map((item) => {
            const chips = getSalesInquiryContextChips(item);
            const edit = edits[item.id] ?? buildEditable(item);

            return (
              <article
                key={item.id}
                className="admin-list-card xl:flex-row xl:items-start xl:justify-between"
              >
                <div className="min-w-0 flex-1">
                  <div className="flex flex-wrap gap-2">
                    <span className={`rounded-full border px-3 py-1 text-xs font-semibold ${getStageTone(edit.pipelineStage)}`}>
                      {getSalesPipelineStageLabel(edit.pipelineStage)}
                    </span>
                    <span className={`rounded-full border px-3 py-1 text-xs font-semibold ${getPriorityTone(edit.priority)}`}>
                      {getSalesPriorityLabel(edit.priority)}
                    </span>
                    <span className="admin-chip !normal-case !tracking-normal">
                      {getSalesInquiryTypeLabel(item.inquiryType)}
                    </span>
                    <span className="admin-chip !normal-case !tracking-normal">
                      {item.locale === "en" ? "EN" : "SR"}
                    </span>
                    {isOverdue(item) ? (
                      <span className="rounded-full border border-red-500/18 bg-red-500/10 px-3 py-1 text-xs font-semibold text-red-700">
                        Follow-up kasni
                      </span>
                    ) : null}
                  </div>

                  <h3 className="mt-3 text-xl font-semibold text-foreground">
                    {item.companyName || item.contactName}
                  </h3>
                  <p className="mt-1 text-sm font-medium text-foreground">
                    {item.contactName} • {item.email}
                    {item.phone ? ` • ${item.phone}` : ""}
                  </p>
                  <p className="mt-3 text-sm leading-7 text-muted-foreground">{item.message}</p>

                  {chips.length ? (
                    <div className="mt-4 flex flex-wrap gap-2">
                      {chips.map((chip) => (
                        <span key={`${item.id}-${chip}`} className="admin-chip !normal-case !tracking-normal">
                          {chip}
                        </span>
                      ))}
                    </div>
                  ) : null}

                  <div className="admin-kpi-grid mt-4 md:grid-cols-4">
                    <div className="admin-kpi-card">
                      <div className="admin-kpi-label">Kreiran</div>
                      <div className="admin-kpi-value">{formatDate(item.createdAt)}</div>
                    </div>
                    <div className="admin-kpi-card">
                      <div className="admin-kpi-label">Follow-up</div>
                      <div className="admin-kpi-value">{formatDate(edit.followUpAt || item.followUpAt)}</div>
                    </div>
                    <div className="admin-kpi-card">
                      <div className="admin-kpi-label">Izvor</div>
                      <div className="admin-kpi-value">
                        {item.sourceLabel || item.sourcePath || "Javna strana"}
                      </div>
                    </div>
                    <div className="admin-kpi-card">
                      <div className="admin-kpi-label">Vrednost</div>
                      <div className="admin-kpi-value">
                        {formatCurrency(Number(edit.estimatedValue || item.estimatedValue || 0))}
                      </div>
                    </div>
                  </div>

                  {item.invoice ? (
                    <div className="mt-4 flex flex-wrap items-center gap-3 rounded-[1.25rem] border border-success/18 bg-success/8 px-4 py-3">
                      <div className="min-w-0 flex-1">
                        <p className="text-sm font-bold text-success">
                          Povezan predračun {item.invoice.number}
                        </p>
                        <p className="mt-1 text-xs text-muted-foreground">
                          {formatCurrency(item.invoice.totalAmount)} · {item.invoice.status}
                        </p>
                      </div>
                      <a
                        className="ghost-button px-4 py-2 text-sm"
                        href={`/api/admin/invoices/${item.invoice.id}/proforma`}
                        target="_blank"
                        rel="noreferrer"
                      >
                        PDF
                      </a>
                      <Link className="ghost-button px-4 py-2 text-sm" href="/admin/naplata">
                        Naplata
                      </Link>
                    </div>
                  ) : null}

                  <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                    <label className="field-shell">
                      <span className="field-label">Faza</span>
                      <select
                        className="input-premium"
                        value={edit.pipelineStage}
                        onChange={(event) =>
                          updateEdit(item.id, {
                            pipelineStage: event.target.value as SalesPipelineStage,
                          })
                        }
                      >
                        {SALES_PIPELINE_STAGES.map((stage) => (
                          <option key={stage} value={stage}>
                            {getSalesPipelineStageLabel(stage)}
                          </option>
                        ))}
                      </select>
                    </label>
                    <label className="field-shell">
                      <span className="field-label">Prioritet</span>
                      <select
                        className="input-premium"
                        value={edit.priority}
                        onChange={(event) =>
                          updateEdit(item.id, { priority: event.target.value as SalesPriority })
                        }
                      >
                        {SALES_PRIORITIES.map((priority) => (
                          <option key={priority} value={priority}>
                            {getSalesPriorityLabel(priority)}
                          </option>
                        ))}
                      </select>
                    </label>
                    <label className="field-shell">
                      <span className="field-label">Vlasnik</span>
                      <input
                        className="input-premium"
                        value={edit.ownerName}
                        onChange={(event) => updateEdit(item.id, { ownerName: event.target.value })}
                        placeholder="Ime prodavca"
                      />
                    </label>
                    <label className="field-shell">
                      <span className="field-label">Follow-up</span>
                      <input
                        type="datetime-local"
                        className="input-premium"
                        value={edit.followUpAt}
                        onChange={(event) => updateEdit(item.id, { followUpAt: event.target.value })}
                      />
                    </label>
                    <label className="field-shell">
                      <span className="field-label">Vrednost RSD</span>
                      <input
                        type="number"
                        min="0"
                        className="input-premium"
                        value={edit.estimatedValue}
                        onChange={(event) =>
                          updateEdit(item.id, { estimatedValue: event.target.value })
                        }
                        placeholder="0"
                      />
                    </label>
                    <label className="field-shell">
                      <span className="field-label">Verovatnoća %</span>
                      <input
                        type="number"
                        min="0"
                        max="100"
                        className="input-premium"
                        value={edit.probability}
                        onChange={(event) =>
                          updateEdit(item.id, { probability: event.target.value })
                        }
                        placeholder="50"
                      />
                    </label>
                    <label className="field-shell md:col-span-2">
                      <span className="field-label">Naredni korak</span>
                      <input
                        className="input-premium"
                        value={edit.nextStep}
                        onChange={(event) => updateEdit(item.id, { nextStep: event.target.value })}
                        placeholder="Pozvati, poslati ponudu, zakazati prezentaciju..."
                      />
                    </label>
                  </div>

                  <div className="mt-4 grid gap-3 xl:grid-cols-2">
                    <label className="block">
                      <span className="admin-kpi-label">Beleška za odgovor</span>
                      <textarea
                        className="mt-2 min-h-28 w-full rounded-[1.2rem] border border-border bg-white/82 px-4 py-3 text-sm text-foreground outline-none transition focus:border-primary/28"
                        value={edit.responseNote}
                        onChange={(event) =>
                          updateEdit(item.id, { responseNote: event.target.value })
                        }
                        placeholder="Šta je poslato ili šta treba poslati klijentu."
                      />
                    </label>
                    <label className="block">
                      <span className="admin-kpi-label">Interna CRM beleška</span>
                      <textarea
                        className="mt-2 min-h-28 w-full rounded-[1.2rem] border border-border bg-white/82 px-4 py-3 text-sm text-foreground outline-none transition focus:border-primary/28"
                        value={edit.internalNotes}
                        onChange={(event) =>
                          updateEdit(item.id, { internalNotes: event.target.value })
                        }
                        placeholder="Kontekst razgovora, prigovori, dogovor, paket koji ima smisla."
                      />
                    </label>
                  </div>
                </div>

                <div className="mt-5 flex w-full flex-wrap items-center gap-3 xl:ml-6 xl:mt-0 xl:w-[260px] xl:justify-end">
                  <button
                    type="button"
                    className="primary-button"
                    disabled={isPending}
                    onClick={() => saveInquiry(item.id)}
                  >
                    Sačuvaj CRM
                  </button>
                  <button
                    type="button"
                    className="ghost-button"
                    disabled={isPending}
                    onClick={() =>
                      updateEdit(item.id, {
                        pipelineStage: "PROPOSAL_SENT",
                        priority: "HIGH",
                        nextStep: edit.nextStep || "Pratiti reakciju na poslatu ponudu.",
                      })
                    }
                  >
                    Poslata ponuda
                  </button>
                  <button
                    type="button"
                    className="ghost-button"
                    disabled={isPending || Boolean(item.invoice)}
                    onClick={() => createInvoice(item.id, false)}
                  >
                    Kreiraj predračun
                  </button>
                  <button
                    type="button"
                    className="ghost-button"
                    disabled={isPending || Boolean(item.invoice)}
                    onClick={() => createInvoice(item.id, true)}
                  >
                    Kreiraj i pošalji
                  </button>
                  <button
                    type="button"
                    className="ghost-button"
                    disabled={isPending}
                    onClick={() =>
                      updateEdit(item.id, {
                        pipelineStage: "WON",
                        probability: "100",
                        nextStep: "Aktivirati paket, kampanju ili naplatu.",
                      })
                    }
                  >
                    Dobijeno
                  </button>
                  <button
                    type="button"
                    className="flex h-12 w-12 items-center justify-center rounded-full border border-[rgba(188,63,41,0.16)] bg-[linear-gradient(180deg,rgba(255,247,245,0.98),rgba(253,239,236,0.94))] text-[#bc3f29] shadow-[0_16px_30px_rgba(188,63,41,0.14)] transition hover:-translate-y-0.5 hover:border-[rgba(188,63,41,0.28)] disabled:cursor-not-allowed disabled:opacity-60"
                    title={`Obriši upit ${item.contactName}`}
                    aria-label={`Obriši upit ${item.contactName}`}
                    disabled={isPending}
                    onClick={() => setDeleteTarget(item)}
                  >
                    <span className="h-5 w-5">
                      <TrashIcon />
                    </span>
                  </button>
                </div>
              </article>
            );
          })
        ) : (
          <div className="p-8 text-sm text-muted-foreground">
            Nema prilika u izabranoj pipeline fazi.
          </div>
        )}
      </div>

      <AdminConfirmDialog
        open={Boolean(deleteTarget)}
        title={deleteTarget ? `Obrisati upit za ${deleteTarget.companyName || deleteTarget.contactName}?` : ""}
        description="Upit će biti trajno uklonjen iz komercijalnog inbox-a i više neće biti dostupan u admin panelu."
        confirmLabel="Da, obriši"
        isPending={isPending}
        onClose={() => setDeleteTarget(null)}
        onConfirm={() => {
          if (deleteTarget) {
            void handleDelete(deleteTarget.id);
          }
        }}
      />
    </section>
  );
}
