import React, { useState } from "react";
import { getSearchUsers } from "../../../services/factoryBuilder/collab/getSearchUsers";
import { useParams } from "react-router-dom";
import { shareProject } from "../../../services/factoryBuilder/collab/shareProject";
import { getUserData } from "../../../functions/getUserData";

interface UserData {
  _id: string;
  Email: string;
  userName: string;
}

interface MultiEmailProps {
  users: any,
  getData: any,
}
const MultiEmailInvite: React.FC<MultiEmailProps> = ({ users, getData }) => {
  const [emails, setEmails] = useState<any>([]);
  const [searchedEmail, setSearchedEmail] = useState<UserData[]>([]);
  const [inputFocus, setInputFocus] = useState(false);
  const [inputValue, setInputValue] = useState("");
  const { projectId } = useParams();
  const { userId } = getUserData();

  const handleAddEmail = async (selectedUser: UserData) => {
    if (!projectId || !selectedUser) return
    const trimmedEmail = inputValue.trim();
    setEmails((prev: any[]) => {
      if (!selectedUser) return prev;
      const isNotCurrentUser = selectedUser._id !== userId;
      const alreadyExistsInEmails = prev.some(email => email._id === selectedUser._id);
      const alreadyExistsInUsers = users.some((val: any) => val.userId === selectedUser._id);
      if (isNotCurrentUser && !alreadyExistsInEmails && !alreadyExistsInUsers) {
        return [...prev, selectedUser];
      }

      return prev;
    });
    setInputValue(""); // Clear the input field after adding
  };
  const handleSearchMail = async (e: any) => {
    setInputValue(e.target.value);
    const trimmedEmail = e.target.value.trim();

    if (trimmedEmail.length < 3) return;
    try {
      const searchedMail = await getSearchUsers(trimmedEmail);
      const filteredEmail = searchedMail.sharchMail?.filtered;
      if (filteredEmail) {
        setSearchedEmail(filteredEmail)
      }
    } catch (error) {
      console.error("Failed to search mail:", error);
    }
  };


  const handleKeyDown = async (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter" || e.key === "," && searchedEmail.length > 0) {
      e.preventDefault();
      handleAddEmail(searchedEmail[0]);
    }
  };

  const handleRemoveEmail = (idToRemove: string) => {
    setEmails((prev: any) => prev.filter((email: any) => email._id !== idToRemove));
  };


  const validateEmail = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const handleInvite = () => {
    if (!projectId) return;
    try {
      emails.forEach((user: any) => {
        shareProject(user._id, projectId)
          .then((res) => {
            console.log("sharedProject:", res);

          })
          .catch((err) => {
            console.error("Error sharing project:", err);
          });
        setEmails([])
        setInputValue("")
      });
      setTimeout(() => {
        getData()
      }, 1000);
    } catch (error) {
      console.error("General error:", error);
    }
  };

  return (
    <div className="multi-email-invite-input-container">
      <div className={`multi-email-invite-input${inputFocus ? " active" : ""}`}>
        {emails.map((email: any, index: number) => (
          <div key={index} className="entered-emails">
            {email.Email}
            <span onClick={() => handleRemoveEmail(email._id)}>&times;</span>
          </div>
        ))}
        <input
          type="text"
          value={inputValue}
          onChange={(e) => handleSearchMail(e)}
          onFocus={() => setInputFocus(true)}
          // onBlur={() => setInputFocus(false)}
          onKeyDown={handleKeyDown}
          placeholder="Enter email and press Enter or comma to seperate"
        />
      </div>
      <div onClick={handleInvite} className="invite-button">
        Add
      </div>
      {inputFocus && inputValue.length > 2 && searchedEmail && searchedEmail.length > 0 && (
        <div className="users-list-container">
          {/* list available users here */}
          {searchedEmail.map((val: any, i: any) => (
            <div onClick={(e) => {
              handleAddEmail(val)
              setInputFocus(false)
            }} key={i} >
              {val?.Email}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default MultiEmailInvite;
