import { useState } from "react";
import { Link } from "@inertiajs/react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import {
  BookOpen, CheckCircle2, Play, ChevronRight, Clock, Award,
  ArrowLeft, Lock, Loader2,
} from "lucide-react";
import { toast } from "sonner";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

interface ELearningPlayerProps {
  slug?: string;
}

const ELearningPlayerPage = ({ slug: slugProp }: ELearningPlayerProps = {}) => {
  const slug = slugProp ?? window.location.pathname.split('/').pop();
  const { user } = useAuth();
  const queryClient = useQueryClient();
  const [activeModule, setActiveModule] = useState(0);

  const { data: course, isLoading: courseLoading } = useQuery({
    queryKey: ["elearning-course", slug],
    queryFn: async () => {
      try {
        const res = await fetch(`/api/marketplace/courses/${encodeURIComponent(slug!)}?category=E-Learning`);
        if (!res.ok) return null;
        return await res.json();
      } catch {
        return null;
      }
    },
    enabled: !!slug,
  });

  const { data: enrolment } = useQuery({
    queryKey: ["elearning-enrolment", course?.id, (user as any)?.id],
    queryFn: async () => {
      try {
        const res = await fetch(`/api/elearning/enrolments?course_id=${encodeURIComponent(course!.id)}`);
        if (!res.ok) return null;
        const data = await res.json();
        if (Array.isArray(data)) return data[0] ?? null;
        return data ?? null;
      } catch {
        return null;
      }
    },
    enabled: !!course?.id && !!(user as any)?.id,
  });

  // Generate modules from course content
  const modules = (() => {
    if (!course?.course_content) return [
      { title: "Introduction", content: "Welcome to this e-learning course. Content will be available shortly." },
      { title: "Core Material", content: "The main learning material for this course." },
      { title: "Assessment", content: "Complete the assessment to receive your certification." },
    ];
    const sections = course.course_content.split("\n").filter((s: string) => s.trim());
    if (sections.length <= 1) return [
      { title: "Module 1: Introduction", content: course.course_content },
      { title: "Module 2: Core Content", content: "Additional course material." },
      { title: "Module 3: Assessment", content: "Complete the assessment." },
    ];
    return sections.map((s: string, i: number) => ({
      title: `Module ${i + 1}: ${s.replace(/^[-•*]\s*/, "").trim()}`,
      content: s.trim(),
    }));
  })();

  const startMutation = useMutation({
    mutationFn: async () => {
      const res = await fetch('/api/elearning/enrolments', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({
          course_id: course!.id,
          status: "in_progress",
          progress_percent: 0,
          started_at: new Date().toISOString(),
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data?.error || "Failed to start course");
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["elearning-enrolment"] });
      toast.success("Course started!");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const updateProgressMutation = useMutation({
    mutationFn: async (newProgress: number) => {
      const updates: Record<string, unknown> = {
        progress_percent: newProgress,
      };
      if (newProgress >= 100) {
        updates.status = "completed";
        updates.completed_at = new Date().toISOString();
      } else {
        updates.status = "in_progress";
      }
      const res = await fetch(`/api/elearning/enrolments/${enrolment!.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify(updates),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data?.error || "Failed to save progress");
      }
    },
    onSuccess: (_, newProgress) => {
      queryClient.invalidateQueries({ queryKey: ["elearning-enrolment"] });
      if (newProgress >= 100) {
        toast.success("🎉 Course completed! Certificate will be issued.");
      } else {
        toast.success("Progress saved");
      }
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const handleCompleteModule = () => {
    if (!enrolment) return;
    const newProgress = Math.min(100, Math.round(((activeModule + 1) / modules.length) * 100));
    updateProgressMutation.mutate(newProgress);
    if (activeModule < modules.length - 1) {
      setActiveModule(activeModule + 1);
    }
  };

  if (courseLoading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  if (!course) {
    return (
      <div className="min-h-screen bg-background">
        <Navbar />
        <div className="container mx-auto px-4 py-24 text-center">
          <h1 className="text-3xl font-bold text-foreground mb-4">Course Not Found</h1>
          <Link href="/courses"><Button variant="hero">Browse Courses</Button></Link>
        </div>
        <Footer />
      </div>
    );
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-background">
        <Navbar />
        <div className="container mx-auto px-4 py-24 text-center">
          <Lock className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
          <h1 className="text-2xl font-bold text-foreground mb-2">Sign In Required</h1>
          <p className="text-muted-foreground mb-6">You need to be signed in to access e-learning courses.</p>
          <Link href="/auth"><Button variant="hero">Sign In</Button></Link>
        </div>
        <Footer />
      </div>
    );
  }

  const progress = (enrolment as any)?.progress_percent || 0;
  const isCompleted = (enrolment as any)?.status === "completed";

  return (
    <div className="min-h-screen bg-background">
      <Navbar />
      <div className="pt-20 pb-16">
        <div className="container mx-auto px-4">
          {/* Header */}
          <div className="flex items-center gap-3 mb-6">
            <Button variant="ghost" size="sm" onClick={() => window.history.back()}>
              <ArrowLeft className="h-4 w-4 mr-1" /> Back
            </Button>
          </div>

          <div className="grid lg:grid-cols-4 gap-6">
            {/* Module sidebar */}
            <div className="lg:col-span-1">
              <div className="bg-card border border-border rounded-xl p-4 sticky top-24">
                <h2 className="font-bold text-foreground mb-1">{course.title}</h2>
                <div className="flex items-center gap-2 mb-4">
                  <Progress value={progress} className="h-2 flex-1" />
                  <span className="text-xs text-muted-foreground font-medium">{progress}%</span>
                </div>

                {!enrolment && (
                  <Button
                    variant="hero"
                    size="sm"
                    className="w-full mb-4"
                    onClick={() => startMutation.mutate()}
                    disabled={startMutation.isPending}
                  >
                    <Play className="h-4 w-4 mr-1" /> Start Course
                  </Button>
                )}

                {isCompleted && (
                  <Badge className="mb-4 w-full justify-center bg-green-600 text-white">
                    <Award className="h-3 w-3 mr-1" /> Completed
                  </Badge>
                )}

                <div className="space-y-1">
                  {modules.map((m, i) => {
                    const moduleComplete = enrolment && progress >= Math.round(((i + 1) / modules.length) * 100);
                    return (
                      <button
                        key={i}
                        onClick={() => setActiveModule(i)}
                        className={`w-full text-left px-3 py-2 rounded-lg text-sm flex items-center gap-2 transition-colors ${
                          activeModule === i
                            ? "bg-primary/10 text-primary font-medium"
                            : "text-muted-foreground hover:bg-accent/50"
                        }`}
                      >
                        {moduleComplete ? (
                          <CheckCircle2 className="h-4 w-4 shrink-0 text-green-600" />
                        ) : (
                          <div className="h-4 w-4 rounded-full border-2 border-muted-foreground/30 shrink-0" />
                        )}
                        <span className="truncate">{m.title}</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>

            {/* Content area */}
            <div className="lg:col-span-3">
              <Card>
                <CardContent className="pt-8 pb-8 px-8">
                  <div className="flex items-center gap-2 text-xs text-muted-foreground mb-4">
                    <BookOpen className="h-3 w-3" />
                    Module {activeModule + 1} of {modules.length}
                  </div>

                  <h2 className="text-2xl font-bold text-foreground mb-6">
                    {modules[activeModule].title}
                  </h2>

                  <div className="prose prose-sm max-w-none text-foreground/80 mb-8">
                    <p>{modules[activeModule].content}</p>
                    {activeModule === modules.length - 1 && (
                      <div className="mt-6 p-4 bg-muted/50 rounded-lg">
                        <p className="font-medium">Assessment Instructions</p>
                        <p>Review all previous modules and confirm your understanding by marking this module as complete. Your certificate will be issued automatically upon completion.</p>
                      </div>
                    )}
                  </div>

                  <div className="flex items-center justify-between border-t border-border pt-6">
                    <Button
                      variant="outline"
                      disabled={activeModule === 0}
                      onClick={() => setActiveModule(activeModule - 1)}
                    >
                      Previous
                    </Button>

                    {enrolment ? (
                      <Button
                        variant="hero"
                        onClick={handleCompleteModule}
                        disabled={updateProgressMutation.isPending || isCompleted}
                      >
                        {isCompleted
                          ? "Course Complete"
                          : activeModule === modules.length - 1
                          ? "Complete Course"
                          : "Mark Complete & Next"}
                        <ChevronRight className="h-4 w-4 ml-1" />
                      </Button>
                    ) : (
                      <Button variant="hero" onClick={() => startMutation.mutate()} disabled={startMutation.isPending}>
                        <Play className="h-4 w-4 mr-1" /> Start Course to Track Progress
                      </Button>
                    )}
                  </div>
                </CardContent>
              </Card>

              {/* Course info */}
              <div className="grid sm:grid-cols-3 gap-4 mt-6">
                <div className="bg-card border border-border rounded-xl p-4 text-center">
                  <Clock className="h-5 w-5 text-muted-foreground mx-auto mb-1" />
                  <p className="text-sm font-medium text-foreground">{course.days} days access</p>
                  <p className="text-xs text-muted-foreground">Self-paced learning</p>
                </div>
                <div className="bg-card border border-border rounded-xl p-4 text-center">
                  <BookOpen className="h-5 w-5 text-muted-foreground mx-auto mb-1" />
                  <p className="text-sm font-medium text-foreground">{modules.length} modules</p>
                  <p className="text-xs text-muted-foreground">Interactive content</p>
                </div>
                <div className="bg-card border border-border rounded-xl p-4 text-center">
                  <Award className="h-5 w-5 text-muted-foreground mx-auto mb-1" />
                  <p className="text-sm font-medium text-foreground">{course.has_certificate ? "Certificate" : "No Certificate"}</p>
                  <p className="text-xs text-muted-foreground">{course.has_certificate ? "Issued on completion" : ""}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default ELearningPlayerPage;
