import { useMemo, useState } from "react";
import { useParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { courseGenerationService } from "@/services/course-generation.service";
import type { CourseConfig } from "@/types";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { AlertTriangle } from "lucide-react";

type ProgressRow = {
  student_name: string;
  overall_progress: number;
  current_module: string;
  time_spent_hours: number;
  predicted_band_delta: number;
  last_activity: string;
  days_idle: number;
};

type CourseWithProgress = CourseConfig & { student_progress?: ProgressRow[] };

export default function CourseProgress() {
  const { courseId: courseIdParam } = useParams();
  const courseId = Number(courseIdParam);
  const [sortKey, setSortKey] = useState<keyof ProgressRow>("student_name");
  const [filter, setFilter] = useState("");
  const [selected, setSelected] = useState<ProgressRow | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ["course", courseId, "teacher-progress"],
    queryFn: () => courseGenerationService.getCourse(courseId) as Promise<CourseWithProgress>,
    enabled: Number.isFinite(courseId) && courseId > 0,
  });

  const rows = useMemo(() => {
    const raw = data?.student_progress;
    if (raw?.length) return raw;
    return [
      {
        student_name: "Amina Rahman",
        overall_progress: 62,
        current_module: "Writing · Task Achievement",
        time_spent_hours: 14,
        predicted_band_delta: 0.5,
        last_activity: new Date().toISOString(),
        days_idle: 1,
      },
      {
        student_name: "Leo Park",
        overall_progress: 12,
        current_module: "Listening · Section 2",
        time_spent_hours: 3,
        predicted_band_delta: 0.1,
        last_activity: new Date(Date.now() - 4 * 86400000).toISOString(),
        days_idle: 4,
      },
    ] satisfies ProgressRow[];
  }, [data]);

  const sorted = useMemo(() => {
    const f = filter.trim().toLowerCase();
    const list = f ? rows.filter((r) => r.student_name.toLowerCase().includes(f)) : [...rows];
    list.sort((a, b) => {
      const av = a[sortKey];
      const bv = b[sortKey];
      if (typeof av === "number" && typeof bv === "number") return bv - av;
      return String(av).localeCompare(String(bv));
    });
    return list;
  }, [rows, sortKey, filter]);

  if (isLoading) {
    return (
      <div className="p-6">
        <Skeleton className="mb-4 h-10 w-64" />
        <Skeleton className="h-72 w-full" />
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-6xl space-y-6 p-6">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold">Course progress</h1>
          <p className="text-muted-foreground">{data?.title ?? `Course ${courseId}`}</p>
        </div>
        <Input
          placeholder="Filter by name"
          className="max-w-xs"
          value={filter}
          onChange={(e) => setFilter(e.target.value)}
        />
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Students</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="cursor-pointer" onClick={() => setSortKey("student_name")}>
                  Student Name
                </TableHead>
                <TableHead className="cursor-pointer" onClick={() => setSortKey("overall_progress")}>
                  Overall Progress
                </TableHead>
                <TableHead>Current Module</TableHead>
                <TableHead className="cursor-pointer" onClick={() => setSortKey("time_spent_hours")}>
                  Time Spent (h)
                </TableHead>
                <TableHead className="cursor-pointer" onClick={() => setSortKey("predicted_band_delta")}>
                  Predicted Δ Band
                </TableHead>
                <TableHead className="cursor-pointer" onClick={() => setSortKey("last_activity")}>
                  Last Activity
                </TableHead>
                <TableHead className="w-12">Alert</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {sorted.map((row) => {
                const alert = row.days_idle >= 3;
                return (
                  <TableRow key={row.student_name}>
                    <TableCell>
                      <Button
                        type="button"
                        variant="link"
                        className="h-auto p-0 font-medium"
                        onClick={() => setSelected(row)}
                      >
                        {row.student_name}
                      </Button>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Progress value={row.overall_progress} className="h-2 w-28" />
                        <span className="text-xs tabular-nums">{row.overall_progress}%</span>
                      </div>
                    </TableCell>
                    <TableCell className="max-w-[200px] truncate">{row.current_module}</TableCell>
                    <TableCell>{row.time_spent_hours}</TableCell>
                    <TableCell>+{row.predicted_band_delta.toFixed(1)}</TableCell>
                    <TableCell className="whitespace-nowrap text-xs text-muted-foreground">
                      {new Date(row.last_activity).toLocaleString()}
                    </TableCell>
                    <TableCell>
                      {alert ? (
                        <span className="text-amber-600" title="No progress 3+ days">
                          <AlertTriangle className="h-4 w-4" />
                        </span>
                      ) : (
                        <Badge variant="outline">OK</Badge>
                      )}
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {selected ? (
        <Card>
          <CardHeader>
            <CardTitle>{selected.student_name}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2 text-sm">
            <p>
              <span className="text-muted-foreground">Current module:</span> {selected.current_module}
            </p>
            <p>
              <span className="text-muted-foreground">Time spent:</span> {selected.time_spent_hours} h
            </p>
            <p>
              <span className="text-muted-foreground">Predicted band improvement:</span> +
              {selected.predicted_band_delta.toFixed(1)}
            </p>
          </CardContent>
        </Card>
      ) : null}
    </div>
  );
}
