import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useCourses } from "@/hooks/queries";
import { Link } from "react-router-dom";
import { Plus, Users, BookOpen, Archive } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

export default function TeacherCourses() {
  const { data: coursesData, isLoading } = useCourses();
  const courses = coursesData?.items ?? [];
  const teacherCourses = courses;
  const { toast } = useToast();

  if (isLoading) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">My Courses</h1>
          <p className="text-muted-foreground">Manage your courses and materials.</p>
        </div>
        <Button asChild><Link to="/teacher/courses/new"><Plus className="mr-2 h-4 w-4" />New Course</Link></Button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {teacherCourses.map(c => (
          <Card key={c.id} className="hover:shadow-md transition-shadow">
            <div className="h-2 rounded-t-lg bg-primary" />
            <CardContent className="pt-5 space-y-3">
              <div className="flex items-center justify-between">
                <Badge variant={c.status === "active" ? "default" : "secondary"} className="capitalize">{c.status}</Badge>
                <span className="text-xs text-muted-foreground">{c.code}</span>
              </div>
              <h3 className="font-semibold">{c.title}</h3>
              <p className="text-sm text-muted-foreground line-clamp-2">{c.description}</p>
              <div className="flex items-center gap-3 text-xs text-muted-foreground">
                <span className="flex items-center gap-1"><Users className="h-3 w-3" />{c.enrolled} students</span>
                <span className="flex items-center gap-1"><BookOpen className="h-3 w-3" />{c.modules.length} modules</span>
              </div>
              <div className="flex gap-2">
                <Button size="sm" variant="outline" asChild><Link to={`/teacher/courses/${c.id}/edit`}>Edit</Link></Button>
                <Button size="sm" variant="ghost" onClick={() => toast({ title: "Course archived" })}><Archive className="h-3 w-3" /></Button>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}
