import { useState, useEffect, useRef } from 'react';
import Dropdown from '@/Components/Dropdown';
import { Link, useForm, usePage } from '@inertiajs/react';

const RightSideActions = () => {
  const user = usePage().props.auth.user;
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsDropdownOpen(false);
      }
    };

    // Add event listener
    document.addEventListener('mousedown', handleClickOutside);

    // Cleanup event listener on component unmount
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const handleLogout = async () => {
    try {
      await fetch('/sanctum/csrf-cookie', { method: 'GET', credentials: 'include' });
  
      const response = await fetch('/logout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
      });
  
      if (response.ok) {
        window.location.href = '/login';
      }
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };
  
  
  

  return (
    <div className="flex justify-end items-center space-x-4 relative">
      {/* Search Icon */}
      <button className="p-2 rounded-full hover:bg-gray-100">
        <svg
          className="w-6 h-6 text-gray-600"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
          />
        </svg>
      </button>

      {/* Notification Icon */}
      <button className="p-2 rounded-full hover:bg-gray-100">
        <svg
          className="w-6 h-6 text-gray-600"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
          />
        </svg>
      </button>

      {/* User Profile Dropdown */}
      <div className="relative" ref={dropdownRef}>
        <button
          className="flex items-center space-x-2 focus:outline-none"
          onClick={() => setIsDropdownOpen(!isDropdownOpen)}
        >
          <span className="hidden md:block text-gray-700">{user.name}</span>
          <img
            src="https://randomuser.me/api/portraits/men/85.jpg"
            alt="Profile"
            className="w-8 h-8 rounded-full object-cover"
          />
        </button>

        {/* Dropdown Menu */}
        {isDropdownOpen && (
          <div className="absolute right-0 mt-2 w-56 bg-white shadow-lg rounded-lg overflow-hidden z-10">
            {/* User Info */}
            <div className="px-4 py-3 border-b border-gray-200">
              <p className="text-sm font-medium text-gray-900">{user.name}</p>
              <p className="text-xs text-gray-500">{user.email}</p>
            </div>

            {/* Menu Items */}
            <div className="py-1">
              <Dropdown.Link href={route('profile.edit')} className='ml-6'>Profile</Dropdown.Link>
              <DropdownItem label="Messages" />
              <DropdownItem  label="Help" />
              <DropdownItem  label="Settings" />
              <DropdownItem  label="New" />
              <DropdownItem  label="Lock Screen" />
              <Dropdown.Link  icon="sign-out-alt" href={route('logout')} className='ml-6' method="post" as="button"> Log Out </Dropdown.Link>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Reusable Dropdown Item Component
const DropdownItem = ({ icon, label, onClick }) => {
    const getIconClass = (icon) => {
      switch (icon) {
        case 'user':
          return 'fas fa-user';
        case 'envelope':
          return 'fas fa-envelope';
        case 'question-circle':
          return 'fas fa-question-circle';
        case 'cog':
          return 'fas fa-cog';
        case 'plus':
          return 'fas fa-plus';
        case 'lock':
          return 'fas fa-lock';
        case 'sign-out-alt':
          return 'fas fa-sign-out-alt';
        default:
          return '';
      }
    };
  
    return (
      <a
        href="#"
        onClick={onClick} // Attach onClick to the anchor element
        className="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition duration-150"
      >
        <i className={`${getIconClass(icon)} w-4 h-4 mr-2 text-gray-500`}></i>
        <span>{label}</span>
      </a>
    );
  };
  

export default RightSideActions;