import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Activity, Clock, DollarSign, MessageSquare } from "lucide-react";
import type { Session, DashboardStats } from "@/lib/types";
import { PageHeader } from "@/components/layout/page-header";

async function getSessions(projectId: string): Promise<Session[]> {
  try {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/sessions?projectId=${projectId}&limit=20`,
      { cache: 'no-store' }
    );
    if (!res.ok) throw new Error('Failed to fetch sessions');
    return res.json();
  } catch (error) {
    console.error('Error fetching sessions:', error);
    return [];
  }
}

async function getStats(projectId: string): Promise<DashboardStats> {
  try {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/stats?projectId=${projectId}`,
      { cache: 'no-store' }
    );
    if (!res.ok) throw new Error('Failed to fetch stats');
    return res.json();
  } catch (error) {
    return {
      totalSessions: 0,
      totalCost: 0,
      totalTokens: 0,
      totalFeatures: 0,
      completedFeatures: 0,
      totalDuration: 0,
    };
  }
}

export default async function SessionsPage({
  params,
}: {
  params: Promise<{ workspace: string; projectId: string }>;
}) {
  const { workspace, projectId } = await params;
  const [sessions, stats] = await Promise.all([
    getSessions(projectId),
    getStats(projectId),
  ]);

  return (
    <>
      <PageHeader
        projectId={projectId}
        projectName="Project"
        projectEmoji="📦"
        pageName="Sessions"
      />
      <div className="flex h-full flex-col overflow-auto">
        {/* Stats Section */}
        <div className="border-b bg-card/50 px-6 py-4">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold">Sessions</h1>
              <p className="text-sm text-muted-foreground">
                Track all your AI coding sessions
              </p>
            </div>
            <Button>
              <Activity className="mr-2 h-4 w-4" />
              New Session
            </Button>
          </div>
        </div>

      {/* Content */}
      <div className="flex-1 overflow-auto p-6">
        <div className="mx-auto max-w-6xl space-y-6">
          {/* Stats */}
          <div className="grid gap-4 md:grid-cols-3">
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Total Sessions
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold">{stats.totalSessions}</div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Total Duration
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold">
                  {Math.round(stats.totalDuration / 60)}h
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Total Cost
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold">
                  ${stats.totalCost.toFixed(2)}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Sessions List */}
          <Card>
            <CardHeader>
              <CardTitle>Recent Sessions</CardTitle>
              <CardDescription>
                Your AI coding activity with conversation history
              </CardDescription>
            </CardHeader>
            <CardContent>
              {sessions.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-12">
                  <div className="mb-4 rounded-full bg-muted p-3">
                    <Activity className="h-6 w-6 text-muted-foreground" />
                  </div>
                  <h3 className="text-lg font-medium mb-2">No sessions yet</h3>
                  <p className="text-sm text-center text-muted-foreground max-w-sm">
                    Start coding with AI and your sessions will appear here
                  </p>
                </div>
              ) : (
                <div className="space-y-4">
                  {sessions.map((session) => (
                    <div
                      key={session.id}
                      className="flex items-center justify-between rounded-lg border p-4 hover:bg-accent/50 transition-colors cursor-pointer"
                    >
                      <div className="flex items-start gap-4">
                        <div className="rounded-full bg-primary/10 p-2">
                          <Activity className="h-5 w-5 text-primary" />
                        </div>
                        <div>
                          <h3 className="font-medium">
                            {session.summary || `Session ${session.session_id.substring(0, 8)}...`}
                          </h3>
                          <div className="mt-1 flex items-center gap-4 text-sm text-muted-foreground">
                            <span className="flex items-center gap-1">
                              <Clock className="h-3 w-3" />
                              {session.duration_minutes} min
                            </span>
                            <span className="flex items-center gap-1">
                              <MessageSquare className="h-3 w-3" />
                              {session.message_count} messages
                            </span>
                            {session.estimated_cost_usd && (
                              <span className="flex items-center gap-1">
                                <DollarSign className="h-3 w-3" />
                                ${session.estimated_cost_usd.toFixed(3)}
                              </span>
                            )}
                          </div>
                          <div className="mt-2 flex gap-2">
                            {session.primary_ai_model && (
                              <Badge variant="outline" className="text-xs">
                                {session.primary_ai_model}
                              </Badge>
                            )}
                            {session.ide_name && (
                              <Badge variant="outline" className="text-xs">
                                {session.ide_name}
                              </Badge>
                            )}
                            {session.github_branch && (
                              <Badge variant="secondary" className="text-xs">
                                {session.github_branch}
                              </Badge>
                            )}
                          </div>
                        </div>
                      </div>
                      <Button variant="ghost" size="sm">
                        View Details
                      </Button>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
    </>
  );
}

