"use client";

import { useCallback, useEffect, useRef, useState } from "react";

import { toast } from "@/lib/toast";
import {
  fetchMembers,
  resolveMemberEmails,
  saveMembers,
  type MemberPerson,
} from "@/services/travel-policy/travel-policy.client";
import { cx, plural } from "@/services/travel-policy/policy-format";

import PolicyOverlay, { PolicyDrawerHead } from "./PolicyOverlay";

/**
 * Manage members (PRD §8.5's drawer).
 *
 * ── Staged, not live ──────────────────────────────────────────────────────
 *
 * Adds and removes are held locally and committed once, which is the design's
 * behaviour and the right one: moving someone between groups changes which
 * travel policy judges their next request, and an admin assembling a team of
 * six should be able to change their mind about the third without six separate
 * writes already having landed.
 *
 * So the list below is three things interleaved — staged adds, real members,
 * and real members staged for removal — each labelled, each undoable, and none
 * of them true until Save members.
 *
 * ── What the CSV is ──────────────────────────────────────────────────────
 *
 * A bulk SELECTOR, not an invite path. It holds work emails of people who
 * already exist; anyone who does not is reported as not found, and inviting
 * them is Workforce's job. Parsed here and resolved to ids by the server, which
 * also says which group each person would move from — the drawer cannot know
 * that for someone who was never in the search results.
 *
 * The default group never reaches this component: its membership is "everyone
 * not in another group", which is not a list, and the API refuses it.
 */

const SEARCH_DEBOUNCE_MS = 250;
const MAX_CSV_BYTES = 2 * 1024 * 1024;

/** The design's own permissive scrape: anything email-shaped, however the file
 *  is delimited. A real CSV parser would reject the hand-edited files these
 *  actually are. */
const EMAIL_PATTERN = /[^\s,;"'<>]+@[^\s,;"'<>]+\.[a-z]{2,}/gi;

interface CsvNote {
  tone: "ok" | "warn" | "error";
  text: string;
}

export default function ManageMembersDrawer({
  token,
  group,
  onClose,
  onSaved,
}: {
  token: string;
  group: { id: string; name: string };
  onClose: () => void;
  onSaved: () => void;
}) {
  const [members, setMembers] = useState<MemberPerson[]>([]);
  const [defaultGroupName, setDefaultGroupName] = useState("All employees");
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);

  const [search, setSearch] = useState("");
  /**
   * The last search that came back, tagged with the term it answered.
   *
   * Not a bare `candidates` array cleared by the search effect: clearing it was
   * a synchronous `setState` in an effect body, and it was also the only thing
   * stopping the previous term's hits from showing against the new one. Pairing
   * the results with their term makes both fall out of the render instead —
   * `candidates` is empty unless the result on hand answers the term being
   * typed, and `searching` is simply "the term has no answer yet".
   */
  const [result, setResult] = useState<{ term: string; people: MemberPerson[] } | null>(null);
  const [filter, setFilter] = useState("");

  /** Staged, newest first — the design's `adds`. Full records, because a person
   *  added from a CSV is not in `candidates` and has to carry their own name. */
  const [adds, setAdds] = useState<MemberPerson[]>([]);
  const [removes, setRemoves] = useState<string[]>([]);

  const [csvNote, setCsvNote] = useState<CsvNote | null>(null);
  const [dragging, setDragging] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);
  const searchRef = useRef<HTMLInputElement>(null);

  const loadMembers = useCallback(
    async (term: string) => {
      const res = await fetchMembers(token, group.id, { search: term || undefined });
      if (!res.success || !res.data) {
        return { ok: false as const, message: res.message };
      }
      return { ok: true as const, data: res.data };
    },
    [token, group.id]
  );

  // First load: members only, no search term.
  useEffect(() => {
    let cancelled = false;
    (async () => {
      const res = await loadMembers("");
      if (cancelled) return;
      setLoading(false);
      if (!res.ok) {
        setLoadError(res.message ?? "We could not load this group’s members. Please try again.");
        return;
      }
      setMembers(res.data.members);
      setDefaultGroupName(res.data.defaultGroupName);
    })();
    return () => {
      cancelled = true;
    };
  }, [loadMembers]);

  // Candidate search, debounced. Cancelled on change so a slow earlier response
  // cannot overwrite a newer one — and every `setState` sits inside the timeout
  // callback, never in the effect body.
  useEffect(() => {
    const term = search.trim();
    if (!term) return;
    let cancelled = false;
    const timer = setTimeout(async () => {
      const res = await loadMembers(term);
      if (cancelled) return;
      // Tagged with the term, so a response that lands after the admin has
      // typed on is simply not shown rather than shown against the wrong query.
      setResult({ term, people: res.ok ? res.data.candidates : [] });
    }, SEARCH_DEBOUNCE_MS);
    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [search, loadMembers]);

  const term = search.trim();
  const candidates = result?.term === term ? result.people : [];
  const searching = Boolean(term) && result?.term !== term;

  const stageAdd = (person: MemberPerson) => {
    // Already staged for removal? Then adding them back is just an undo.
    if (removes.includes(person.id)) {
      setRemoves((ids) => ids.filter((id) => id !== person.id));
    } else if (!adds.some((p) => p.id === person.id) && !members.some((m) => m.id === person.id)) {
      setAdds((list) => [person, ...list]);
    }
    // Clearing the box is enough: `candidates` is derived from it.
    setSearch("");
    searchRef.current?.focus();
  };

  const pendingCount = adds.length + removes.length;
  const total = members.length - removes.length + adds.length;

  const readFile = async (file: File | undefined) => {
    if (!file) return;
    if (file.size > MAX_CSV_BYTES) {
      setCsvNote({ tone: "error", text: "This file is over 2 MB. Upload a smaller CSV." });
      return;
    }

    const text = await file.text();
    const emails = Array.from(
      new Set((text.match(EMAIL_PATTERN) ?? []).map((e) => e.toLowerCase()))
    );
    if (fileRef.current) fileRef.current.value = "";

    if (emails.length === 0) {
      setCsvNote({ tone: "error", text: `No work emails found in ${file.name}.` });
      return;
    }

    const res = await resolveMemberEmails(token, group.id, emails);
    if (!res.success || !res.data) {
      setCsvNote({
        tone: "error",
        text: res.message ?? "We could not read that file. Please try again.",
      });
      return;
    }

    const { resolved, alreadyInGroup, notFound } = res.data;
    // Un-stage any removal the file re-asserts, then stage the rest.
    const resolvedIds = new Set(resolved.map((p) => p.id));
    setRemoves((ids) => ids.filter((id) => !resolvedIds.has(id)));
    setAdds((list) => {
      const known = new Set([...list.map((p) => p.id), ...members.map((m) => m.id)]);
      return [...resolved.filter((p) => !known.has(p.id)), ...list];
    });

    setCsvNote({
      tone: notFound.length > 0 ? "warn" : "ok",
      text: [
        `${plural(resolved.length, "person", "people")} added from ${file.name}`,
        notFound.length > 0 && `${notFound.length} not found`,
        alreadyInGroup.length > 0 && `${alreadyInGroup.length} already in this group`,
      ]
        .filter(Boolean)
        .join(" · "),
    });
  };

  const submit = async () => {
    if (pendingCount === 0 || submitting) return;
    setSubmitting(true);
    const res = await saveMembers(token, group.id, {
      add: adds.map((p) => p.id),
      remove: removes,
    });
    setSubmitting(false);

    if (!res.success) {
      toast.error(res.message ?? "We could not update the members. Please try again.");
      // A stale list is the usual cause (someone deactivated since the drawer
      // opened), so reloading is the useful next step rather than leaving the
      // admin staring at names the server has just rejected.
      if (res.code === "EMPLOYEE_NOT_AVAILABLE") {
        const reload = await loadMembers("");
        if (reload.ok) {
          setMembers(reload.data.members);
          setAdds([]);
          setRemoves([]);
        }
      }
      return;
    }

    toast.success(res.message ?? `Members updated for ${group.name}.`);
    onSaved();
  };

  const matchesFilter = (person: MemberPerson) => {
    const q = filter.trim().toLowerCase();
    if (!q) return true;
    return person.name.toLowerCase().includes(q) || person.workEmail.toLowerCase().includes(q);
  };

  const visibleAdds = adds.filter(matchesFilter);
  const visibleMembers = members.filter(matchesFilter);

  return (
    <PolicyOverlay
      label={`Manage members · ${group.name}`}
      variant="drawer"
      onClose={onClose}
      busy={submitting}
    >
      <PolicyDrawerHead title={`Manage members · ${group.name}`} onClose={onClose} />

      <div className="bz-modal-body bp-mm">
        <p className="bp-mm-intro">
          Each employee is in one group. Adding someone here moves them out of their current group.
        </p>

        <label className="bz-label" htmlFor="tpMemSearch">
          Add employees
        </label>
        <div className="bz-affix is-icon">
          <i className="bi bi-search bz-affix-pre" aria-hidden="true" />
          <input
            ref={searchRef}
            type="search"
            className="bz-input"
            id="tpMemSearch"
            placeholder="Search by name or work email"
            autoComplete="off"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onKeyDown={(e) => {
              // Enter takes the first hit, so a known name can be added
              // without reaching for the mouse.
              if (e.key !== "Enter") return;
              e.preventDefault();
              const first = candidates.find(
                (c) => !adds.some((a) => a.id === c.id) && !members.some((m) => m.id === c.id)
              );
              if (first) stageAdd(first);
            }}
            autoFocus
          />
        </div>

        <ul className="bp-mm-results" aria-live="polite">
          {term && searching && <li className="is-empty">Searching…</li>}
          {term &&
            !searching &&
            candidates
              .filter(
                (c) => !adds.some((a) => a.id === c.id) && !members.some((m) => m.id === c.id)
              )
              .map((person) => (
                <li key={person.id}>
                  <span className="bp-mm-person">
                    <strong>{person.name}</strong>
                    <small>
                      {person.workEmail} · Currently in: {person.currentGroup}
                    </small>
                  </span>
                  <button
                    type="button"
                    className="bz-btn bz-btn-secondary bz-btn-sm"
                    onClick={() => stageAdd(person)}
                  >
                    Add
                  </button>
                </li>
              ))}
          {term &&
            !searching &&
            candidates.filter(
              (c) => !adds.some((a) => a.id === c.id) && !members.some((m) => m.id === c.id)
            ).length === 0 && (
              <li className="is-empty">
                No one outside {group.name} matches &ldquo;{term}&rdquo;.
              </li>
            )}
        </ul>

        <div className="bp-mm-csv">
          <label
            className={cx("bp-mm-upload", dragging && "is-over")}
            htmlFor="tpMemCsv"
            onDragEnter={(e) => {
              e.preventDefault();
              setDragging(true);
            }}
            onDragOver={(e) => {
              e.preventDefault();
              setDragging(true);
            }}
            onDragLeave={(e) => {
              e.preventDefault();
              setDragging(false);
            }}
            onDrop={(e) => {
              e.preventDefault();
              setDragging(false);
              void readFile(e.dataTransfer.files[0]);
            }}
          >
            <input
              ref={fileRef}
              type="file"
              id="tpMemCsv"
              accept=".csv,.txt,text/csv,text/plain"
              className="bz-sr"
              onChange={(e) => void readFile(e.target.files?.[0])}
            />
            <i className="bi bi-upload" aria-hidden="true" />
            <span>Upload CSV of work emails</span>
          </label>
          <span className="bp-mm-csv-hint">or drop a file here · max 2 MB</span>
        </div>
        {csvNote && (
          <p
            className={cx(
              "bp-csv-note",
              csvNote.tone === "error" && "is-error",
              csvNote.tone === "warn" && "is-warn"
            )}
            role="status"
          >
            {csvNote.text}
          </p>
        )}

        <div className="bp-mm-head">
          <h4 className="bp-mm-title">Members ({total})</h4>
          <div className="bz-affix is-icon bp-mem-filter">
            <i className="bi bi-filter bz-affix-pre" aria-hidden="true" />
            <label className="bz-sr" htmlFor="tpMemFilter">
              Filter members
            </label>
            <input
              type="search"
              className="bz-input"
              id="tpMemFilter"
              placeholder="Filter members"
              autoComplete="off"
              value={filter}
              onChange={(e) => setFilter(e.target.value)}
            />
          </div>
        </div>

        <ul className="bp-mm-list">
          {loading && <li className="is-empty">Loading members…</li>}
          {!loading && loadError && <li className="is-empty">{loadError}</li>}

          {!loading &&
            !loadError &&
            visibleAdds.map((person) => (
              <li className="is-new" key={`add-${person.id}`}>
                <span className="bp-mm-person">
                  <strong>{person.name}</strong>
                  <small>
                    {person.workEmail} · from {person.currentGroup}
                  </small>
                </span>
                <span className="bp-mm-actions">
                  <span className="bp-mm-tag is-new">To add</span>
                  <button
                    type="button"
                    className="bz-link"
                    onClick={() => setAdds((list) => list.filter((p) => p.id !== person.id))}
                  >
                    Undo
                  </button>
                </span>
              </li>
            ))}

          {!loading &&
            !loadError &&
            visibleMembers.map((person) =>
              removes.includes(person.id) ? (
                <li className="is-removed" key={person.id}>
                  <span className="bp-mm-person">
                    <strong>{person.name}</strong>
                    <small>Moves to {defaultGroupName}</small>
                  </span>
                  <span className="bp-mm-actions">
                    <span className="bp-mm-tag is-rm">To remove</span>
                    <button
                      type="button"
                      className="bz-link"
                      onClick={() => setRemoves((ids) => ids.filter((id) => id !== person.id))}
                    >
                      Undo
                    </button>
                  </span>
                </li>
              ) : (
                <li key={person.id}>
                  <span className="bp-mm-person">
                    <strong>{person.name}</strong>
                    <small>{person.workEmail}</small>
                  </span>
                  <button
                    type="button"
                    className="bz-link is-danger"
                    onClick={() => setRemoves((ids) => [...ids, person.id])}
                    aria-label={`Remove ${person.name}`}
                  >
                    Remove
                  </button>
                </li>
              )
            )}

          {!loading && !loadError && visibleAdds.length === 0 && visibleMembers.length === 0 && (
            <li className="is-empty">
              {filter.trim()
                ? "No members match this filter."
                : "No members yet. Search above or upload a CSV to add people."}
            </li>
          )}
        </ul>
      </div>

      <div className="bz-modal-foot">
        <span className="bz-modal-note">
          {adds.length} to add · {removes.length} to remove
        </span>
        <button
          type="button"
          className="bz-btn bz-btn-secondary"
          onClick={onClose}
          disabled={submitting}
        >
          Cancel
        </button>
        <button
          type="button"
          id="tpMemSave"
          className="bz-btn bz-btn-primary"
          onClick={() => void submit()}
          disabled={pendingCount === 0 || submitting}
        >
          {submitting ? "Saving…" : "Save members"}
        </button>
      </div>
    </PolicyOverlay>
  );
}
