import React from 'react';
import { Button } from '@/components/ui/button';
import { Icon } from '@iconify/react/dist/iconify.js';
import { useFacebookLogin } from '@/hooks/use-facebook-login';
import { FacebookLoginResponse } from '@/types/facebook-login';

interface FacebookLoginButtonProps {
  appId: string;
  onSuccess?: (response: FacebookLoginResponse) => void;
  onError?: (error: any) => void;
  permissions?: string[];
  className?: string;
  children?: React.ReactNode;
  disabled?: boolean;
}

export const FacebookLoginButton: React.FC<FacebookLoginButtonProps> = ({
  appId,
  onSuccess,
  onError,
  permissions = ['public_profile', 'email'],
  className = '',
  children,
  disabled = false,
}) => {
  const { isLoaded, isLoggedIn, login, logout } = useFacebookLogin({
    appId,
  });

  const handleLogin = async () => {
    try {
      const response = await login(permissions);
      onSuccess?.(response);
    } catch (error) {
      onError?.(error);
    }
  };

  const handleLogout = async () => {
    try {
      await logout();
    } catch (error) {
      onError?.(error);
    }
  };

  if (!isLoaded) {
    return (
      <Button
        variant="default"
        className={`w-full flex items-center justify-center gap-2 bg-[#1877F2] hover:bg-[#166fe0] ${className}`}
        disabled
      >
        <Icon icon="logos:facebook" className="text-xl" />
        Loading...
      </Button>
    );
  }

  if (isLoggedIn) {
    return (
      <Button
        variant="default"
        className={`w-full flex items-center justify-center gap-2 bg-[#1877F2] hover:bg-[#166fe0] ${className}`}
        onClick={handleLogout}
        disabled={disabled}
      >
        <Icon icon="logos:facebook" className="text-xl" />
        {children || 'Disconnect Facebook'}
      </Button>
    );
  }

  return (
    <Button
      variant="default"
      className={`w-full flex items-center justify-center gap-2 bg-[#1877F2] hover:bg-[#166fe0] ${className}`}
      onClick={handleLogin}
      disabled={disabled}
    >
      <Icon icon="logos:facebook" className="text-xl" />
      {children || 'Connect Facebook'}
    </Button>
  );
}; 