"use client";

import { useCallback, useState } from "react";
import Link from "next/link";

type TargetType = "companies" | "people" | "contact_points" | "all";

type SearchHit = { id: string; label: string; kind: TargetType | "mixed" };

async function searchEndpoint(
  path: string,
  q: string
): Promise<Record<string, unknown>[]> {
  const params = new URLSearchParams({ page: "1", limit: "15" });
  if (q) params.set("q", q);
  const res = await fetch(`${path}?${params}`);
  if (!res.ok) return [];
  const json = await res.json();
  return (json.data ?? []) as Record<string, unknown>[];
}

export function StaticSegmentManager({
  segmentId,
  targetType,
}: {
  segmentId: string;
  targetType: TargetType;
}) {
  const [q, setQ] = useState("");
  const [results, setResults] = useState<SearchHit[]>([]);
  const [picked, setPicked] = useState<Set<string>>(new Set());
  const [message, setMessage] = useState("");

  const search = useCallback(async () => {
    const paths: Array<{ kind: TargetType; path: string }> =
      targetType === "all"
        ? [
            { kind: "companies", path: "/api/market/companies" },
            { kind: "people", path: "/api/market/people" },
            { kind: "contact_points", path: "/api/market/contact-points" },
          ]
        : [
            {
              kind: targetType,
              path:
                targetType === "companies"
                  ? "/api/market/companies"
                  : targetType === "people"
                    ? "/api/market/people"
                    : "/api/market/contact-points",
            },
          ];

    const batches = await Promise.all(
      paths.map(async ({ kind, path }) => {
        const rows = await searchEndpoint(path, q);
        return rows.map((row) => {
          const id = String(row._id);
          let label = id;
          if (kind === "companies") {
            label = String(row.nameAr ?? row.nameEn ?? id);
          } else if (kind === "people") {
            label = String(row.fullName ?? id);
          } else {
            label = `${String(row.contactType ?? "")}: ${String(row.contactValue ?? id)}`;
          }
          const prefix =
            targetType === "all"
              ? kind === "companies"
                ? "[شركة] "
                : kind === "people"
                  ? "[شخص] "
                  : "[اتصال] "
              : "";
          return { id, label: prefix + label, kind };
        });
      })
    );
    setResults(batches.flat());
  }, [q, targetType]);

  async function addMembers() {
    if (picked.size === 0) return;
    setMessage("");
    const res = await fetch(`/api/segments/${segmentId}/members`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ids: [...picked] }),
    });
    const json = await res.json();
    if (!res.ok) {
      setMessage(json.error ?? "فشل الإضافة");
      return;
    }
    setMessage(`تمت إضافة ${picked.size} عضو`);
    setPicked(new Set());
    window.location.reload();
  }

  return (
    <section className="rounded-lg border border-neutral-200 bg-white p-5">
      <h2 className="text-lg font-semibold">إضافة أعضاء (شريحة ثابتة)</h2>
      <p className="mt-1 text-sm text-neutral-600">
        ابحث وحدد العناصر للإضافة — بدون عرض معرفات داخلية.
      </p>
      <div className="mt-3 flex flex-wrap gap-2">
        <input
          className="min-w-[200px] flex-1 rounded border px-3 py-2 text-sm"
          placeholder="بحث..."
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <button
          type="button"
          onClick={() => void search()}
          className="rounded border px-3 py-2 text-sm"
        >
          بحث
        </button>
        <button
          type="button"
          disabled={picked.size === 0}
          onClick={() => void addMembers()}
          className="rounded bg-[var(--accent)] px-3 py-2 text-sm text-white disabled:opacity-50"
        >
          إضافة المحدد ({picked.size})
        </button>
      </div>
      {message ? <p className="mt-2 text-sm text-green-700">{message}</p> : null}
      <ul className="mt-3 max-h-64 space-y-1 overflow-y-auto text-sm">
        {results.map((row) => (
          <li key={row.id} className="flex items-center gap-2 border-b py-1">
            <input
              type="checkbox"
              checked={picked.has(row.id)}
              onChange={(e) => {
                setPicked((prev) => {
                  const next = new Set(prev);
                  if (e.target.checked) next.add(row.id);
                  else next.delete(row.id);
                  return next;
                });
              }}
            />
            {row.kind === "companies" ? (
              <Link href={`/market/companies/${row.id}`} className="text-[var(--accent)]">
                {row.label}
              </Link>
            ) : row.kind === "people" ? (
              <Link href={`/market/people/${row.id}`} className="text-[var(--accent)]">
                {row.label}
              </Link>
            ) : (
              <span>{row.label}</span>
            )}
          </li>
        ))}
      </ul>
    </section>
  );
}
