import Link from "next/link";
import { redirect } from "next/navigation";
import { PlusCircle } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";

import { getCurrent } from "@/features/auth/queries";
import { getWorkspaces } from "@/features/workspaces/queries";

export const dynamic = 'force-dynamic';

export default async function NoWorkspacesPage() {
  const user = await getCurrent();
  
  if (!user) {
    redirect("/sign-in");
  }

  // Double-check that the user really has no workspaces
  const workspaces = await getWorkspaces();
  
  console.log("No-workspaces page - User:", user?.id);
  console.log("No-workspaces page - Workspaces:", workspaces);
  
  if (workspaces && workspaces.total > 0 && workspaces.documents && workspaces.documents.length > 0) {
    // Sort by most recently updated and redirect to latest workspace
    const sortedWorkspaces = workspaces.documents.sort((a: { updatedAt: string | number | Date; }, b: { updatedAt: string | number | Date; }) => 
      new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
    );
    redirect(`/workspaces/${sortedWorkspaces[0].id}`);
  }

  return (
    <div className="flex items-center justify-center h-[80vh]">
      {/* Debug Information */}
      <div className="fixed top-4 right-4 bg-red-50 border border-red-200 p-3 rounded-lg text-xs max-w-sm z-50">
        <h4 className="font-bold text-red-600 mb-2">🐛 Debug Info</h4>
        <p><strong>User ID:</strong> {user?.id || "None"}</p>
        <p><strong>User Email:</strong> {user?.email || "None"}</p>
        <p><strong>User Name:</strong> {user?.name || "None"}</p>
        <p><strong>Workspaces Total:</strong> {workspaces?.total || 0}</p>
        <p><strong>Environment:</strong> {process.env.NODE_ENV}</p>
        <p><strong>Base URL:</strong> {process.env.NEXT_PUBLIC_APP_URL || "Not Set"}</p>
      </div>
      
      <Card className="w-full max-w-md border-none shadow-none">
        <CardHeader className="text-center">
          <CardTitle className="text-2xl">Welcome to LCI</CardTitle>
          <CardDescription>
            You don&apos;t have any workspaces yet
          </CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col gap-4">
          <p className="text-center text-muted-foreground">
            Create a new workspace to get started or wait for an invitation from another user.
          </p>
          <div className="flex justify-center mt-4">
            <Button asChild>
              <Link href="/workspaces/create">
                <PlusCircle className="mr-2 h-4 w-4" />
                Create a Workspace
              </Link>
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
} 