import { InnerCard } from "@/components/menu-slider";
import { searchByPermission } from "@/components/pages/add-emp/searchPermissions";
import { Badge } from "@/components/ui/badge";
import {
  Menubar,
  MenubarContent,
  MenubarItem,
  MenubarMenu,
  MenubarTrigger,
} from "@/components/ui/menubar";
import Axios from "@/lib/Axios";
import { PaginationStructT, PermissionsDataT } from "@/types/global";
import { UserListT } from "@/types/user";
import { UserLogsT } from "@/types/userLogs";
import { useQuery } from "@tanstack/react-query";
import { format, compareAsc } from "date-fns";
import { Ellipsis } from "lucide-react";
import Link from "next/link";
import { useState, useRef, useEffect } from 'react';
import { Pencil } from "lucide-react";

const permissionList = [
  "Permission 1",
  "Permission 2",
  "Permission 3",
  "Permission 4",
  "Permission 5",
  "Permission 6",
];

export function UserMenuDetails(userData: UserListT) {
  return (
    <>
      <InnerCard>
        <>
          <p className="text-danger text-xl underline">Basis Details</p>
          <div className="text-xs mt-2 text-black">
            <p className="">
              Name: <span className="font-medium">{userData?.user?.name}</span>
            </p>
            <p className="">
              Role: <span className="font-medium">{userData?.role?.name}</span>
            </p>
            <p className="">
              Report To:{" "}
              <span className="font-medium">
                {userData?.reports_to?.user.name}
              </span>
            </p>
            <p className="">
              Status:{" "}
              <span className="font-medium">
                <Badge
                  className={`${
                    userData?.is_active ? "bg-primary" : "bg-danger"
                  }`}
                >
                  {userData?.is_active ? "Active" : "Inactive"}
                </Badge>
              </span>
            </p>
          </div>
        </>
      </InnerCard>
      <PermissionList userData={userData} />

      <InnerCard>
        <>
          <p className="text-danger text-xl underline mb-3">User Logs</p>

          <div className="space-y-1 text-black">
            <UserLogs id={userData.id} />
          </div>
        </>
      </InnerCard>
    </>
  );
}

function UserLogs({ id }: { id: number }) {
  const { data, error, isLoading, isSuccess, refetch } = useQuery({
    queryKey: ["user-logs-in-menu"],
    queryFn: fetchData,
  });

  async function fetchData() {
    return Axios.get<PaginationStructT<UserLogsT[]>>("core/users_activity/", {
      params: {
        user__id: id,
      },
    }).then((res) => res.data.data);
  }

  return (
    <div className="min-h-52 text-xs space-y-4">
      {data?.map((log) => {
        return (
          <div className="" key={log.id}>
            <p className="tracking-widest">
              {format(log.time, "MMM dd hh:mm:ss ")} :
              <span className="">{log?.changed_object}</span>
            </p>
          </div>
        );
      })}
    </div>
  );
}  

function PermissionList({ userData }: { userData: UserListT }) {
  const [isPopupOpen, setIsPopupOpen] = useState(false);
  const popupRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  const togglePopup = () => {
    setIsPopupOpen(!isPopupOpen);
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        popupRef.current &&
        !popupRef.current.contains(event.target as Node) &&
        buttonRef.current &&
        !buttonRef.current.contains(event.target as Node)
      ) {
        setIsPopupOpen(false);
      }
    };

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

  return (
    <InnerCard>
      <div className="flex justify-between items-center text-black">
        <p className="text-danger text-xl underline">Permissions</p>
      
        <button
          ref={buttonRef}
          onClick={togglePopup}
          className="underline text-danger text-xs focus:outline-none hover:text-danger-dark"
        >
          View all
        </button>
      </div>

      <div className="grid grid-cols-2 gap-2 mt-3 text-black">
        {userData.granted_permissions?.slice(0, 6).map((item, index) => (
          <label
            key={index}
            className="text-xs flex items-start gap-2 leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
          >
            <input
              type="checkbox"
              defaultChecked={true}
              disabled
              className="w-4 h-4 text-amber-700 bg-gray-100 border-gray-300 rounded focus:ring-amber-500 disabled:opacity-70"
            />
            {item.name}
          </label>
        ))}
      </div>

      {isPopupOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-30 flex items-center justify-center z-50">
          <div
            ref={popupRef}
            className="bg-white bg-opacity-95 rounded-lg p-6 w-full max-w-lg max-h-[80vh] overflow-y-auto border border-gray-200 shadow-xl"
          >
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-danger text-xl underline">All Permissions</h2>
              <div className="flex items-center gap-5">
                <Link
                  href={"user/manage-user/" + userData.id}
                  className="underline text-danger text-xs hover:text-danger-dark focus:outline-none"
                >
                  Edit
                </Link>
                <button
                  onClick={togglePopup}
                  className="text-gray-500 hover:text-gray-700 focus:outline-none"
                >
                  ✕
                </button>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-2 text-black">
              {userData.granted_permissions?.map((item, index) => (
                <label
                  key={index}
                  className="text-xs flex items-start gap-2 leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                >
                  <input
                    type="checkbox"
                    defaultChecked={true}
                    disabled
                    className="w-4 h-4 text-amber-700 bg-gray-100 border-gray-300 rounded focus:ring-amber-500 disabled:opacity-70"
                  />
                  {item.name}
                </label>
              ))}
            </div>
            <div className="mt-4 flex justify-end">
              <button
                onClick={togglePopup}
                className="underline text-danger text-xs hover:text-danger-dark focus:outline-none"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </InnerCard>
  );
}

export function UserMenuSliderOptions(data: UserListT) {
  return (
    <Link
      href={"user/manage-user/" + data.id}
      className="inline-flex items-center gap-2 text-white px-2 py-1 rounded-md transition-colors duration-200"
      style={{ backgroundColor: '#d4af37' }}
      onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#5a6b2d'}
      onMouseLeave={(e) => e.currentTarget.style.backgroundColor = '#d9c0a2'}
    >
      <Pencil className="w-4 h-4" />
      Edit
    </Link>
  );
}