'use client';

import React from 'react';
import { Button } from '@/ui/Button';
import { useEffectiveDriverId } from "@/hooks/useEffectiveDriverId";
import { useTeamMembership } from "@/hooks/team/useTeamMembership";
import { useJoinTeam } from "@/hooks/team/useJoinTeam";
import { useLeaveTeam } from "@/hooks/team/useLeaveTeam";

interface JoinTeamButtonProps {
  teamId: string;
  requiresApproval?: boolean;
  onUpdate?: () => void;
}

export function JoinTeamButton({
  teamId,
  requiresApproval = false,
  onUpdate,
}: JoinTeamButtonProps) {
  const currentDriverId = useEffectiveDriverId();

  // Use hooks for data fetching
  const { data: membership, isLoading: loadingMembership } = useTeamMembership(teamId, currentDriverId || '');

  // Use hooks for mutations
  const joinTeamMutation = useJoinTeam({
    onSuccess: () => {
      onUpdate?.();
    },
  });

  const leaveTeamMutation = useLeaveTeam({
    onSuccess: () => {
      onUpdate?.();
    },
  });

  const handleJoin = () => {
    if (!currentDriverId) {
      alert('Please log in to join a team');
      return;
    }
    joinTeamMutation.mutate({
      teamId,
      driverId: currentDriverId,
      requiresApproval,
    });
  };

  const handleLeave = () => {
    if (!currentDriverId) {
      alert('Please log in to leave a team');
      return;
    }
    if (!confirm('Are you sure you want to leave this team?')) {
      return;
    }
    leaveTeamMutation.mutate({
      teamId,
      driverId: currentDriverId,
    });
  };

  // Loading state
  if (loadingMembership) {
    return (
      <Button variant="primary" disabled>
        Loading...
      </Button>
    );
  }

  // Already a member
  if (membership && membership.isActive) {
    if (membership.role === 'owner') {
      return (
        <Button variant="secondary" disabled>
          Team Owner
        </Button>
      );
    }

    return (
      <Button
        variant="danger"
        onClick={handleLeave}
        disabled={leaveTeamMutation.isPending}
      >
        {leaveTeamMutation.isPending ? 'Leaving...' : 'Leave Team'}
      </Button>
    );
  }

  // Can join
  return (
    <Button
      variant="primary"
      onClick={handleJoin}
      disabled={joinTeamMutation.isPending || !currentDriverId}
    >
      {joinTeamMutation.isPending
        ? 'Processing...'
        : requiresApproval
        ? 'Request to Join'
        : 'Join Team'}
    </Button>
  );
}
