"use client";

import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { MemberList } from "@/components/workspace/MemberList";
import { useAuth } from "@/lib/auth/auth-context";
import { WorkspaceMemberRole } from "@mosaic/shared";
import {
  fetchWorkspaceMembers,
  fetchUserWorkspaces,
  updateWorkspaceMemberRole,
  removeWorkspaceMember,
  type WorkspaceMemberEntry,
  type UserWorkspace,
} from "@/lib/api/workspaces";
import type { WorkspaceMemberWithUser } from "@/components/workspace/MemberList";

function getErrorMessage(error: unknown, fallback: string): string {
  if (error instanceof Error) return error.message;
  return fallback;
}

function toMemberWithUser(m: WorkspaceMemberEntry): WorkspaceMemberWithUser {
  return {
    workspaceId: m.workspaceId,
    userId: m.userId,
    role: m.role,
    joinedAt: new Date(m.joinedAt),
    user: {
      id: m.user.id,
      email: m.user.email,
      name: m.user.name ?? "",
      image: m.user.image,
      emailVerified: true,
      authProviderId: null,
      preferences: {},
      deactivatedAt: null,
      isLocalAuth: false,
      passwordHash: null,
      invitedBy: null,
      invitationToken: null,
      invitedAt: null,
      createdAt: new Date(),
      updatedAt: new Date(),
    },
  };
}

export default function WorkspaceDetailPage(): React.ReactElement {
  const params = useParams<{ id: string }>();
  const workspaceId = params.id;
  const { user: authUser } = useAuth();

  const [workspace, setWorkspace] = useState<UserWorkspace | null>(null);
  const [members, setMembers] = useState<WorkspaceMemberEntry[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async (): Promise<void> => {
    setIsLoading(true);
    setError(null);
    try {
      const [workspaces, memberList] = await Promise.all([
        fetchUserWorkspaces(),
        fetchWorkspaceMembers(workspaceId),
      ]);
      const ws = workspaces.find((w) => w.id === workspaceId) ?? null;
      setWorkspace(ws);
      setMembers(memberList);
    } catch (err) {
      setError(getErrorMessage(err, "Failed to load workspace"));
    } finally {
      setIsLoading(false);
    }
  }, [workspaceId]);

  useEffect(() => {
    void load();
  }, [load]);

  const handleRoleChange = useCallback(
    async (userId: string, newRole: WorkspaceMemberRole): Promise<void> => {
      await updateWorkspaceMemberRole(workspaceId, userId, { role: newRole });
      await load();
    },
    [workspaceId, load]
  );

  const handleRemove = useCallback(
    async (userId: string): Promise<void> => {
      await removeWorkspaceMember(workspaceId, userId);
      await load();
    },
    [workspaceId, load]
  );

  if (isLoading) {
    return (
      <div className="p-8 text-center text-gray-500" role="status" aria-label="Loading workspace">
        Loading workspace…
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8">
        <div className="rounded-lg border border-red-200 bg-red-50 p-4 text-red-700" role="alert">
          <p className="font-medium">Failed to load workspace</p>
          <p className="mt-1 text-sm">Please try again later.</p>
        </div>
        <Link
          href="/settings/workspaces"
          className="mt-4 inline-block text-sm text-blue-600 hover:underline"
        >
          ← Back to Workspaces
        </Link>
      </div>
    );
  }

  const currentUserId = authUser?.id ?? "";
  const currentMember = members.find((m) => m.userId === currentUserId);
  const currentUserRole = currentMember?.role ?? workspace?.role ?? WorkspaceMemberRole.MEMBER;
  const ownerId =
    members.find((m) => m.role === WorkspaceMemberRole.OWNER)?.userId ?? workspace?.ownerId ?? "";

  return (
    <div className="p-8 max-w-3xl">
      <div className="mb-6">
        <Link href="/settings/workspaces" className="text-sm text-gray-500 hover:text-gray-700">
          ← Back to Workspaces
        </Link>
        <h1 className="mt-2 text-2xl font-bold text-gray-900">{workspace?.name ?? "Workspace"}</h1>
      </div>

      <MemberList
        members={members.map(toMemberWithUser)}
        currentUserId={currentUserId}
        currentUserRole={currentUserRole}
        workspaceOwnerId={ownerId}
        onRoleChange={handleRoleChange}
        onRemove={handleRemove}
      />
    </div>
  );
}
