"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { WorkspaceSettings } from "@/components/workspace/WorkspaceSettings";
import { MemberList } from "@/components/workspace/MemberList";
import { InviteMember } from "@/components/workspace/InviteMember";
import { WorkspaceMemberRole } from "@mosaic/shared";
import type { Workspace, WorkspaceMemberWithUser } from "@mosaic/shared";
import Link from "next/link";

interface WorkspaceDetailPageProps {
  params: {
    id: string;
  };
}

// Mock data - TODO: Replace with real API calls
const mockWorkspace: Workspace = {
  id: "ws-1",
  name: "Personal Workspace",
  ownerId: "user-1",
  settings: {},
  createdAt: new Date("2024-01-15"),
  updatedAt: new Date("2024-01-15"),
};

const mockMembers: WorkspaceMemberWithUser[] = [
  {
    workspaceId: "ws-1",
    userId: "user-1",
    role: WorkspaceMemberRole.OWNER,
    joinedAt: new Date("2024-01-15"),
    user: {
      id: "user-1",
      email: "owner@example.com",
      name: "John Doe",
      emailVerified: true,
      image: null,
      authProviderId: null,
      preferences: {},
      createdAt: new Date("2024-01-15"),
      updatedAt: new Date("2024-01-15"),
    },
  },
  {
    workspaceId: "ws-1",
    userId: "user-2",
    role: WorkspaceMemberRole.ADMIN,
    joinedAt: new Date("2024-01-16"),
    user: {
      id: "user-2",
      email: "admin@example.com",
      name: "Jane Smith",
      emailVerified: true,
      image: null,
      authProviderId: null,
      preferences: {},
      createdAt: new Date("2024-01-16"),
      updatedAt: new Date("2024-01-16"),
    },
  },
  {
    workspaceId: "ws-1",
    userId: "user-3",
    role: WorkspaceMemberRole.MEMBER,
    joinedAt: new Date("2024-01-17"),
    user: {
      id: "user-3",
      email: "member@example.com",
      name: "Bob Johnson",
      emailVerified: true,
      image: null,
      authProviderId: null,
      preferences: {},
      createdAt: new Date("2024-01-17"),
      updatedAt: new Date("2024-01-17"),
    },
  },
];

export default function WorkspaceDetailPage({
  params,
}: WorkspaceDetailPageProps): React.JSX.Element {
  const router = useRouter();
  const [workspace, setWorkspace] = useState<Workspace>(mockWorkspace);
  const [members, setMembers] = useState<WorkspaceMemberWithUser[]>(mockMembers);
  const currentUserId = "user-1"; // TODO: Get from auth context
  const currentUserRole: WorkspaceMemberRole = WorkspaceMemberRole.OWNER; // TODO: Get from API

  // TODO: Replace with actual role check when API is implemented
  // Currently hardcoded to OWNER in mock data (line 89)
  const canInvite =
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    currentUserRole === WorkspaceMemberRole.OWNER || currentUserRole === WorkspaceMemberRole.ADMIN;

  const handleUpdateWorkspace = async (name: string): Promise<void> => {
    // TODO: Replace with real API call
    console.log("Updating workspace:", { id: params.id, name });
    await new Promise((resolve) => setTimeout(resolve, 500));
    setWorkspace({ ...workspace, name, updatedAt: new Date() });
  };

  const handleDeleteWorkspace = async (): Promise<void> => {
    // TODO: Replace with real API call
    console.log("Deleting workspace:", params.id);
    await new Promise((resolve) => setTimeout(resolve, 1000));
    router.push("/settings/workspaces");
  };

  const handleRoleChange = async (userId: string, newRole: WorkspaceMemberRole): Promise<void> => {
    // TODO: Replace with real API call
    console.log("Changing role:", { userId, newRole });
    await new Promise((resolve) => setTimeout(resolve, 500));
    setMembers(
      members.map((member) => (member.userId === userId ? { ...member, role: newRole } : member))
    );
  };

  const handleRemoveMember = async (userId: string): Promise<void> => {
    // TODO: Replace with real API call
    console.log("Removing member:", userId);
    await new Promise((resolve) => setTimeout(resolve, 500));
    setMembers(members.filter((member) => member.userId !== userId));
  };

  const handleInviteMember = async (email: string, role: WorkspaceMemberRole): Promise<void> => {
    // TODO: Replace with real API call
    console.log("Inviting member:", { email, role, workspaceId: params.id });
    await new Promise((resolve) => setTimeout(resolve, 1000));
    // In real implementation, this would send an invitation email
  };

  return (
    <main className="container mx-auto px-4 py-8 max-w-5xl">
      <div className="mb-8">
        <div className="flex items-center justify-between mb-2">
          <h1 className="text-3xl font-bold text-gray-900">{workspace.name}</h1>
          <Link href="/settings/workspaces" className="text-sm text-blue-600 hover:text-blue-700">
            ← Back to Workspaces
          </Link>
        </div>
        <p className="text-gray-600">Manage workspace settings and team members</p>
      </div>

      <div className="space-y-6">
        {/* Workspace Settings */}
        <WorkspaceSettings
          workspace={workspace}
          userRole={currentUserRole}
          onUpdate={handleUpdateWorkspace}
          onDelete={handleDeleteWorkspace}
        />

        {/* Members Section */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div className="lg:col-span-2">
            <MemberList
              members={members}
              currentUserId={currentUserId}
              currentUserRole={currentUserRole}
              workspaceOwnerId={workspace.ownerId}
              onRoleChange={handleRoleChange}
              onRemove={handleRemoveMember}
            />
          </div>

          {/* Invite Member */}
          {canInvite && (
            <div className="lg:col-span-2">
              <InviteMember onInvite={handleInviteMember} />
            </div>
          )}
        </div>
      </div>
    </main>
  );
}
