"use client";

import React, { useState } from "react";
import Modal from "@/components/elements/Modal";
import RoundedButton from "@/components/elements/RoundedButton";
import useAxios from "@/hooks/useAxios";
import ChatRoomMemberPicker, {
  ChatRoomMember,
} from "@/components/chat/ChatRoomMemberPicker";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { getStoredUserId } from "@/lib/auth/session";
import { ensureRoomAesKey } from "@/lib/e2ee";

type Props = {
  open: boolean;
  onClose: () => void;
  onAdded: () => void;
  roomId: string;
  existingMemberIds?: string[];
};

export default function AddChatRoomMembersModal({
  open,
  onClose,
  onAdded,
  roomId,
  existingMemberIds = [],
}: Props) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [selected, setSelected] = useState<ChatRoomMember[]>([]);
  const [submitting, setSubmitting] = useState(false);

  const handleClose = () => {
    setSelected([]);
    onClose();
  };

  const submit = async () => {
    const memberIds = selected
      .map((member) => member._id)
      .filter((id) => !existingMemberIds.includes(id));

    if (memberIds.length === 0) {
      toast.error(t("chats.toast.selectNewMember"));
      return;
    }

    setSubmitting(true);
    try {
      await request("POST", `/chat-rooms/${roomId}/members`, {
        member_ids: memberIds,
      });
      const uid = getStoredUserId();
      if (uid) {
        try {
          await ensureRoomAesKey(String(uid), roomId);
        } catch {
          /* wrap sync best-effort */
        }
      }
      toast.success(t("chats.toast.membersAdded"));
      setSelected([]);
      onAdded();
      onClose();
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { error?: string; message?: string } } })
          ?.response?.data?.error ||
        (err as { response?: { data?: { message?: string } } })?.response?.data
          ?.message;
      toast.error(message || t("chats.toast.addMembersFailed"));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal
      isOpen={open}
      onClose={handleClose}
      height="fit"
      elevated
      panelClassName="!p-0 max-h-[90dvh] w-full overflow-y-auto"
    >
      <div className="px-4 py-5 pb-[calc(5rem+env(safe-area-inset-bottom,0px))]">
        <div className="mx-auto w-full max-w-sm">
          <h2 className="mb-4 text-center font-semibold">
            {t("chats.modal.addMembersTitle")}
          </h2>
          <ChatRoomMemberPicker selected={selected} onChange={setSelected} />
          <div className="mt-5 flex flex-col items-center gap-3">
            <RoundedButton
              type="button"
              variant="primary"
              disabled={submitting}
              onClick={() => void submit()}
              className="h-10 w-full max-w-[200px] text-sm"
            >
              {submitting ? t("chats.actions.addingMembers") : t("chats.actions.add")}
            </RoundedButton>
            <RoundedButton
              type="button"
              onClick={handleClose}
              className="h-10 w-full max-w-[200px] text-sm"
            >
              {t("chats.actions.cancel")}
            </RoundedButton>
          </div>
        </div>
      </div>
    </Modal>
  );
}
