import type { ReactNode } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { FileText, Video, Link2, BookOpen, MessageSquare, Trophy, ExternalLink } from "lucide-react";
import { useTopicContent } from "@/hooks/queries";
import AiStudyCoach from "@/components/ai/AiStudyCoach";

const resourceIcons: Record<string, ReactNode> = {
  pdf: <FileText className="h-4 w-4" />,
  video: <Video className="h-4 w-4" />,
  link: <Link2 className="h-4 w-4" />,
  document: <BookOpen className="h-4 w-4" />,
  interactive: <MessageSquare className="h-4 w-4" />,
};

export default function TopicLearning() {
  const { topicId } = useParams<{ topicId: string }>();
  const navigate = useNavigate();
  const { data: topicContent, isLoading } = useTopicContent(Number(topicId));

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

  if (!topicContent) {
    return (
      <div className="text-center py-16 text-muted-foreground">
        <BookOpen className="h-12 w-12 mx-auto mb-3 opacity-40" />
        <p>Topic content not found.</p>
        <Button variant="outline" className="mt-4" onClick={() => navigate(-1)}>Go Back</Button>
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <div className="lg:col-span-2 space-y-6">
        <div>
          <h1 className="text-2xl font-bold">{topicContent.topic_name}</h1>
          {topicContent.has_content_gap && (
            <Badge variant="secondary" className="mt-2">AI-supplemented content</Badge>
          )}
        </div>

        {topicContent.ai_content && (
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <MessageSquare className="h-5 w-5 text-primary" />
                AI Explanation
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <p className="text-sm leading-relaxed">{topicContent.ai_content.explanation}</p>
              {topicContent.ai_content.key_points.length > 0 && (
                <>
                  <h4 className="font-medium text-sm">Key Points</h4>
                  <ul className="list-disc pl-5 space-y-1 text-sm text-muted-foreground">
                    {topicContent.ai_content.key_points.map((point, i) => (
                      <li key={i}>{point}</li>
                    ))}
                  </ul>
                </>
              )}
              {topicContent.ai_content.examples.length > 0 && (
                <>
                  <h4 className="font-medium text-sm">Examples</h4>
                  {topicContent.ai_content.examples.map((ex, i) => (
                    <div key={i} className="p-3 bg-accent/50 rounded-lg text-sm">{ex}</div>
                  ))}
                </>
              )}
            </CardContent>
          </Card>
        )}

        {topicContent.resources.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Resources</CardTitle>
              <CardDescription>{topicContent.resources.length} resources available</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {topicContent.resources.map((resource) => (
                  <div key={resource.id} className="flex items-center justify-between p-3 rounded-lg border hover:bg-accent/50 transition-colors">
                    <div className="flex items-center gap-3">
                      {resourceIcons[resource.resource_type] ?? <FileText className="h-4 w-4" />}
                      <div>
                        <p className="text-sm font-medium">{resource.name}</p>
                        <p className="text-xs text-muted-foreground capitalize">{resource.resource_type}</p>
                      </div>
                    </div>
                    {resource.url && (
                      <Button variant="ghost" size="sm" asChild>
                        <a href={resource.url} target="_blank" rel="noopener noreferrer">
                          Open <ExternalLink className="ml-1 h-3 w-3" />
                        </a>
                      </Button>
                    )}
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        <Separator />

        <div className="flex gap-3">
          <Button variant="outline" className="flex-1">
            <BookOpen className="mr-2 h-4 w-4" /> Practice Questions
          </Button>
          <Button className="flex-1">
            <Trophy className="mr-2 h-4 w-4" /> Mastery Quiz
          </Button>
        </div>
      </div>

      <div className="space-y-6">
        <AiStudyCoach />
      </div>
    </div>
  );
}
