'use client';

import React, { useState, useRef } from 'react';
import Link from 'next/link';
import { LogOut, User, ChevronDown } from 'lucide-react';
import { useClickOutside } from '@/hooks/useClickOutside';
import { cn } from '@/utils/helpers';

interface UserDropdownProps {
  user: {
    firstName?: string;
    lastName?: string;
    email?: string;
  } | null;
  profilePath: string;
  onLogout: () => void;
  accentColor?: 'blue' | 'green';
  className?: string;
}

const accentColors = {
  blue: 'bg-blue-600',
  green: 'bg-green-600',
};

export const UserDropdown: React.FC<UserDropdownProps> = ({
  user,
  profilePath,
  onLogout,
  accentColor = 'blue',
  className,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useClickOutside(dropdownRef, () => setIsOpen(false), isOpen);

  const initials = `${user?.firstName?.charAt(0) || ''}${user?.lastName?.charAt(0) || ''}`;

  return (
    <div ref={dropdownRef} className={cn('relative', className)}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-3 px-4 py-2 rounded-lg hover:bg-gray-100 transition-colors"
      >
        <div className="flex items-center gap-3">
          <div className={cn(
            'w-10 h-10 rounded-full flex items-center justify-center text-white font-bold',
            accentColors[accentColor]
          )}>
            {initials}
          </div>
          <div className="text-left">
            <p className="text-sm font-bold text-gray-900">
              {user?.firstName} {user?.lastName}
            </p>
            <p className="text-xs text-gray-500">{user?.email}</p>
          </div>
        </div>
        <ChevronDown className={cn(
          'w-4 h-4 text-gray-500 transition-transform',
          isOpen && 'rotate-180'
        )} />
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-64 bg-white rounded-lg shadow-lg border border-gray-200 py-2 z-50">
          <Link
            href={profilePath}
            onClick={() => setIsOpen(false)}
            className="flex items-center gap-3 px-4 py-3 hover:bg-gray-100 transition-colors"
          >
            <User className="w-4 h-4 text-gray-600" />
            <span className="text-sm font-medium text-gray-700">Profil</span>
          </Link>
          <div className="border-t border-gray-200 my-1" />
          <button
            onClick={() => {
              setIsOpen(false);
              onLogout();
            }}
            className="w-full flex items-center gap-3 px-4 py-3 hover:bg-red-50 transition-colors text-left"
          >
            <LogOut className="w-4 h-4 text-red-600" />
            <span className="text-sm font-medium text-red-600">Deconnexion</span>
          </button>
        </div>
      )}
    </div>
  );
};

export default UserDropdown;
