"use client";

import type { ReactElement } from "react";

import { useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { TeamSettings } from "@/components/team/TeamSettings";
import { TeamMemberList } from "@/components/team/TeamMemberList";
import { mockTeamWithMembers } from "@/lib/api/teams";
import type { User } from "@mosaic/shared";
import type { TeamMemberRole } from "@mosaic/shared";
import Link from "next/link";

// Mock available users for adding to team
const mockAvailableUsers: User[] = [
  {
    id: "user-3",
    email: "alice@example.com",
    name: "Alice Johnson",
    emailVerified: true,
    image: null,
    authProviderId: null,
    preferences: {},
    createdAt: new Date("2026-01-17"),
    updatedAt: new Date("2026-01-17"),
  },
  {
    id: "user-4",
    email: "bob@example.com",
    name: "Bob Wilson",
    emailVerified: true,
    image: null,
    authProviderId: null,
    preferences: {},
    createdAt: new Date("2026-01-18"),
    updatedAt: new Date("2026-01-18"),
  },
];

export default function TeamDetailPage(): ReactElement {
  const params = useParams();
  const router = useRouter();
  const workspaceId = params.id as string;
  // const teamId = params.teamId as string; // Will be used for API calls

  // TODO: Replace with real API call when backend is ready
  // const { data: team, isLoading } = useQuery({
  //   queryKey: ["team", workspaceId, params.teamId],
  //   queryFn: () => fetchTeam(workspaceId, params.teamId as string),
  // });

  const [team] = useState(mockTeamWithMembers);
  const [isLoading] = useState(false);

  const handleUpdateTeam = (data: { name?: string; description?: string }): Promise<void> => {
    // TODO: Replace with real API call
    // await updateTeam(workspaceId, teamId, data);
    console.log("Updating team:", data);
    // TODO: Refetch team data
    return Promise.resolve();
  };

  const handleDeleteTeam = (): Promise<void> => {
    // TODO: Replace with real API call
    // await deleteTeam(workspaceId, teamId);
    console.log("Deleting team");

    // Navigate back to teams list
    router.push(`/settings/workspaces/${workspaceId}/teams`);
    return Promise.resolve();
  };

  const handleAddMember = (userId: string, role?: TeamMemberRole): Promise<void> => {
    // TODO: Replace with real API call
    // await addTeamMember(workspaceId, teamId, { userId, role });
    console.log("Adding member:", { userId, role });
    // TODO: Refetch team data
    return Promise.resolve();
  };

  const handleRemoveMember = (userId: string): Promise<void> => {
    // TODO: Replace with real API call
    // await removeTeamMember(workspaceId, teamId, userId);
    console.log("Removing member:", userId);
    // TODO: Refetch team data
    return Promise.resolve();
  };

  if (isLoading) {
    return (
      <main className="container mx-auto px-4 py-8">
        <div className="flex justify-center items-center p-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
          <span className="ml-3 text-gray-600">Loading team...</span>
        </div>
      </main>
    );
  }

  return (
    <main className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <Link
          href={`/settings/workspaces/${workspaceId}/teams`}
          className="text-blue-600 hover:text-blue-700 text-sm mb-2 inline-block"
        >
          ← Back to Teams
        </Link>
        <h1 className="text-3xl font-bold text-gray-900">{team.name}</h1>
        {team.description && <p className="text-gray-600 mt-2">{team.description}</p>}
      </div>

      <div className="space-y-6">
        <TeamSettings team={team} onUpdate={handleUpdateTeam} onDelete={handleDeleteTeam} />

        <TeamMemberList
          members={team.members}
          onAddMember={handleAddMember}
          onRemoveMember={handleRemoveMember}
          availableUsers={mockAvailableUsers}
        />
      </div>
    </main>
  );
}
