import React, { useState } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { cn } from '../utils/cn';
import { LogOut } from 'lucide-react';

interface LogoutButtonProps {
  className?: string;
  showConfirmation?: boolean;
  variant?: 'button' | 'link';
}

export const LogoutButton: React.FC<LogoutButtonProps> = ({
  className,
  showConfirmation = true,
  variant = 'button',
}) => {
  const { logout, isLoading } = useAuth();
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);

  const handleLogout = async () => {
    if (showConfirmation && !showConfirmDialog) {
      setShowConfirmDialog(true);
      return;
    }

    try {
      await logout();
      setShowConfirmDialog(false);
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };

  const handleCancel = () => {
    setShowConfirmDialog(false);
  };

  if (showConfirmDialog) {
    return (
      <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div className="bg-white shadow-soft rounded-lg border border-gray-100 p-6 max-w-sm mx-4">
          <h3 className="text-lg font-medium text-primary-800 mb-4">Confirm Logout</h3>
          <p className="text-gray-600 mb-6">Are you sure you want to sign out?</p>
          <div className="flex space-x-3">
            <button
              onClick={handleLogout}
              disabled={isLoading}
              className="flex-1 bg-error-600 text-white py-2 px-4 rounded-md hover:bg-error-700 focus:outline-none focus:ring-2 focus:ring-error-500 disabled:opacity-50 transition-colors duration-200"
            >
              {isLoading ? 'Signing out...' : 'Sign Out'}
            </button>
            <button
              onClick={handleCancel}
              disabled={isLoading}
              className="flex-1 bg-gray-200 text-gray-800 py-2 px-4 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 transition-colors duration-200"
            >
              Cancel
            </button>
          </div>
        </div>
      </div>
    );
  }

  const baseClasses = variant === 'button'
    ? "inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-error-600 hover:bg-error-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-error-500 disabled:opacity-50 transition-colors duration-200"
    : "inline-flex items-center text-sm text-gray-700 hover:text-error-600 focus:outline-none focus:underline transition-colors duration-200";

  return (
    <button
      onClick={handleLogout}
      disabled={isLoading}
      className={cn(baseClasses, className)}
    >
      <LogOut className="h-4 w-4 mr-2" />
      {isLoading ? 'Signing out...' : 'Sign Out'}
    </button>
  );
};

export default LogoutButton;