"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { assignStaffAction, setStaffRoleAction } from "@/lib/actions/team";

type Option = { id: string; name: string };

export function StaffAssignmentCard({
  client,
  departments,
  positions,
  teams,
}: {
  client: {
    id: string;
    name: string;
    email: string;
    avatarPath: string;
    departmentId: string;
    positionId: string;
    teamIds: string[];
  };
  departments: Option[];
  positions: (Option & { departmentId: string })[];
  teams: Option[];
}) {
  const [pending, startTransition] = useTransition();
  const router = useRouter();

  function submit(form: HTMLFormElement) {
    const data = new FormData(form);
    startTransition(async () => {
      await assignStaffAction(client.id, data);
      router.refresh();
    });
  }

  const positionsForDept = positions.filter((p) => p.departmentId === client.departmentId);

  return (
    <div className="bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5">
      <div className="flex items-center justify-between gap-3 mb-3">
        <div className="min-w-0">
          <Link href={`/de/admin/team/${client.id}`} className="text-sm font-medium truncate hover:underline">
            {client.name}
          </Link>
          <p className="text-xs text-[var(--rk-ink-muted)] truncate">{client.email}</p>
        </div>
        <button
          disabled={pending}
          onClick={() => {
            if (confirm(`${client.name} nicht mehr als Mitarbeiter führen?`)) {
              startTransition(async () => {
                await setStaffRoleAction(client.id, false);
                router.refresh();
              });
            }
          }}
          className="text-xs text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50 shrink-0"
        >
          Mitarbeiter entfernen
        </button>
      </div>

      <form onChange={(e) => submit(e.currentTarget)} className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <label className="flex flex-col gap-1 text-xs">
          <span className="text-[var(--rk-ink-muted)]">Abteilung</span>
          <select
            name="departmentId"
            defaultValue={client.departmentId}
            disabled={pending}
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-2.5 py-1.5 text-sm"
          >
            <option value="">—</option>
            {departments.map((d) => (
              <option key={d.id} value={d.id}>
                {d.name}
              </option>
            ))}
          </select>
        </label>
        <label className="flex flex-col gap-1 text-xs">
          <span className="text-[var(--rk-ink-muted)]">Position</span>
          <select
            name="positionId"
            defaultValue={client.positionId}
            disabled={pending}
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-2.5 py-1.5 text-sm"
          >
            <option value="">—</option>
            {positionsForDept.map((p) => (
              <option key={p.id} value={p.id}>
                {p.name}
              </option>
            ))}
          </select>
        </label>
        <div className="flex flex-col gap-1 text-xs sm:col-span-2">
          <span className="text-[var(--rk-ink-muted)]">Teams</span>
          <div className="flex flex-wrap gap-2">
            {teams.map((t) => (
              <label key={t.id} className="flex items-center gap-1.5 border border-white/15 rounded-full px-2.5 py-1">
                <input
                  type="checkbox"
                  name="teamIds"
                  value={t.id}
                  defaultChecked={client.teamIds.includes(t.id)}
                  disabled={pending}
                  className="h-3 w-3"
                />
                {t.name}
              </label>
            ))}
            {teams.length === 0 && <span className="text-[var(--rk-ink-muted)]">Keine Teams angelegt</span>}
          </div>
        </div>
      </form>
    </div>
  );
}
