'use client';

import Button from '@/components/ui/Button';
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
import { useEffect, useState } from 'react';
import { useServices } from '@/lib/services/ServiceProvider';

type TeamMembershipStatus = 'active' | 'pending' | 'inactive';

interface TeamMembership {
  teamId: string;
  driverId: string;
  role: 'owner' | 'manager' | 'driver';
  status: TeamMembershipStatus;
  joinedAt: Date | string;
}

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

export default function JoinTeamButton({
  teamId,
  requiresApproval = false,
  onUpdate,
}: JoinTeamButtonProps) {
  const [loading, setLoading] = useState(false);
  const currentDriverId = useEffectiveDriverId();
  const [membership, setMembership] = useState<TeamMembership | null>(null);
  const { teamService, teamJoinService } = useServices();

  useEffect(() => {
    const load = async () => {
      try {
        const m = await teamService.getMembership(teamId, currentDriverId);
        setMembership(m as TeamMembership | null);
      } catch (error) {
        console.error('Failed to load membership:', error);
      }
    };
    void load();
  }, [teamId, currentDriverId, teamService]);

  const handleJoin = async () => {
    setLoading(true);
    try {
      if (requiresApproval) {
        const existing = await teamService.getMembership(teamId, currentDriverId);
        if (existing) {
          throw new Error('Already a member or have a pending request');
        }

        // Note: Team join request functionality would need to be added to teamService
        // For now, we'll use a placeholder
        console.log('Saving join request:', {
          id: `team-request-${Date.now()}`,
          teamId,
          driverId: currentDriverId,
          requestedAt: new Date(),
        });
        alert('Join request sent! Wait for team approval.');
      } else {
        // Note: Team join functionality would need to be added to teamService
        // For now, we'll use a placeholder
        console.log('Joining team:', { teamId, driverId: 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 {
      // Note: Leave team functionality would need to be added to teamService
      // For now, we'll use a placeholder
      console.log('Leaving team:', { teamId, driverId: 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>
    );
  }

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