"use client";

import { useState } from "react";
import { Icon } from "@/components/ui/Icon";
import { Avatar } from "@/components/ui/Avatar";

// ──────────────────────────────────────────────────────────────────────────
// Auswahl von Freigabe-Zielen (Personen, Teams, Rollen) mit Suche.
// Wird vom Passwortmanager und vom Cloud-Speicher gemeinsam genutzt.
// ──────────────────────────────────────────────────────────────────────────

export type ShareTargets = {
  users: { id: string; name: string; avatarUrl: string | null }[];
  teams: { id: string; name: string; color: string | null }[];
  roles: { id: string; name: string }[];
};

type Kind = "team" | "role" | "user";
const FILTERS: { key: "all" | Kind; label: string }[] = [
  { key: "all", label: "Alle" },
  { key: "user", label: "Personen" },
  { key: "team", label: "Teams" },
  { key: "role", label: "Rollen" },
];

export function SharePicker({
  targets,
  userIds,
  teamIds,
  roleIds,
  onUsers,
  onTeams,
  onRoles,
}: {
  targets: ShareTargets;
  userIds: string[];
  teamIds: string[];
  roleIds: string[];
  onUsers: (v: string[]) => void;
  onTeams: (v: string[]) => void;
  onRoles: (v: string[]) => void;
}) {
  const [q, setQ] = useState("");
  const [filter, setFilter] = useState<"all" | Kind>("all");

  const needle = q.trim().toLowerCase();
  const match = (name: string) => !needle || name.toLowerCase().includes(needle);
  const show = (kind: Kind) => filter === "all" || filter === kind;

  const teams = show("team") ? targets.teams.filter((t) => match(t.name)) : [];
  const roles = show("role") ? targets.roles.filter((r) => match(r.name)) : [];
  const users = show("user") ? targets.users.filter((u) => match(u.name)) : [];

  const toggle = (arr: string[], id: string, set: (v: string[]) => void) =>
    set(arr.includes(id) ? arr.filter((x) => x !== id) : [...arr, id]);

  const remove = (kind: Kind, id: string) => {
    if (kind === "team") toggle(teamIds, id, onTeams);
    else if (kind === "role") toggle(roleIds, id, onRoles);
    else toggle(userIds, id, onUsers);
  };

  const selected = [
    ...targets.teams
      .filter((t) => teamIds.includes(t.id))
      .map((t) => ({ id: t.id, name: t.name, color: t.color, kind: "team" as Kind })),
    ...targets.roles
      .filter((r) => roleIds.includes(r.id))
      .map((r) => ({ id: r.id, name: r.name, color: null, kind: "role" as Kind })),
    ...targets.users
      .filter((u) => userIds.includes(u.id))
      .map((u) => ({ id: u.id, name: u.name, color: null, kind: "user" as Kind })),
  ];

  const iconFor = (kind: Kind) => (kind === "team" ? "users" : kind === "role" ? "shield" : "user");

  return (
    <>
      {/* Ausgewählte Ziele */}
      {selected.length === 0 ? (
        <div className="share-empty">
          <Icon name="lock" size={15} />
          Noch keine Freigabe — der Eintrag ist nur für dich sichtbar.
        </div>
      ) : (
        <div className="flex flex-wrap gap-1.5">
          {selected.map((s) => (
            <button
              key={`${s.kind}-${s.id}`}
              type="button"
              className="badge"
              onClick={() => remove(s.kind, s.id)}
              title="Freigabe entfernen"
            >
              {s.kind === "team" ? (
                <span className="team-dot" style={{ background: s.color ?? "var(--blue)" }} />
              ) : (
                <Icon name={iconFor(s.kind)} size={11} />
              )}
              {s.name}
              <Icon name="close" size={10} />
            </button>
          ))}
        </div>
      )}

      {/* Filter & Suche */}
      <div className="flex flex-wrap items-center gap-2">
        <div className="segmented">
          {FILTERS.map((f) => (
            <button
              key={f.key}
              type="button"
              className="segmented-btn"
              style={{ padding: "6px 12px", fontSize: "0.76rem" }}
              data-active={filter === f.key}
              onClick={() => setFilter(f.key)}
            >
              {f.label}
            </button>
          ))}
        </div>
      </div>

      <div className="relative">
        <input
          className="input"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder="Person, Team oder Rolle suchen …"
          style={{ paddingLeft: 38 }}
        />
        <span className="text-muted pointer-events-none absolute left-3 top-1/2 -translate-y-1/2">
          <Icon name="search" size={16} />
        </span>
      </div>

      {/* Trefferliste */}
      <div className="share-list">
        {teams.length > 0 ? <div className="share-group">Teams</div> : null}
        {teams.map((t) => {
          const active = teamIds.includes(t.id);
          return (
            <button
              key={t.id}
              type="button"
              className="share-row"
              data-active={active}
              onClick={() => toggle(teamIds, t.id, onTeams)}
            >
              <span className="share-check">{active ? <Icon name="check" size={12} /> : null}</span>
              <span className="team-dot" style={{ background: t.color ?? "var(--blue)" }} />
              <span className="min-w-0 flex-1 truncate font-bold">{t.name}</span>
              <span className="text-muted text-[11px]">Team</span>
            </button>
          );
        })}

        {roles.length > 0 ? <div className="share-group">Rollen</div> : null}
        {roles.map((r) => {
          const active = roleIds.includes(r.id);
          return (
            <button
              key={r.id}
              type="button"
              className="share-row"
              data-active={active}
              onClick={() => toggle(roleIds, r.id, onRoles)}
            >
              <span className="share-check">{active ? <Icon name="check" size={12} /> : null}</span>
              <Icon name="shield" size={15} style={{ color: "var(--violet)" }} />
              <span className="min-w-0 flex-1 truncate font-bold">{r.name}</span>
              <span className="text-muted text-[11px]">alle mit dieser Rolle</span>
            </button>
          );
        })}

        {users.length > 0 ? <div className="share-group">Personen</div> : null}
        {users.map((u) => {
          const active = userIds.includes(u.id);
          return (
            <button
              key={u.id}
              type="button"
              className="share-row"
              data-active={active}
              onClick={() => toggle(userIds, u.id, onUsers)}
            >
              <span className="share-check">{active ? <Icon name="check" size={12} /> : null}</span>
              <Avatar name={u.name} src={u.avatarUrl} size={22} />
              <span className="min-w-0 flex-1 truncate font-bold">{u.name}</span>
            </button>
          );
        })}

        {teams.length + roles.length + users.length === 0 ? (
          <p className="text-muted px-2 py-5 text-center text-sm">
            {needle ? "Keine Treffer." : "Nichts vorhanden."}
          </p>
        ) : null}
      </div>
    </>
  );
}
