import { useParams, useNavigate } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import { ArrowRight, Target, TrendingUp } from "lucide-react";
import { useProficiency } from "@/hooks/queries";

function getMasteryColor(mastery: number): string {
  if (mastery >= 80) return "text-green-600";
  if (mastery >= 60) return "text-blue-600";
  if (mastery >= 40) return "text-yellow-600";
  if (mastery >= 20) return "text-orange-600";
  return "text-red-600";
}

function getMasteryBg(mastery: number): string {
  if (mastery >= 80) return "bg-green-100";
  if (mastery >= 60) return "bg-blue-100";
  if (mastery >= 40) return "bg-yellow-100";
  if (mastery >= 20) return "bg-orange-100";
  return "bg-red-100";
}

export default function ProficiencyProfile() {
  const { subjectId } = useParams<{ subjectId: string }>();
  const navigate = useNavigate();
  const { data: proficiencies = [], isLoading } = useProficiency({ subject_id: Number(subjectId) });

  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>;

  const domains = [...new Set(proficiencies.map(p => p.domain_name))];
  const overallMastery = proficiencies.length > 0 ? proficiencies.reduce((sum, p) => sum + p.mastery, 0) / proficiencies.length : 0;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Proficiency Profile</h1>
          <p className="text-muted-foreground">Your knowledge map across all topics.</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => navigate(`/student/diagnostic/${subjectId}`)}>Retake Diagnostic</Button>
          <Button onClick={() => navigate(`/student/plan/${subjectId}`)}>Learning Plan <ArrowRight className="ml-1 h-4 w-4" /></Button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardContent className="pt-6 text-center">
            <Target className="h-8 w-8 mx-auto text-primary mb-2" />
            <div className="text-3xl font-bold">{Math.round(overallMastery)}%</div>
            <p className="text-sm text-muted-foreground">Overall Mastery</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6 text-center">
            <TrendingUp className="h-8 w-8 mx-auto text-green-500 mb-2" />
            <div className="text-3xl font-bold">{proficiencies.filter(p => p.mastery >= 80).length}</div>
            <p className="text-sm text-muted-foreground">Topics Mastered</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6 text-center">
            <div className="h-8 w-8 mx-auto text-orange-500 mb-2 text-2xl font-bold">{proficiencies.filter(p => p.mastery < 40).length}</div>
            <p className="text-sm text-muted-foreground">Topics Needing Work</p>
          </CardContent>
        </Card>
      </div>

      {domains.map((domain) => {
        const topics = proficiencies.filter(p => p.domain_name === domain);
        const domainMastery = topics.reduce((s, t) => s + t.mastery, 0) / topics.length;

        return (
          <Card key={domain}>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-lg">{domain}</CardTitle>
                <Badge variant="outline" className={getMasteryColor(domainMastery)}>{Math.round(domainMastery)}%</Badge>
              </div>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                {topics.map((topic) => (
                  <div
                    key={topic.topic_id}
                    className={`p-3 rounded-lg border ${getMasteryBg(topic.mastery)} cursor-pointer hover:shadow-sm transition-shadow`}
                    onClick={() => navigate(`/student/topic/${topic.topic_id}`)}
                  >
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm font-medium truncate">{topic.topic_name}</span>
                      <span className={`text-sm font-semibold ${getMasteryColor(topic.mastery)}`}>{Math.round(topic.mastery)}%</span>
                    </div>
                    <Progress value={topic.mastery} className="h-1.5" />
                    <div className="flex items-center justify-between mt-1">
                      <Badge variant="secondary" className="text-xs">{topic.mastery_level}</Badge>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        );
      })}

      {proficiencies.length === 0 && (
        <Card>
          <CardContent className="text-center py-12 text-muted-foreground">
            <p>No proficiency data yet. Take a diagnostic assessment first.</p>
            <Button className="mt-4" onClick={() => navigate(`/student/diagnostic/${subjectId}`)}>Start Diagnostic</Button>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
