'use client';

import { useState } from 'react';
import Link from 'next/link';
import { Plus, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useProjects } from '@/lib/hooks/use-projects';
import { CreateProjectDialog } from '@/components/features/projects/CreateProjectDialog';

export default function ProjectsPage() {
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const { data: projects, isLoading, error } = useProjects();

  // Log state for debugging
  console.log('[ProjectsPage] State:', {
    isLoading,
    error,
    projects,
    apiUrl: process.env.NEXT_PUBLIC_API_URL,
  });

  if (isLoading) {
    return (
      <div className="flex h-[50vh] items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000/api/v1';

    console.error('[ProjectsPage] Error loading projects:', error);

    return (
      <div className="flex h-[50vh] items-center justify-center">
        <Card className="w-full max-w-md">
          <CardHeader>
            <CardTitle className="text-red-600">Failed to Load Projects</CardTitle>
            <CardDescription>Unable to connect to the backend API</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <p className="text-sm font-medium">Error Details:</p>
              <p className="text-sm text-muted-foreground">{errorMessage}</p>
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium">API URL:</p>
              <p className="text-sm font-mono text-muted-foreground">{apiUrl}</p>
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium">Troubleshooting Steps:</p>
              <ul className="list-disc list-inside text-sm text-muted-foreground space-y-1">
                <li>Check if the backend server is running</li>
                <li>Verify the API URL in .env.local</li>
                <li>Check browser console (F12) for detailed errors</li>
                <li>Check network tab (F12) for failed requests</li>
              </ul>
            </div>
            <Button
              onClick={() => window.location.reload()}
              className="w-full"
            >
              Retry
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Projects</h1>
          <p className="text-muted-foreground">
            Manage your projects and track progress
          </p>
        </div>
        <Button onClick={() => setIsCreateDialogOpen(true)}>
          <Plus className="mr-2 h-4 w-4" />
          New Project
        </Button>
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {projects?.map((project) => (
          <Link key={project.id} href={`/projects/${project.id}`}>
            <Card className="transition-colors hover:bg-accent">
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div className="space-y-1">
                    <CardTitle>{project.name}</CardTitle>
                    <CardDescription>{project.key}</CardDescription>
                  </div>
                  <span
                    className={`rounded-full px-2 py-1 text-xs font-medium ${
                      project.status === 'Active'
                        ? 'bg-green-100 text-green-700'
                        : 'bg-gray-100 text-gray-700'
                    }`}
                  >
                    {project.status}
                  </span>
                </div>
              </CardHeader>
              <CardContent>
                <p className="line-clamp-2 text-sm text-muted-foreground">
                  {project.description}
                </p>
              </CardContent>
            </Card>
          </Link>
        ))}

        {!projects || projects.length === 0 ? (
          <Card className="col-span-full">
            <CardContent className="flex h-40 items-center justify-center">
              <p className="text-sm text-muted-foreground">
                No projects yet. Create your first project to get started.
              </p>
            </CardContent>
          </Card>
        ) : null}
      </div>

      <CreateProjectDialog
        open={isCreateDialogOpen}
        onOpenChange={setIsCreateDialogOpen}
      />
    </div>
  );
}
