import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { BookOpen, TrendingUp, Activity, CheckCircle2, FileText, ClipboardList } from "lucide-react";
import { useProficiencySummary } from "@/hooks/queries";
import { analyticsService } from "@/services/analytics.service";
import { adaptiveService } from "@/services/adaptive.service";
import { useQuery } from "@tanstack/react-query";

export default function StudentJourney() {
  const { data: summaries = [], isLoading: ls } = useProficiencySummary();

  const { data: analyticsData, isLoading: la } = useQuery({
    queryKey: ["analytics", "student", "journey"],
    queryFn: () => analyticsService.getStudentAnalytics(),
  });

  const { data: planData, isLoading: lp } = useQuery({
    queryKey: ["adaptive", "plan", "all"],
    queryFn: () => adaptiveService.getLearningPlan({}),
  });

  const analytics = analyticsData as { recent_activity?: { action: string; description: string; date: string }[] } | undefined;
  const recentActivity = analytics?.recent_activity?.slice(0, 10) ?? [];

  if (ls || la || lp) 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>;

  const activityIcons: Record<string, React.ReactNode> = {
    exam: <ClipboardList className="h-4 w-4" />,
    assignment: <FileText className="h-4 w-4" />,
    chapter: <BookOpen className="h-4 w-4" />,
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">My Learning Journey</h1>
        <p className="text-muted-foreground">Track your progress and proficiency across all subjects.</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {summaries.map(s => {
          const mastery = Math.round(s.overall_mastery ?? 0);
          return (
            <Card key={s.subject_id} className="hover:shadow-md transition-shadow">
              <CardHeader className="pb-3">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                    <BookOpen className="h-5 w-5 text-primary" />
                  </div>
                  <div>
                    <CardTitle className="text-base">{s.subject_name ?? `Subject ${s.subject_id}`}</CardTitle>
                    <CardDescription>{s.topics_mastered ?? 0} / {s.topics_total ?? 0} topics mastered</CardDescription>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="space-y-1">
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Overall Mastery</span>
                    <span className="font-medium">{mastery}%</span>
                  </div>
                  <Progress value={mastery} className="h-2" />
                </div>
                <Badge variant={mastery >= 80 ? "default" : mastery >= 50 ? "secondary" : "outline"}>
                  {mastery >= 80 ? "Proficient" : mastery >= 50 ? "Developing" : "Beginner"}
                </Badge>
              </CardContent>
            </Card>
          );
        })}
        {summaries.length === 0 && (
          <div className="col-span-full text-center py-12 text-muted-foreground">
            <TrendingUp className="h-12 w-12 mx-auto mb-3 opacity-40" />
            <p>Take a diagnostic assessment to start tracking your journey.</p>
          </div>
        )}
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <Activity className="h-5 w-5 text-primary" />
            <CardTitle>Recent Activity</CardTitle>
          </div>
          <CardDescription>Your last 10 actions across all courses.</CardDescription>
        </CardHeader>
        <CardContent>
          {recentActivity.length > 0 ? (
            <div className="space-y-3">
              {recentActivity.map((act, i) => (
                <div key={i} className="flex items-center gap-3 p-3 rounded-lg border">
                  <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0">
                    {activityIcons[act.action] ?? <CheckCircle2 className="h-4 w-4" />}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium">{act.description}</p>
                    <p className="text-xs text-muted-foreground">{new Date(act.date).toLocaleDateString()}</p>
                  </div>
                  <Badge variant="outline" className="text-xs shrink-0">{act.action}</Badge>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-sm text-muted-foreground text-center py-6">No recent activity to show.</p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
