"use client";

import { useMemo, useState } from "react";

import { toast } from "@/lib/toast";
import {
  createGroup,
  deleteGroup,
  duplicateGroup,
  renameGroup,
  type GroupCard,
} from "@/services/travel-policy/travel-policy.client";
import { MSG, cx, flightShortText, groupLook } from "@/services/travel-policy/policy-format";

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

/**
 * Create / rename / duplicate / delete a policy group (PRD §8.5's four modals).
 *
 * All four share one validation shape, ported from the design's `wireName`: the
 * name is checked as it is typed, the message appears only once the field has
 * been touched, and the submit button is disabled while it is invalid. The
 * copy is the design's own `MSG` table.
 *
 * Uniqueness is checked against the groups already on screen, which is what the
 * design does. It is advisory: the server owns the real answer (it compares
 * case-insensitively across the whole company and has `@@unique([companyId,
 * name])` behind that), and a `GROUP_NAME_TAKEN` reply is put back on the field
 * rather than shown as a toast. Two tabs open on the same page is the realistic
 * way the client-side check goes stale.
 */

/** Shared name field + live validation. Returns the pieces each modal renders. */
function useGroupName(params: {
  groups: readonly GroupCard[];
  initial?: string;
  exceptId?: string;
}) {
  const [value, setValue] = useState(params.initial ?? "");
  const [touched, setTouched] = useState(Boolean(params.initial));
  /** Set from a server reply, cleared on the next keystroke. */
  const [serverError, setServerError] = useState<string | null>(null);

  const taken = useMemo(() => {
    const needle = value.trim().toLowerCase();
    return params.groups.some(
      (g) => g.id !== params.exceptId && g.name.trim().toLowerCase() === needle
    );
  }, [value, params.groups, params.exceptId]);

  const localError = (() => {
    const name = value.trim();
    if (!name) return MSG.nameEmpty;
    if (name.length > 60) return MSG.nameLong;
    if (taken) return MSG.nameTaken;
    return null;
  })();

  const error = serverError ?? (touched ? localError : null);

  return {
    value,
    setValue: (next: string) => {
      setValue(next);
      setTouched(true);
      setServerError(null);
    },
    blur: () => setTouched(true),
    error,
    /** Blocks submit on the LOCAL check only — a stale server error must not
     *  wedge the button once the admin has started typing something else. */
    invalid: Boolean(localError),
    setServerError,
    touch: () => setTouched(true),
  };
}

function NameField({
  id,
  label,
  field,
  placeholder,
  autoFocus,
}: {
  id: string;
  label: string;
  field: ReturnType<typeof useGroupName>;
  placeholder?: string;
  autoFocus?: boolean;
}) {
  return (
    <div>
      <label className="bz-label" htmlFor={id}>
        {label}
      </label>
      <input
        type="text"
        className={cx("bz-input", field.error && "is-invalid")}
        id={id}
        maxLength={80}
        value={field.value}
        placeholder={placeholder}
        autoComplete="off"
        autoFocus={autoFocus}
        onChange={(e) => field.setValue(e.target.value)}
        onBlur={field.blur}
        aria-invalid={field.error ? true : undefined}
        aria-describedby={field.error ? `${id}-error` : undefined}
      />
      <span className="bz-error" id={`${id}-error`} role="alert">
        {field.error ?? ""}
      </span>
    </div>
  );
}

function DescriptionField({
  id,
  value,
  onChange,
}: {
  id: string;
  value: string;
  onChange: (next: string) => void;
}) {
  return (
    <div>
      <label className="bz-label" htmlFor={id}>
        Description <span className="bz-muted">(optional)</span>
      </label>
      <input
        type="text"
        className="bz-input"
        id={id}
        maxLength={120}
        value={value}
        placeholder="Who is in this group?"
        autoComplete="off"
        onChange={(e) => onChange(e.target.value)}
      />
    </div>
  );
}

/* ── Create ────────────────────────────────────────────────────────────────── */

export function CreateGroupModal({
  token,
  groups,
  onClose,
  onCreated,
}: {
  token: string;
  groups: readonly GroupCard[];
  onClose: () => void;
  onCreated: (group: { id: string; name: string }) => void;
}) {
  const name = useGroupName({ groups });
  const [description, setDescription] = useState("");
  // Pre-selected to the first group, as the design's radio list is. There is
  // deliberately no "start blank": a group with no rows silently follows the
  // PRD defaults, which is a confusing thing to have chosen on purpose.
  const [copyFrom, setCopyFrom] = useState(groups[0]?.id ?? "");
  const [submitting, setSubmitting] = useState(false);

  const submit = async () => {
    name.touch();
    if (name.invalid || submitting) return;
    setSubmitting(true);
    const res = await createGroup(token, {
      name: name.value.trim(),
      description: description.trim() || undefined,
      copyFromGroupId: copyFrom || undefined,
    });
    setSubmitting(false);

    if (!res.success || !res.data) {
      // A name clash belongs on the field, not in a toast the admin has to
      // read and then re-find the cause of.
      if (res.code === "GROUP_NAME_TAKEN") {
        name.setServerError(MSG.nameTaken);
        return;
      }
      toast.error(res.message ?? "We could not create that group. Please try again.");
      return;
    }

    toast.success(res.message ?? `Group “${res.data.name}” created.`);
    onCreated(res.data);
  };

  return (
    <PolicyOverlay label="Create group" width={540} onClose={onClose} busy={submitting}>
      <form
        noValidate
        onSubmit={(e) => {
          e.preventDefault();
          void submit();
        }}
      >
        <PolicyModalHead
          icon="bi-collection"
          title="Create group"
          sub="Employees in this group follow its travel rules."
        />
        <div className="bz-modal-body">
          <NameField
            id="tpNewName"
            label="Group name"
            field={name}
            placeholder="e.g. Customer Success"
            autoFocus
          />
          <DescriptionField id="tpNewDesc" value={description} onChange={setDescription} />
          <fieldset className="bp-copy-set">
            <legend className="bz-label">Start with rules from</legend>
            <div className="bp-copy-list">
              {groups.map((group) => {
                const look = groupLook(group);
                return (
                  <label className="bp-copy" key={group.id}>
                    <input
                      type="radio"
                      name="copyFrom"
                      value={group.id}
                      checked={copyFrom === group.id}
                      onChange={() => setCopyFrom(group.id)}
                    />
                    <span className={`bz-icon-tile tone-${look.tone}`} aria-hidden="true">
                      <i className={`bi ${look.icon}`} />
                    </span>
                    <span className="bp-copy-text">
                      <strong>{group.name}</strong>
                      <small>{flightShortText(group.flights.DOMESTIC_FLIGHT)}</small>
                    </span>
                  </label>
                );
              })}
            </div>
          </fieldset>
        </div>
        <div className="bz-modal-foot">
          <button
            type="button"
            className="bz-btn bz-btn-secondary"
            onClick={onClose}
            disabled={submitting}
          >
            Cancel
          </button>
          <button
            type="submit"
            className="bz-btn bz-btn-primary"
            disabled={name.invalid || submitting}
          >
            {submitting ? "Creating…" : "Create group"}
          </button>
        </div>
      </form>
    </PolicyOverlay>
  );
}

/* ── Rename ────────────────────────────────────────────────────────────────── */

export function RenameGroupModal({
  token,
  group,
  groups,
  onClose,
  onRenamed,
}: {
  token: string;
  group: GroupCard;
  groups: readonly GroupCard[];
  onClose: () => void;
  onRenamed: () => void;
}) {
  const name = useGroupName({ groups, initial: group.name, exceptId: group.id });
  const [description, setDescription] = useState(group.description ?? "");
  const [submitting, setSubmitting] = useState(false);

  const submit = async () => {
    name.touch();
    if (name.invalid || submitting) return;

    const nextName = name.value.trim();
    const nextDescription = description.trim();
    if (nextName === group.name && nextDescription === (group.description ?? "")) {
      onClose();
      return;
    }

    setSubmitting(true);
    const res = await renameGroup(token, group.id, {
      name: nextName,
      description: nextDescription,
    });
    setSubmitting(false);

    if (!res.success) {
      if (res.code === "GROUP_NAME_TAKEN") {
        name.setServerError(MSG.nameTaken);
        return;
      }
      toast.error(res.message ?? "We could not rename that group. Please try again.");
      return;
    }

    toast.success(res.message ?? "Group renamed.");
    onRenamed();
  };

  return (
    <PolicyOverlay label={`Rename ${group.name}`} width={500} onClose={onClose} busy={submitting}>
      <form
        noValidate
        onSubmit={(e) => {
          e.preventDefault();
          void submit();
        }}
      >
        <PolicyModalHead
          icon="bi-pencil"
          title={<>Rename &ldquo;{group.name}&rdquo;</>}
          sub="Members and rules stay the same."
        />
        <div className="bz-modal-body">
          <NameField id="tpRename" label="Group name" field={name} autoFocus />
          <DescriptionField id="tpRedesc" value={description} onChange={setDescription} />
        </div>
        <div className="bz-modal-foot">
          <button
            type="button"
            className="bz-btn bz-btn-secondary"
            onClick={onClose}
            disabled={submitting}
          >
            Cancel
          </button>
          <button
            type="submit"
            className="bz-btn bz-btn-primary"
            disabled={name.invalid || submitting}
          >
            {submitting ? "Saving…" : "Save"}
          </button>
        </div>
      </form>
    </PolicyOverlay>
  );
}

/* ── Duplicate ─────────────────────────────────────────────────────────────── */

/** "Sales (copy)", then "(copy 2)" — the design's `uniqueName`. */
function copyName(base: string, groups: readonly GroupCard[]): string {
  const taken = (candidate: string) =>
    groups.some((g) => g.name.trim().toLowerCase() === candidate.trim().toLowerCase());
  let candidate = `${base} (copy)`;
  let n = 2;
  while (taken(candidate)) candidate = `${base} (copy ${n++})`;
  return candidate;
}

export function DuplicateGroupModal({
  token,
  group,
  groups,
  onClose,
  onDuplicated,
}: {
  token: string;
  group: GroupCard;
  groups: readonly GroupCard[];
  onClose: () => void;
  onDuplicated: () => void;
}) {
  const name = useGroupName({ groups, initial: copyName(group.name, groups) });
  const [moveMembers, setMoveMembers] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  // The design offers the checkbox only when there is something to move. The
  // default group's followers are ungrouped rows, not members, so it never has
  // any to move.
  const canMove = !group.isDefault && group.memberCount > 0;

  const submit = async () => {
    name.touch();
    if (name.invalid || submitting) return;
    setSubmitting(true);
    const res = await duplicateGroup(token, group.id, {
      name: name.value.trim(),
      moveMembers: canMove && moveMembers,
    });
    setSubmitting(false);

    if (!res.success || !res.data) {
      if (res.code === "GROUP_NAME_TAKEN") {
        name.setServerError(MSG.nameTaken);
        return;
      }
      toast.error(res.message ?? "We could not duplicate that group. Please try again.");
      return;
    }

    toast.success(res.message ?? `“${res.data.name}” created.`);
    onDuplicated();
  };

  return (
    <PolicyOverlay
      label={`Duplicate ${group.name}`}
      width={500}
      onClose={onClose}
      busy={submitting}
    >
      <form
        noValidate
        onSubmit={(e) => {
          e.preventDefault();
          void submit();
        }}
      >
        <PolicyModalHead
          icon="bi-copy"
          title={<>Duplicate &ldquo;{group.name}&rdquo;</>}
          sub="All flight and hotel rules are copied to the new group."
        />
        <div className="bz-modal-body">
          <NameField id="tpDupName" label="New group name" field={name} autoFocus />
          {canMove && (
            <label className="bp-option">
              <input
                type="checkbox"
                checked={moveMembers}
                onChange={(e) => setMoveMembers(e.target.checked)}
              />
              <span>
                <strong>Also move members to the new group</strong>
                <small>
                  {group.memberCount} {group.memberCount === 1 ? "member" : "members"} will leave{" "}
                  {group.name}.
                </small>
              </span>
            </label>
          )}
        </div>
        <div className="bz-modal-foot">
          <button
            type="button"
            className="bz-btn bz-btn-secondary"
            onClick={onClose}
            disabled={submitting}
          >
            Cancel
          </button>
          <button
            type="submit"
            className="bz-btn bz-btn-primary"
            disabled={name.invalid || submitting}
          >
            {submitting ? "Duplicating…" : "Duplicate"}
          </button>
        </div>
      </form>
    </PolicyOverlay>
  );
}

/* ── Delete ────────────────────────────────────────────────────────────────── */

export function DeleteGroupModal({
  token,
  group,
  groups,
  onClose,
  onDeleted,
}: {
  token: string;
  group: GroupCard;
  groups: readonly GroupCard[];
  onClose: () => void;
  onDeleted: () => void;
}) {
  const others = groups.filter((g) => g.id !== group.id);
  // Defaults to the company's default group, which is PRD §8.5's own default
  // for this select.
  const [moveTo, setMoveTo] = useState(others.find((g) => g.isDefault)?.id ?? others[0]?.id ?? "");
  const [submitting, setSubmitting] = useState(false);

  const submit = async () => {
    if (submitting) return;
    setSubmitting(true);
    const res = await deleteGroup(token, group.id, group.memberCount > 0 ? moveTo : undefined);
    setSubmitting(false);

    if (!res.success) {
      toast.error(res.message ?? "We could not delete that group. Please try again.");
      return;
    }

    toast.success(res.message ?? `“${group.name}” deleted.`);
    onDeleted();
  };

  return (
    <PolicyOverlay label={`Delete ${group.name}?`} width={500} onClose={onClose} busy={submitting}>
      <PolicyModalHead
        icon="bi-trash3"
        tone="coral"
        title={<>Delete &ldquo;{group.name}&rdquo;?</>}
        sub="This group’s rules will be deleted. Requests already submitted keep their policy results."
      />
      <div className="bz-modal-body">
        {group.memberCount > 0 ? (
          <div>
            <label className="bz-label" htmlFor="tpMoveTo">
              Move {group.memberCount} {group.memberCount === 1 ? "member" : "members"} to
            </label>
            <div className="bz-select">
              <select
                className="bz-input"
                id="tpMoveTo"
                value={moveTo}
                onChange={(e) => setMoveTo(e.target.value)}
              >
                {others.map((g) => (
                  <option value={g.id} key={g.id}>
                    {g.name}
                  </option>
                ))}
              </select>
            </div>
            <span className="bz-help">
              They&rsquo;ll follow that group&rsquo;s rules from their next request.
            </span>
          </div>
        ) : (
          <p className="bz-muted">This group has no members.</p>
        )}
      </div>
      <div className="bz-modal-foot">
        <button
          type="button"
          className="bz-btn bz-btn-secondary"
          onClick={onClose}
          disabled={submitting}
          autoFocus
        >
          Cancel
        </button>
        <button
          type="button"
          className="bz-btn bz-btn-danger"
          onClick={() => void submit()}
          disabled={submitting}
        >
          {submitting ? "Deleting…" : "Delete group"}
        </button>
      </div>
    </PolicyOverlay>
  );
}
