import React, { useEffect, useState } from "react";
import { useContactProfile } from "../../hooks/useDirectory";
import Avatar from "../common/Avatar";
import moment from "moment";
import NotesDirectory from "./NotesDirectory";

const ProfileContactDirectory = ({ contact, setOpen_contact, closeModal }) => {
  const { contactProfile, loading, refetch } = useContactProfile(contact?.id);
  const [copiedIndex, setCopiedIndex] = useState(null);

  const [profileContactState, setProfileContactState] = useState(null);
  const [expanded, setExpanded] = useState(false);

  const description = profileContactState?.description || "";
  const limit = 500;

  const toggleReadMore = () => setExpanded(!expanded);

  const isLong = description.length > limit;
  const displayText = expanded
    ? description
    : description.slice(0, limit) + (isLong ? "..." : "");

  useEffect(() => {
    if (contactProfile) {
      const names = (contact?.name || "").trim().split(" ");
      let firstName = "";
      let middleName = "";
      let lastName = "";
      let fullName = contact?.name || "";

      // Logic to determine first, middle, and last names
      if (names.length === 1) {
        firstName = names[0];
      } else if (names.length === 2) {
        firstName = names[0];
        lastName = names[1];
      } else if (names.length >= 3) {
        firstName = names[0];
        middleName = names[1]; // This was an error in the original prompt, corrected to names[1]
        lastName = names[names.length - 1];
        // Reconstruct full name to be precise with spacing
        fullName = `${firstName} ${middleName ? middleName + ' ' : ''}${lastName}`;
      } else {
        // Fallback if no names or empty string
        firstName = "Contact";
        fullName = "Contact";
      }


      setProfileContactState({
        ...contactProfile,
        firstName: contactProfile.firstName || firstName,
        // Adding middleName and lastName to the state for potential future use or more granular access
        middleName: contactProfile.middleName || middleName,
        lastName: contactProfile.lastName || lastName,
        fullName: contactProfile.fullName || fullName, // Prioritize fetched fullName, fallback to derived
      });
    }
  }, [contactProfile, contact?.name]);

  const handleCopy = (email, index) => {
    navigator.clipboard.writeText(email);
    setCopiedIndex(index);
    setTimeout(() => setCopiedIndex(null), 2000);
  };

  return (
    <div className="p-1">
      <div className="text-center m-0 p-0">
        <p className="fw-semibold fs-6 m-0">Contact Profile</p>
      </div>
      <div>
        <div className="d-flex align-items-center mb-2">
          <Avatar
            size="sm"
            classAvatar="m-0"
            firstName={
              (contact?.name || "").trim().split(" ")[0]?.charAt(0) || ""
            }
            lastName={
              (contact?.name || "").trim().split(" ")[1]?.charAt(0) || ""
            }
          />
          <div className="d-flex flex-column text-start ms-1">
            <span className="m-0 fw-semibold">{contact?.name}</span>
            <small className="text-secondary small-text">
              {profileContactState?.designation}
            </small>
          </div>
        </div>
        <div className="row ms-9">
          <div className="col-12 col-md-6 d-flex flex-column text-start">
            {profileContactState?.contactEmails?.length > 0 && (
              <div className="d-flex mb-2 align-items-start">
                <div
                  className="d-flex align-items-start"
                  style={{ width: "100px", minWidth: "130px" }}
                >
                  <span className="d-flex">
                    <i className="bx bx-envelope bx-xs me-2 mt-1"></i>
                    <span>Email</span>
                  </span>
                  <span style={{ marginLeft: "45px" }}>:</span>
                </div>

                <div style={{ flex: 1 }}>
                  <ul className="list-unstyled mb-0">
                    {profileContactState.contactEmails.map((email, idx) => (
                      <li className="d-flex align-items-center mb-1" key={idx}>
                        <span className="me-1 text-break overflow-wrap">
                          {email.emailAddress}
                        </span>
                        <i
                          className={`bx bx-copy-alt cursor-pointer bx-xs text-start ${copiedIndex === idx ? "text-secondary" : "text-primary"
                            }`}
                          title={copiedIndex === idx ? "Copied!" : "Copy Email"}
                          style={{ flexShrink: 0 }}
                          onClick={() => handleCopy(email.emailAddress, idx)}
                        ></i>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            )}

            {profileContactState?.contactPhones?.length > 0 && (
              <div className="d-flex mb-2 align-items-start">
                <div className="d-flex" style={{ minWidth: "130px" }}>
                  <span className="d-flex align-items-center">
                    <i className="bx bx-phone bx-xs me-2"></i>
                    <span>Phone</span>
                  </span>
                  <span style={{ marginLeft: "40px" }}>:</span>
                </div>

                <div>
                  <ul className="list-inline mb-0">
                    {profileContactState.contactPhones.map((phone, idx) => (
                      <li className="list-inline-item me-1" key={idx}>
                        {phone.phoneNumber}
                        {idx < profileContactState.contactPhones.length - 1 && ","}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            )}

            {profileContactState?.createdAt && (
              <div className="d-flex mb-2 align-items-start">
                <div className="d-flex" style={{ minWidth: "130px" }}>
                  <span className="d-flex align-items-center">
                    <i className="bx bx-calendar-week bx-xs me-2"></i>
                    <span>Created</span>
                  </span>
                  <span style={{ marginLeft: "30px" }}>:</span>
                </div>

                <div className="d-flex align-items-center">
                  <span>
                    {moment(profileContactState.createdAt).format("DD MMMM, YYYY")}
                  </span>
                </div>
              </div>
            )}

            {profileContactState?.address && (
              <div className="d-flex mb-2 align-items-start">
                <div className="d-flex" style={{ minWidth: "130px" }}>
                  <span className="d-flex align-items-start">
                    <i className="bx bx-map bx-xs me-2 mt-1"></i>
                    <span>Location</span>
                  </span>
                  <span style={{ marginLeft: "26px" }}>:</span>
                </div>
                <div>
                  <span className="text-break small">{profileContactState.address}</span>
                </div>
              </div>
            )}
          </div>

          <div className="col-12 col-md-6 d-flex flex-column text-start">
            {profileContactState?.organization && (
              <div className="d-flex mb-2 align-items-start">
                <div className="d-flex" style={{ minWidth: "130px" }}>
                  <span className="d-flex align-items-center">
                    <i className="fa-solid fa-briefcase me-2"></i>
                    <span>Organization</span>
                  </span>
                  <span className="ms-2">:</span>
                </div>

                <div className="d-flex align-items-center">
                  <span style={{ wordBreak: "break-word" }}>
                    {profileContactState.organization}
                  </span>
                </div>
              </div>
            )}

            {profileContactState?.contactCategory && (
              <div className="d-flex mb-2 align-items-start">
                <div className="d-flex" style={{ minWidth: "130px" }}>
                  <span className="d-flex align-items-center">
                    <i className="bx bx-user bx-xs me-2"></i>
                    <span>Category</span>
                  </span>
                  <span style={{ marginLeft: "28px" }}>:</span>
                </div>

                <div>
                  <ul className="list-inline mb-0">
                    <li className="list-inline-item">
                      {profileContactState.contactCategory.name}
                    </li>
                  </ul>
                </div>
              </div>
            )}

            {profileContactState?.tags?.length > 0 && (
              <div className="d-flex mb-2 align-items-start">
                <div className="d-flex" style={{ minWidth: "130px" }}>
                  <span className="d-flex align-items-center">
                    <i className="fa-solid fa-tag me-2"></i>
                    <span>Tags</span>
                  </span>
                  <span style={{ marginLeft: "60px" }}>:</span>
                </div>

                <div>
                  <ul className="list-inline mb-0">
                    {profileContactState.tags.map((tag, index) => (
                      <li key={index} className="list-inline-item">
                        {tag.name}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            )}

            {profileContactState?.buckets?.length > 0 && (
              <div className="d-flex mb-2 align-items-start">
                <div className="d-flex" style={{ minWidth: "130px" }}>
                  <span className="d-flex align-items-center">
                    <i className="bx bx-layer me-1"></i>
                    <span>Buckets</span>
                  </span>
                  <span style={{ marginLeft: "35px" }}>:</span>
                </div>

                <div>
                  <ul className="list-inline mb-0">
                    {profileContactState.buckets.map((bucket) => (
                      <li className="list-inline-item me-2" key={bucket.id}>
                        <span className="badge bg-label-primary my-1">
                          {bucket.name}
                        </span>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            )}
          </div>

          {profileContactState?.projects?.length > 0 && (
            <div className="d-flex mb-2 align-items-start">
              <div className="d-flex" style={{ minWidth: "130px" }}>
                <span className="d-flex align-items-center">
                  <i className="bx bx-building-house me-1"></i>
                  <span>Projects</span>
                </span>
                <span style={{ marginLeft: "28px" }}>:</span>
              </div>

              <div className="text-start">
                <ul className="list-inline mb-0">
                  {profileContactState.projects.map((project, index) => (
                    <li className="list-inline-item me-2" key={project.id}>
                      {project.name}
                      {index < profileContactState.projects.length - 1 && ","}
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          )}
        </div>

        <div className="d-flex mb-2 align-items-start" style={{ marginLeft: "3rem" }}>
          <div className="d-flex" style={{ minWidth: "130px" }}>
            <span className="d-flex align-items-start">
              <i className="bx bx-book me-1"></i>
              <span>Description</span>
            </span>
            <span style={{ marginLeft: "10px" }}>:</span>
          </div>

          <div className="text-start">
            {displayText}
            {isLong && (
              <>
                <br />
                <span
                  onClick={toggleReadMore}
                  className="text-primary mx-1 cursor-pointer"
                >
                  {expanded ? "Read less" : "Read more"}
                </span>
              </>
            )}
          </div>
        </div>


        <hr className="my-1" />
        <NotesDirectory
          refetchProfile={refetch}
          isLoading={loading}
          contactProfile={profileContactState}
          setProfileContact={setProfileContactState}
        />
      </div>
    </div>
  );
};

export default ProfileContactDirectory;