'use client';

import Card from '@/components/ui/Card';
import type { LeagueAdminRosterJoinRequestViewModel } from '@/lib/view-models/LeagueAdminRosterJoinRequestViewModel';
import type { LeagueAdminRosterMemberViewModel } from '@/lib/view-models/LeagueAdminRosterMemberViewModel';
import type { MembershipRole } from '@/lib/types/MembershipRole';
import { useServices } from '@/lib/services/ServiceProvider';
import { useParams } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';

const ROLE_OPTIONS: MembershipRole[] = ['owner', 'admin', 'steward', 'member'];

export function RosterAdminPage() {
  const params = useParams();
  const leagueId = params.id as string;

  const { leagueService } = useServices();

  const [loading, setLoading] = useState(true);
  const [joinRequests, setJoinRequests] = useState<LeagueAdminRosterJoinRequestViewModel[]>([]);
  const [members, setMembers] = useState<LeagueAdminRosterMemberViewModel[]>([]);

  const loadRoster = async () => {
    setLoading(true);
    try {
      const [requestsVm, membersVm] = await Promise.all([
        leagueService.getAdminRosterJoinRequests(leagueId),
        leagueService.getAdminRosterMembers(leagueId),
      ]);
      setJoinRequests(requestsVm);
      setMembers(membersVm);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void loadRoster();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [leagueId]);

  const pendingCountLabel = useMemo(() => {
    return joinRequests.length === 1 ? '1 request' : `${joinRequests.length} requests`;
  }, [joinRequests.length]);

  const handleApprove = async (joinRequestId: string) => {
    await leagueService.approveJoinRequest(leagueId, joinRequestId);
    setJoinRequests((prev) => prev.filter((r) => r.id !== joinRequestId));
  };

  const handleReject = async (joinRequestId: string) => {
    await leagueService.rejectJoinRequest(leagueId, joinRequestId);
    setJoinRequests((prev) => prev.filter((r) => r.id !== joinRequestId));
  };

  const handleRoleChange = async (driverId: string, newRole: MembershipRole) => {
    setMembers((prev) => prev.map((m) => (m.driverId === driverId ? { ...m, role: newRole } : m)));
    const result = await leagueService.updateMemberRole(leagueId, driverId, newRole);
    if (!result.success) {
      await loadRoster();
    }
  };

  const handleRemove = async (driverId: string) => {
    await leagueService.removeMember(leagueId, driverId);
    setMembers((prev) => prev.filter((m) => m.driverId !== driverId));
  };

  return (
    <div className="space-y-6">
      <Card>
        <div className="space-y-4">
          <div>
            <h1 className="text-2xl font-bold text-white">Roster Admin</h1>
            <p className="text-sm text-gray-400">Manage join requests and member roles.</p>
          </div>

          <div className="border-t border-charcoal-outline pt-4 space-y-3">
            <div className="flex items-center justify-between gap-3">
              <h2 className="text-lg font-semibold text-white">Pending join requests</h2>
              <p className="text-xs text-gray-500">{pendingCountLabel}</p>
            </div>

            {loading ? (
              <div className="py-4 text-sm text-gray-400">Loading…</div>
            ) : joinRequests.length ? (
              <div className="space-y-2">
                {joinRequests.map((req) => (
                  <div
                    key={req.id}
                    className="flex items-center justify-between gap-3 bg-deep-graphite border border-charcoal-outline rounded p-3"
                  >
                    <div className="min-w-0">
                      <p className="text-white font-medium truncate">{req.driverName}</p>
                      <p className="text-xs text-gray-400 truncate">{req.requestedAtIso}</p>
                      {req.message ? <p className="text-xs text-gray-500 truncate">{req.message}</p> : null}
                    </div>

                    <div className="flex items-center gap-2">
                      <button
                        type="button"
                        data-testid={`join-request-${req.id}-approve`}
                        onClick={() => handleApprove(req.id)}
                        className="px-3 py-1.5 rounded bg-primary-blue text-white"
                      >
                        Approve
                      </button>
                      <button
                        type="button"
                        data-testid={`join-request-${req.id}-reject`}
                        onClick={() => handleReject(req.id)}
                        className="px-3 py-1.5 rounded bg-iron-gray text-gray-200"
                      >
                        Reject
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="py-4 text-sm text-gray-500">No pending join requests.</div>
            )}
          </div>

          <div className="border-t border-charcoal-outline pt-4 space-y-3">
            <h2 className="text-lg font-semibold text-white">Members</h2>

            {loading ? (
              <div className="py-4 text-sm text-gray-400">Loading…</div>
            ) : members.length ? (
              <div className="space-y-2">
                {members.map((member) => (
                  <div
                    key={member.driverId}
                    className="flex flex-col md:flex-row md:items-center md:justify-between gap-3 bg-deep-graphite border border-charcoal-outline rounded p-3"
                  >
                    <div className="min-w-0">
                      <p className="text-white font-medium truncate">{member.driverName}</p>
                      <p className="text-xs text-gray-400 truncate">{member.joinedAtIso}</p>
                    </div>

                    <div className="flex flex-col md:flex-row md:items-center gap-2">
                      <label className="text-xs text-gray-400" htmlFor={`role-${member.driverId}`}>
                        Role for {member.driverName}
                      </label>
                      <select
                        id={`role-${member.driverId}`}
                        aria-label={`Role for ${member.driverName}`}
                        value={member.role}
                        onChange={(e) => handleRoleChange(member.driverId, e.target.value as MembershipRole)}
                        className="bg-iron-gray text-white px-3 py-2 rounded"
                      >
                        {ROLE_OPTIONS.map((role) => (
                          <option key={role} value={role}>
                            {role}
                          </option>
                        ))}
                      </select>

                      <button
                        type="button"
                        data-testid={`member-${member.driverId}-remove`}
                        onClick={() => handleRemove(member.driverId)}
                        className="px-3 py-1.5 rounded bg-iron-gray text-gray-200"
                      >
                        Remove
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="py-4 text-sm text-gray-500">No members found.</div>
            )}
          </div>
        </div>
      </Card>
    </div>
  );
}