import { GroupRoles } from 'pl-api';
import React from 'react';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl';

import Button from '@/components/ui/button';
import {
  useJoinGroupMutation,
  useLeaveGroupMutation,
} from '@/queries/groups/use-group-relationship';
import { useModalsActions } from '@/stores/modals';
import toast from '@/toast';

import type { Group } from 'pl-api';

interface IGroupActionButton {
  group: Pick<Group, 'id' | 'locked' | 'relationship'>;
}

const messages = defineMessages({
  confirmationConfirm: { id: 'confirmations.leave_group.confirm', defaultMessage: 'Leave' },
  confirmationHeading: { id: 'confirmations.leave_group.heading', defaultMessage: 'Leave group' },
  confirmationMessage: {
    id: 'confirmations.leave_group.message',
    defaultMessage: 'You are about to leave the group. Do you want to continue?',
  },
  joinRequestSuccess: {
    id: 'group.join.request_success',
    defaultMessage: 'Request sent to group owner',
  },
  joinSuccess: { id: 'group.join.success', defaultMessage: 'Group joined successfully!' },
  leaveSuccess: { id: 'group.leave.success', defaultMessage: 'Left the group' },
});

const GroupActionButton = ({ group }: IGroupActionButton) => {
  const intl = useIntl();

  const { openModal } = useModalsActions();
  const { mutate: joinGroup, isPending: isJoiningGroup } = useJoinGroupMutation(group.id);
  const { mutate: leaveGroup, isPending: isLeavingGroup } = useLeaveGroupMutation(group.id);

  const isRequested = group.relationship?.requested;
  const isNonMember = !group.relationship?.member && !isRequested;
  const isOwner = group.relationship?.role === GroupRoles.OWNER;
  const isAdmin = group.relationship?.role === GroupRoles.ADMIN;

  const onJoinGroup = () =>
    joinGroup(undefined, {
      onSuccess: () => {
        toast.success(
          group.locked
            ? intl.formatMessage(messages.joinRequestSuccess)
            : intl.formatMessage(messages.joinSuccess),
        );
      },
      // onError: (error) => {
      //   const message = error.response?.json?.error;
      //   if (message) {
      //     toast.error(message);
      //   }
      // },
    });

  const onLeaveGroup = () => {
    openModal('CONFIRM', {
      heading: intl.formatMessage(messages.confirmationHeading),
      message: intl.formatMessage(messages.confirmationMessage),
      confirm: intl.formatMessage(messages.confirmationConfirm),
      onConfirm: () =>
        leaveGroup(undefined, {
          onSuccess: () => {
            toast.success(intl.formatMessage(messages.leaveSuccess));
          },
        }),
    });
  };

  const onCancelRequest = () => leaveGroup();

  if (isOwner || isAdmin) {
    return (
      <Button theme='secondary' to='/groups/$groupId/manage' params={{ groupId: group.id }}>
        <FormattedMessage id='group.manage' defaultMessage='Manage group' />
      </Button>
    );
  }

  if (isNonMember) {
    return (
      <Button theme='primary' onClick={onJoinGroup} disabled={isJoiningGroup || isLeavingGroup}>
        {group.locked ? (
          <FormattedMessage id='group.join.private' defaultMessage='Request access' />
        ) : (
          <FormattedMessage id='group.join.public' defaultMessage='Join group' />
        )}
      </Button>
    );
  }

  if (isRequested) {
    return (
      <Button
        theme='secondary'
        onClick={onCancelRequest}
        disabled={isJoiningGroup || isLeavingGroup}
      >
        <FormattedMessage id='group.cancel_request' defaultMessage='Cancel request' />
      </Button>
    );
  }

  return (
    <Button theme='secondary' onClick={onLeaveGroup} disabled={isJoiningGroup || isLeavingGroup}>
      <FormattedMessage id='group.leave' defaultMessage='Leave group' />
    </Button>
  );
};

export { GroupActionButton as default };
