'use client';

import { useState } from 'react';
import Button from '@/components/ui/Button';
import {
  getCurrentDriverId,
  getTeamMembership,
  getDriverTeam,
  joinTeam,
  requestToJoinTeam,
  leaveTeam,
} from '@/lib/team-data';

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

export default function JoinTeamButton({
  teamId,
  requiresApproval = false,
  onUpdate,
}: JoinTeamButtonProps) {
  const [loading, setLoading] = useState(false);
  const currentDriverId = getCurrentDriverId();
  const membership = getTeamMembership(teamId, currentDriverId);
  const currentTeam = getDriverTeam(currentDriverId);

  const handleJoin = async () => {
    setLoading(true);
    try {
      if (requiresApproval) {
        requestToJoinTeam(teamId, currentDriverId);
        alert('Join request sent! Wait for team approval.');
      } else {
        joinTeam(teamId, currentDriverId);
        alert('Successfully joined team!');
      }
      onUpdate?.();
    } catch (error) {
      alert(error instanceof Error ? error.message : 'Failed to join team');
    } finally {
      setLoading(false);
    }
  };

  const handleLeave = async () => {
    if (!confirm('Are you sure you want to leave this team?')) {
      return;
    }

    setLoading(true);
    try {
      leaveTeam(teamId, currentDriverId);
      alert('Successfully left team');
      onUpdate?.();
    } catch (error) {
      alert(error instanceof Error ? error.message : 'Failed to leave team');
    } finally {
      setLoading(false);
    }
  };

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

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

  // Already on another team
  if (currentTeam && currentTeam.team.id !== teamId) {
    return (
      <Button variant="secondary" disabled>
        Already on {currentTeam.team.name}
      </Button>
    );
  }

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