All files / app/(dashboard)/tutor page.tsx

77.63% Statements 243/313
73.33% Branches 22/30
66.66% Functions 2/3
77.63% Lines 243/313

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 4041x                                                                               7x 7x 7x 7x   7x 7x   7x 7x 7x 7x 7x 1x 1x 1x     6x 6x 6x 6x 6x   7x 1x 1x 1x     5x 5x 5x 5x 5x     7x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     2x 2x 2x 2x 2x   7x 7x     7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 7x   7x 7x   7x 4x 4x 4x 4x 4x 4x 4x   4x     7x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x   2x 2x 2x 2x 2x   2x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x     1x 1x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   7x 7x 7x 7x 7x 7x 2x 2x 2x 7x 7x         7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x     7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 1x 1x 1x 1x 1x               7x   7x 7x 1x 1x 1x 1x               7x 7x 7x 7x 7x   7x                                                                                                                              
'use client';
 
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import {
  Calendar,
  IndianRupee,
  Clock,
  Plus,
  ChevronRight,
  GraduationCap,
  CalendarDays,
  BookOpen,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Loader2,
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { createClient } from '@/lib/supabase/client';
import type { TutorProfile, Booking, Profile } from '@/types/database';
 
interface TutorDashboardData {
  tutorProfile: TutorProfile | null;
  profile: Profile | null;
  bookings: Booking[];
  stats: {
    totalBookings: number;
    pendingBookings: number;
    completedSessions: number;
    totalEarnings: number;
    upcomingCount: number;
  };
}
 
export default function TutorDashboardPage() {
  const [data, setData] = useState<TutorDashboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const router = useRouter();
 
  useEffect(() => {
    const supabase = createClient();
 
    async function fetchData() {
      const {
        data: { user },
      } = await supabase.auth.getUser();
      if (!user) {
        router.push('/login');
        return;
      }
 
      // Get profile
      const { data: profile } = await supabase
        .from('profiles')
        .select('*')
        .eq('user_id', user.id)
        .single();
 
      if (!profile) {
        router.push('/profile');
        return;
      }
 
      // Get tutor profile
      const { data: tutorProfile } = await supabase
        .from('tutor_profiles')
        .select('*')
        .eq('profile_id', profile.id)
        .single();
 
      // If no tutor profile, redirect to setup
      if (!tutorProfile) {
        setData({
          tutorProfile: null,
          profile,
          bookings: [],
          stats: {
            totalBookings: 0,
            pendingBookings: 0,
            completedSessions: 0,
            totalEarnings: 0,
            upcomingCount: 0,
          },
        });
        setLoading(false);
        return;
      }
 
      // Get bookings
      const { data: bookings } = await supabase
        .from('bookings')
        .select('*')
        .eq('tutor_profile_id', tutorProfile.id)
        .order('session_date', { ascending: true });
 
      const allBookings = bookings || [];
      const today = new Date().toISOString().split('T')[0];
 
      // Calculate stats
      const stats = {
        totalBookings: allBookings.length,
        pendingBookings: allBookings.filter((b) => b.status === 'pending').length,
        completedSessions: allBookings.filter((b) => b.status === 'completed').length,
        totalEarnings: allBookings
          .filter((b) => b.payment_status === 'captured')
          .reduce((sum, b) => sum + b.amount_inr, 0),
        upcomingCount: allBookings.filter(
          (b) => b.session_date >= today && b.status === 'confirmed'
        ).length,
      };
 
      setData({ tutorProfile, profile, bookings: allBookings, stats });
      setLoading(false);
    }
 
    fetchData();
  }, [router]);
 
  if (loading) {
    return (
      <div className="flex min-h-[400px] items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
          <p className="text-sm text-muted-foreground">Loading tutor dashboard...</p>
        </div>
      </div>
    );
  }
 
  // No tutor profile - show setup prompt
  if (!data?.tutorProfile) {
    return (
      <div className="space-y-8">
        <div>
          <h1 className="text-3xl font-bold">Tutor Dashboard</h1>
          <p className="text-muted-foreground">Manage your tutoring sessions and bookings</p>
        </div>
 
        <Card className="border-dashed">
          <CardContent className="flex flex-col items-center justify-center py-16">
            <div className="mb-4 rounded-full bg-primary/10 p-4">
              <GraduationCap className="h-12 w-12 text-primary" />
            </div>
            <h2 className="mb-2 text-xl font-semibold">Set Up Your Tutor Profile</h2>
            <p className="mb-6 max-w-md text-center text-muted-foreground">
              Create your tutor profile to start accepting bookings. Add your subjects,
              availability, and pricing to get started.
            </p>
            <Button asChild size="lg">
              <Link href="/tutor/setup">
                <Plus className="mr-2 h-4 w-4" />
                Create Tutor Profile
              </Link>
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }
 
  const { tutorProfile, bookings, stats } = data;
  const today = new Date().toISOString().split('T')[0];
  const upcomingBookings = bookings.filter(
    (b) => b.session_date >= today && ['confirmed', 'pending'].includes(b.status)
  );
  const pastBookings = bookings.filter((b) => b.session_date < today || b.status === 'completed');
 
  const statCards = [
    {
      title: 'Total Bookings',
      value: stats.totalBookings,
      icon: CalendarDays,
      color: 'text-blue-500',
    },
    {
      title: 'Pending Approval',
      value: stats.pendingBookings,
      icon: AlertCircle,
      color: 'text-yellow-500',
    },
    {
      title: 'Completed Sessions',
      value: stats.completedSessions,
      icon: CheckCircle2,
      color: 'text-green-500',
    },
    {
      title: 'Total Earnings',
      value: `₹${(stats.totalEarnings / 100).toLocaleString()}`,
      icon: IndianRupee,
      color: 'text-emerald-500',
    },
  ];
 
  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-3xl font-bold">Tutor Dashboard</h1>
          <p className="text-muted-foreground">Manage your tutoring sessions and bookings</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" asChild>
            <Link href="/tutor/settings">Settings</Link>
          </Button>
          <Button asChild>
            <Link href="/tutor/availability">
              <Calendar className="mr-2 h-4 w-4" />
              Manage Availability
            </Link>
          </Button>
        </div>
      </div>
 
      {/* Stats */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {statCards.map((stat, index) => (
          <motion.div
            key={stat.title}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: index * 0.1 }}
          >
            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">{stat.title}</p>
                    <p className="text-3xl font-bold">{stat.value}</p>
                  </div>
                  <stat.icon className={`h-8 w-8 ${stat.color}`} />
                </div>
              </CardContent>
            </Card>
          </motion.div>
        ))}
      </div>
 
      {/* Quick Info */}
      <Card>
        <CardHeader>
          <CardTitle>Your Tutor Profile</CardTitle>
          <CardDescription>Quick overview of your teaching setup</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            <div className="space-y-1">
              <p className="text-sm text-muted-foreground">Hourly Rate</p>
              <p className="font-semibold">
                {tutorProfile.hourly_rate_inr
                  ? `₹${(tutorProfile.hourly_rate_inr / 100).toLocaleString()}/hr`
                  : 'Not set'}
              </p>
            </div>
            <div className="space-y-1">
              <p className="text-sm text-muted-foreground">Subjects</p>
              <div className="flex flex-wrap gap-1">
                {(tutorProfile.subjects as string[])?.slice(0, 3).map((subject: string) => (
                  <Badge key={subject} variant="secondary" className="text-xs">
                    {subject}
                  </Badge>
                ))}
                {(tutorProfile.subjects as string[])?.length > 3 && (
                  <Badge variant="outline" className="text-xs">
                    +{(tutorProfile.subjects as string[]).length - 3}
                  </Badge>
                )}
              </div>
            </div>
            <div className="space-y-1">
              <p className="text-sm text-muted-foreground">Status</p>
              <Badge variant={tutorProfile.is_accepting_students ? 'default' : 'secondary'}>
                {tutorProfile.is_accepting_students ? 'Accepting Students' : 'Not Accepting'}
              </Badge>
            </div>
            <div className="space-y-1">
              <p className="text-sm text-muted-foreground">Booking Mode</p>
              <p className="font-semibold">
                {tutorProfile.instant_booking ? 'Instant Booking' : 'Approval Required'}
              </p>
            </div>
          </div>
        </CardContent>
      </Card>
 
      {/* Bookings */}
      <Card>
        <CardHeader>
          <CardTitle>Bookings</CardTitle>
          <CardDescription>Manage your tutoring sessions</CardDescription>
        </CardHeader>
        <CardContent>
          <Tabs defaultValue="upcoming">
            <TabsList className="mb-4">
              <TabsTrigger value="upcoming">Upcoming ({upcomingBookings.length})</TabsTrigger>
              <TabsTrigger value="past">Past ({pastBookings.length})</TabsTrigger>
            </TabsList>
 
            <TabsContent value="upcoming">
              {upcomingBookings.length === 0 ? (
                <div className="py-12 text-center text-muted-foreground">
                  <CalendarDays className="mx-auto mb-4 h-12 w-12 opacity-50" />
                  <p>No upcoming bookings</p>
                  <p className="text-sm">Share your profile to get more students!</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {upcomingBookings.map((booking) => (
                    <BookingCard key={booking.id} booking={booking} />
                  ))}
                </div>
              )}
            </TabsContent>
 
            <TabsContent value="past">
              {pastBookings.length === 0 ? (
                <div className="py-12 text-center text-muted-foreground">
                  <BookOpen className="mx-auto mb-4 h-12 w-12 opacity-50" />
                  <p>No past sessions yet</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {pastBookings.slice(0, 10).map((booking) => (
                    <BookingCard key={booking.id} booking={booking} isPast />
                  ))}
                </div>
              )}
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
    </div>
  );
}
 
function BookingCard({ booking, isPast: _isPast = false }: { booking: Booking; isPast?: boolean }) {
  const statusConfig: Record<string, { color: string; icon: React.ElementType }> = {
    pending: { color: 'bg-yellow-500/10 text-yellow-600', icon: AlertCircle },
    confirmed: { color: 'bg-green-500/10 text-green-600', icon: CheckCircle2 },
    completed: { color: 'bg-blue-500/10 text-blue-600', icon: CheckCircle2 },
    cancelled: { color: 'bg-red-500/10 text-red-600', icon: XCircle },
    no_show: { color: 'bg-gray-500/10 text-gray-600', icon: XCircle },
  };
 
  const status = statusConfig[booking.status] || statusConfig.pending;
  const StatusIcon = status.icon;
 
  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      className="flex items-center justify-between rounded-lg border p-4 transition-colors hover:bg-muted/50"
    >
      <div className="flex items-center gap-4">
        <div className="hidden h-12 w-12 items-center justify-center rounded-lg bg-primary/10 sm:flex">
          <BookOpen className="h-6 w-6 text-primary" />
        </div>
        <div>
          <div className="flex items-center gap-2">
            <p className="font-medium">{booking.student_name}</p>
            <Badge variant="outline" className="text-xs">
              {booking.subject}
            </Badge>
          </div>
          <div className="flex items-center gap-3 text-sm text-muted-foreground">
            <span className="flex items-center gap-1">
              <CalendarDays className="h-3.5 w-3.5" />
              {new Date(booking.session_date).toLocaleDateString('en-IN', {
                weekday: 'short',
                day: 'numeric',
                month: 'short',
              })}
            </span>
            <span className="flex items-center gap-1">
              <Clock className="h-3.5 w-3.5" />
              {booking.start_time}
            </span>
            <span>{booking.duration_minutes} min</span>
          </div>
        </div>
      </div>
 
      <div className="flex items-center gap-3">
        <Badge className={status.color}>
          <StatusIcon className="mr-1 h-3 w-3" />
          {booking.status.charAt(0).toUpperCase() + booking.status.slice(1)}
        </Badge>
        <Button variant="ghost" size="icon" asChild>
          <Link href={`/tutor/bookings/${booking.id}`}>
            <ChevronRight className="h-4 w-4" />
          </Link>
        </Button>
      </div>
    </motion.div>
  );
}