'use client';

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

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

export default function JoinTeamButton({
  teamId,
  requiresApproval = false,
  onUpdate,
}: JoinTeamButtonProps) {
  const currentDriverId = useEffectiveDriverId();
  const [showConfirmation, setShowConfirmation] = useState(false);

  // 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?.();
      setShowConfirmation(false);
    },
  });

  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>
  );
}