'use client';

import Card from '@/components/ui/Card';
import { DriverIdentity } from '@/components/drivers/DriverIdentity';
import { useTeamRoster } from "@/lib/hooks/team";
import { useState } from 'react';
import type { DriverViewModel } from '@/lib/view-models/DriverViewModel';

type TeamRole = 'owner' | 'admin' | 'member';
type TeamMemberRole = 'owner' | 'manager' | 'member';

interface TeamRosterProps {
  teamId: string;
  memberships: Array<{
    driverId: string;
    driverName: string;
    role: 'owner' | 'manager' | 'member';
    joinedAt: string;
    isActive: boolean;
    avatarUrl: string;
  }>;
  isAdmin: boolean;
  onRemoveMember?: (driverId: string) => void;
  onChangeRole?: (driverId: string, newRole: TeamRole) => void;
}

export default function TeamRoster({
  teamId,
  memberships,
  isAdmin,
  onRemoveMember,
  onChangeRole,
}: TeamRosterProps) {
  const [sortBy, setSortBy] = useState<'role' | 'rating' | 'name'>('rating');

  // Use hook for data fetching
  const { data: teamMembers = [], isLoading: loading } = useTeamRoster(memberships);

  const getRoleBadgeColor = (role: TeamRole) => {
    switch (role) {
      case 'owner':
        return 'bg-warning-amber/20 text-warning-amber';
      case 'admin':
        return 'bg-primary-blue/20 text-primary-blue';
      default:
        return 'bg-charcoal-outline text-gray-300';
    }
  };

  const getRoleLabel = (role: TeamRole | TeamMemberRole) => {
    // Convert manager to admin for display
    const displayRole = role === 'manager' ? 'admin' : role;
    return displayRole.charAt(0).toUpperCase() + displayRole.slice(1);
  };

  function getRoleOrder(role: TeamMemberRole): number {
    switch (role) {
      case 'owner':
        return 0;
      case 'manager':
        return 1;
      case 'member':
        return 2;
      default:
        return 3;
    }
  }

  const sortedMembers = [...teamMembers].sort((a, b) => {
    switch (sortBy) {
      case 'rating': {
        const ratingA = a.rating ?? 0;
        const ratingB = b.rating ?? 0;
        return ratingB - ratingA;
      }
      case 'role': {
        return getRoleOrder(a.role) - getRoleOrder(b.role);
      }
      case 'name': {
        return a.driver.name.localeCompare(b.driver.name);
      }
      default:
        return 0;
    }
  });

  const teamAverageRating = teamMembers.length > 0
    ? teamMembers.reduce((sum, m) => sum + (m.rating || 0), 0) / teamMembers.length
    : 0;

  if (loading) {
    return (
      <Card>
        <div className="text-center py-8 text-gray-400">Loading roster...</div>
      </Card>
    );
  }

  return (
    <Card>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h3 className="text-xl font-semibold text-white">Team Roster</h3>
          <p className="text-sm text-gray-400 mt-1">
            {memberships.length} {memberships.length === 1 ? 'member' : 'members'} • Avg Rating:{' '}
            <span className="text-primary-blue font-medium">{teamAverageRating}</span>
          </p>
        </div>

        <div className="flex items-center gap-2">
          <label className="text-sm text-gray-400">Sort by:</label>
          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value as typeof sortBy)}
            className="px-3 py-1 bg-deep-graphite border border-charcoal-outline rounded text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary-blue"
          >
            <option value="rating">Rating</option>
            <option value="role">Role</option>
            <option value="name">Name</option>
          </select>
        </div>
      </div>

      <div className="space-y-3">
        {sortedMembers.map((member) => {
          const { driver, role, joinedAt, rating, overallRank } = member;

          // Convert manager to admin for display purposes
          const displayRole: TeamRole = role === 'manager' ? 'admin' : (role as TeamRole);
          const canManageMembership = isAdmin && role !== 'owner';

          return (
            <div
              key={driver.id}
              className="flex items-center justify-between p-4 rounded-lg bg-deep-graphite border border-charcoal-outline hover:border-charcoal-outline/60 transition-colors"
            >
              <DriverIdentity
                driver={driver as DriverViewModel}
                href={`/drivers/${driver.id}?from=team&teamId=${teamId}`}
                contextLabel={getRoleLabel(role)}
                meta={
                  <span>
                    {driver.country} • Joined {new Date(joinedAt).toLocaleDateString()}
                  </span>
                }
                size="md"
              />

              {rating !== null && (
                <div className="flex items-center gap-6 text-center">
                  <div>
                    <div className="text-lg font-bold text-primary-blue">
                      {rating}
                    </div>
                    <div className="text-xs text-gray-400">Rating</div>
                  </div>
                  {overallRank !== null && (
                    <div>
                      <div className="text-sm text-gray-300">#{overallRank}</div>
                      <div className="text-xs text-gray-500">Rank</div>
                    </div>
                  )}
                </div>
              )}

              {canManageMembership && (
                <div className="flex items-center gap-2">
                  <select
                    className="px-3 py-2 bg-iron-gray border-0 rounded text-white ring-1 ring-inset ring-charcoal-outline focus:ring-2 focus:ring-primary-blue transition-all duration-150 text-sm"
                    value={displayRole}
                    onChange={(e) =>
                      onChangeRole?.(driver.id, e.target.value as TeamRole)
                    }
                  >
                    <option value="member">Member</option>
                    <option value="admin">Admin</option>
                  </select>

                  <button
                    onClick={() => onRemoveMember?.(driver.id)}
                    className="px-3 py-2 bg-danger-red/20 hover:bg-danger-red/30 text-danger-red rounded text-sm font-medium transition-colors"
                  >
                    Remove
                  </button>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {memberships.length === 0 && (
        <div className="text-center py-8 text-gray-400">No team members yet.</div>
      )}
    </Card>
  );
}