/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable @next/next/no-img-element */
/* eslint-disable @typescript-eslint/no-explicit-any */
import React from "react";
import Swal from "sweetalert2";
import { getFormattedAddress } from "../../../lib/Helper";

const DEFAULT_IMAGE = "/images/international/no-image.jpg";

interface Props {
  users: any[];
  handleEdit: (user: any) => void;
  handleChangeStatus: (user: any) => void;
  handleResetPassword: (user: any) => void;
}

const StaffCard = ({
  users = [],
  handleEdit,
  handleChangeStatus,
  handleResetPassword,
}: Props) => {
  const [openId, setOpenId] = React.useState<number | null>(null);
  const dropdownRef = React.useRef<HTMLDivElement | null>(null);

  /* ================= CLICK OUTSIDE ================= */
  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setOpenId(null);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    Swal.fire({
      toast: true,
      position: "top-end",
      icon: "success",
      title: "Copied to clipboard",
      showConfirmButton: false,
      timer: 1500,
    });
  };

  return (
    <>
      <style>
        {`
          .staff-card {
            transition: all 0.25s ease;
            border-radius: 14px;
          }

          .staff-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 12px 25px rgba(0,0,0,0.08);
          }

          .dropdown-menu.show {
            font-size: 12px;
            background: #f7deff;
            border-color: #dedbdb;
            border-radius: 10px;
            animation: fadeIn 0.15s ease-in-out;
          }

          @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-5px); }
            to { opacity: 1; transform: translateY(0); }
          }

          .staff-img {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #eee;
          }

          .address-clamp {
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.4;
            min-height: 2.8em;
          }

          .contact-link {
            cursor: pointer;
            transition: color 0.2s ease;
          }

          .contact-link:hover {
            color: #6f42c1;
            text-decoration: underline;
          }
        `}
      </style>

      {users.map((user: any) => (
        <div key={user.id} className="col-lg-3 order-list-box">
          <div className="card staff-card mb-3 mx-0 order-list-heightSame">
            <div className="content">
              <div className="w-100">
                {/* ===== HEADER ===== */}
                <div className="d-flex align-items-start justify-content-between position-relative mb-2">
                  {/* IMAGE */}
                  <img
                    src={user?.profilePicture || DEFAULT_IMAGE}
                    className="staff-img"
                    onError={(e) =>
                      ((e.target as HTMLImageElement).src = DEFAULT_IMAGE)
                    }
                  />

                  {/* DETAILS */}
                  <div className="flex-grow-1 ms-2">
                    <div className="d-flex justify-content-between align-items-center">
                      <span
                        className={`badge rounded-xl ${
                          user?.isActive ? "bg-purple" : "delybell-yellow"
                        } font-12 px-2`}
                      >
                        {user?.isActive ? "Active" : "Inactive"}
                      </span>

                      <button
                        type="button"
                        className="btn p-0 border-0 bg-transparent"
                        onClick={() =>
                          setOpenId(openId === user.id ? null : user.id)
                        }
                      >
                        <i className="fa fa-ellipsis-v font-12 color-primary" />
                      </button>
                    </div>

                    {/* NAME */}
                    <span
                      className="font-700 font-15 d-block"
                      title={`${user?.firstName} ${user?.lastName}`}
                    >
                      {user?.firstName} {user?.lastName}
                    </span>

                    {/* EMPLOYEE ID */}
                    <p className="mb-0 font-13 opacity-60">
                      {user?.employeeId || "—"}
                    </p>
                  </div>

                  {/* DROPDOWN */}
                  {openId === user.id && (
                    <div
                      ref={dropdownRef}
                      className="dropdown-menu show position-absolute end-0 mt-2"
                      style={{ zIndex: 1050, minWidth: "150px" }}
                    >
                      <button
                        className="dropdown-item d-flex gap-2"
                        onClick={() => {
                          setOpenId(null);
                          handleEdit(user);
                        }}
                      >
                        <i className="fa fa-edit" /> Edit
                      </button>

                      <button
                        className="dropdown-item d-flex gap-2"
                        onClick={() => {
                          setOpenId(null);
                          handleChangeStatus(user);
                        }}
                      >
                        <i
                          className={`fa ${
                            user?.isActive ? "fa-toggle-on" : "fa-toggle-off"
                          }`}
                        />
                        {user?.isActive ? "Deactivate" : "Activate"}
                      </button>

                      <button
                        className="dropdown-item d-flex gap-2"
                        onClick={() => {
                          setOpenId(null);
                          handleResetPassword(user);
                        }}
                      >
                        <i className="fa fa-key" /> Reset Password
                      </button>
                    </div>
                  )}
                </div>

                {/* ADDRESS */}
                <p
                  className="mb-2 font-13 address-clamp"
                  title={getFormattedAddress(user)}
                >
                  <i className="fa fa-map-marker me-1 text-muted" />
                  {getFormattedAddress(user)}
                </p>

                <hr className="mt-2 mb-2" />

                {/* CONTACT */}
                <div className="d-flex justify-content-between align-items-center">
                  <span
                    className="font-13 contact-link"
                    onClick={() => window.open(`tel:${user?.phone}`)}
                  >
                    <i className="fa fa-phone me-1" />
                    {user?.phone || "—"}
                  </span>

                  <span
                    className="font-13 contact-link text-end"
                    onClick={() => copyToClipboard(user?.email)}
                    title="Click to copy email"
                  >
                    <i className="fa fa-envelope me-1" />
                    {user?.email || "—"}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      ))}
    </>
  );
};

export default StaffCard;
