"use client"
import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import {
  ArrowLeft,
  Calendar,
  CreditCard,
  Download,
  Edit,
  GraduationCap,
  Mail,
  MoreHorizontal,
  Phone,
  User,
  UserCog,
  Clock,
  CheckCircle,
  BookOpen,
  FileText,
  BarChart3,
  MessageSquare,
  Trash2,
} from "lucide-react"

import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Separator } from "@/components/ui/separator"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Progress } from "@/components/ui/progress"

import { getStudentById } from "@/services/students/query"
import { orders as ordersData } from "@/services/orders/query"
import type { Student } from "@/services/types"

// Mock data for enrollments
const enrollments = [
  {
    id: 1,
    course_id: 1,
    course_name: "Super Memory Mastery",
    package_name: "Online Long-Term Course",
    status: "in_progress",
    progress: 65,
    start_date: "2024-02-15T10:00:00Z",
    last_accessed: "2024-04-18T14:30:00Z",
  },
  {
    id: 2,
    course_id: 2,
    course_name: "Speed Reading Mastery",
    package_name: "Offline Intensive Course",
    status: "completed",
    progress: 100,
    start_date: "2023-11-10T09:00:00Z",
    last_accessed: "2024-01-20T16:45:00Z",
  },
  {
    id: 3,
    course_id: 3,
    course_name: "Mind Mapping Techniques",
    package_name: "Online Self-Paced Course",
    status: "not_started",
    progress: 0,
    start_date: "2024-04-01T08:30:00Z",
    last_accessed: null,
  },
]

// Mock data for payments
const payments = [
  {
    id: 1,
    order_id: 1,
    amount: 1898,
    status: "completed",
    payment_method: "credit_card",
    date: "2024-04-01T10:30:00Z",
    description: "Payment for Super Memory Mastery Course",
  },
  {
    id: 2,
    order_id: 2,
    amount: 450,
    status: "completed",
    payment_method: "paypal",
    date: "2023-11-10T09:15:00Z",
    description: "Payment for Speed Reading Mastery Course",
  },
  {
    id: 3,
    order_id: 3,
    amount: 299,
    status: "pending",
    payment_method: "bank_transfer",
    date: "2024-04-01T08:45:00Z",
    description: "Payment for Mind Mapping Techniques Course",
  },
]

export default function StudentDetailPage({ params }: { params: { id: string } }) {
  const router = useRouter()
  const studentId = Number.parseInt(params.id)

  const [student, setStudent] = useState<Student | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchStudent = async () => {
      try {
        setLoading(true)
        console.log("[student] Fetching student with ID:", studentId)
        const studentData = await getStudentById(studentId)
        console.log("[student] Student data fetched:", studentData)
        setStudent(studentData)
      } catch (err) {
        console.error("[student] Error fetching student:", err)
        setError("Failed to load student data")
      } finally {
        setLoading(false)
      }
    }

    if (studentId) {
      fetchStudent()
    }
  }, [studentId])

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center h-[80vh]">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mb-4"></div>
        <p className="text-muted-foreground">Loading student data...</p>
      </div>
    )
  }

  if (error || !student) {
    return (
      <div className="flex flex-col items-center justify-center h-[80vh]">
        <h1 className="text-2xl font-bold mb-2">Student Not Found</h1>
        <p className="text-muted-foreground mb-4">
          {error || "The student you're looking for doesn't exist or has been removed."}
        </p>
        <Button onClick={() => router.push("/admin/students")}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back to Students
        </Button>
      </div>
    )
  }

  // Get student's orders - ensure orders is always an array
  const orders = Array.isArray(ordersData) ? ordersData : []
  const studentOrders = orders.filter((order) => order.student_id === studentId)

  return (
    <div className="flex flex-col gap-6 p-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Button variant="outline" size="icon" onClick={() => router.push("/admin/students")}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <h1 className="text-3xl font-bold tracking-tight">Student Profile</h1>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline">
            <Mail className="mr-2 h-4 w-4" />
            Contact
          </Button>
          <Button>
            <Edit className="mr-2 h-4 w-4" />
            Edit Profile
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <Card className="md:col-span-1">
          <CardHeader className="pb-3">
            <CardTitle>Student Information</CardTitle>
            <CardDescription>Personal details and account information</CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col items-center text-center pb-2">
            <Avatar className="h-24 w-24 mb-4">
              <AvatarImage src={student.avatar || "/placeholder.svg"} alt={student.name} />
              <AvatarFallback className="text-xl">{student.name.charAt(0)}</AvatarFallback>
            </Avatar>
            <h3 className="text-xl font-semibold">{student.name}</h3>
            <p className="text-muted-foreground mb-4">Student ID: {student.id}</p>

            <div className="w-full space-y-3 mt-2">
              <div className="flex items-center gap-2 text-sm">
                <Mail className="h-4 w-4 text-muted-foreground" />
                <span className="text-left flex-1">{student.email}</span>
              </div>
              <div className="flex items-center gap-2 text-sm">
                <Phone className="h-4 w-4 text-muted-foreground" />
                <span className="text-left flex-1">{student.contact_number}</span>
              </div>
              <div className="flex items-center gap-2 text-sm">
                <Calendar className="h-4 w-4 text-muted-foreground" />
                <span className="text-left flex-1">Joined: {new Date(student.created_at).toLocaleDateString()}</span>
              </div>
            </div>
          </CardContent>
          <Separator className="my-2" />
          <CardFooter className="flex justify-between pt-3">
            <Button variant="outline" size="sm">
              <UserCog className="mr-2 h-4 w-4" />
              Manage Access
            </Button>
            <Button variant="destructive" size="sm">
              <Trash2 className="mr-2 h-4 w-4" />
              Delete
            </Button>
          </CardFooter>
        </Card>

        <Card className="md:col-span-2">
          <CardHeader className="pb-3">
            <CardTitle>Overview</CardTitle>
            <CardDescription>Student activity and enrollment summary</CardDescription>
          </CardHeader>
          <CardContent className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-blue-50 rounded-lg p-4 border border-blue-100">
              <div className="flex items-center justify-between mb-2">
                <h4 className="text-sm font-medium text-blue-700">Enrollments</h4>
                <GraduationCap className="h-4 w-4 text-blue-700" />
              </div>
              <p className="text-2xl font-bold text-blue-800">{enrollments.length}</p>
              <p className="text-xs text-blue-600 mt-1">
                {enrollments.filter((e) => e.status === "completed").length} completed
              </p>
            </div>

            <div className="bg-green-50 rounded-lg p-4 border border-green-100">
              <div className="flex items-center justify-between mb-2">
                <h4 className="text-sm font-medium text-green-700">Total Spent</h4>
                <CreditCard className="h-4 w-4 text-green-700" />
              </div>
              <p className="text-2xl font-bold text-green-800">
                ${studentOrders.reduce((sum, order) => sum + order.final_amount, 0)}
              </p>
              <p className="text-xs text-green-600 mt-1">{studentOrders.length} orders</p>
            </div>

            <div className="bg-amber-50 rounded-lg p-4 border border-amber-100">
              <div className="flex items-center justify-between mb-2">
                <h4 className="text-sm font-medium text-amber-700">Last Activity</h4>
                <Clock className="h-4 w-4 text-amber-700" />
              </div>
              <p className="text-sm font-medium text-amber-800">
                {enrollments.some((e) => e.last_accessed)
                  ? new Date(
                      Math.max(
                        ...enrollments.filter((e) => e.last_accessed).map((e) => new Date(e.last_accessed!).getTime()),
                      ),
                    ).toLocaleDateString()
                  : "No activity yet"}
              </p>
              <p className="text-xs text-amber-600 mt-1">
                {enrollments.some((e) => e.status === "in_progress") ? "Active student" : "Inactive student"}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>

      <Tabs defaultValue="enrollments" className="w-full">
        <TabsList className="grid w-full grid-cols-3 mb-4">
          <TabsTrigger value="enrollments">Enrollments</TabsTrigger>
          <TabsTrigger value="payments">Payment History</TabsTrigger>
          <TabsTrigger value="activity">Activity Log</TabsTrigger>
        </TabsList>

        <TabsContent value="enrollments" className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle>Course Enrollments</CardTitle>
                <Button variant="outline" size="sm">
                  <GraduationCap className="mr-2 h-4 w-4" />
                  Enroll in New Course
                </Button>
              </div>
              <CardDescription>All courses the student is enrolled in</CardDescription>
            </CardHeader>
            <CardContent>
              {enrollments.length > 0 ? (
                <div className="space-y-4">
                  {enrollments.map((enrollment, index) => (
                    <div
                      key={enrollment.id}
                      className={`rounded-lg border p-4 ${
                        index % 3 === 0
                          ? "bg-blue-50/50 border-blue-100"
                          : index % 3 === 1
                            ? "bg-green-50/50 border-green-100"
                            : "bg-amber-50/50 border-amber-100"
                      }`}
                    >
                      <div className="flex items-start justify-between mb-2">
                        <div>
                          <h3 className="font-medium">{enrollment.course_name}</h3>
                          <p className="text-sm text-muted-foreground">{enrollment.package_name}</p>
                        </div>
                        <Badge
                          variant="outline"
                          className={
                            enrollment.status === "completed"
                              ? "bg-green-50 text-green-700 border-green-200"
                              : enrollment.status === "in_progress"
                                ? "bg-blue-50 text-blue-700 border-blue-200"
                                : "bg-amber-50 text-amber-700 border-amber-200"
                          }
                        >
                          {enrollment.status === "completed"
                            ? "Completed"
                            : enrollment.status === "in_progress"
                              ? "In Progress"
                              : "Not Started"}
                        </Badge>
                      </div>

                      <div className="space-y-2">
                        <div className="flex justify-between text-sm">
                          <span>Progress</span>
                          <span>{enrollment.progress}%</span>
                        </div>
                        <Progress value={enrollment.progress} className="h-2" />
                      </div>

                      <div className="mt-4 flex flex-wrap gap-2 text-xs text-muted-foreground">
                        <div className="flex items-center">
                          <Calendar className="mr-1 h-3 w-3" />
                          Started: {new Date(enrollment.start_date).toLocaleDateString()}
                        </div>
                        {enrollment.last_accessed && (
                          <div className="flex items-center">
                            <Clock className="mr-1 h-3 w-3" />
                            Last accessed: {new Date(enrollment.last_accessed).toLocaleDateString()}
                          </div>
                        )}
                      </div>

                      <div className="mt-3 flex justify-end gap-2">
                        <Button variant="outline" size="sm">
                          <BookOpen className="mr-1 h-3 w-3" />
                          View Course
                        </Button>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="icon" className="h-8 w-8">
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem>
                              <FileText className="mr-2 h-4 w-4" />
                              View Details
                            </DropdownMenuItem>
                            <DropdownMenuItem>
                              <BarChart3 className="mr-2 h-4 w-4" />
                              View Progress
                            </DropdownMenuItem>
                            <DropdownMenuItem>
                              <MessageSquare className="mr-2 h-4 w-4" />
                              Send Message
                            </DropdownMenuItem>
                            <DropdownMenuSeparator />
                            <DropdownMenuItem className="text-destructive">
                              <Trash2 className="mr-2 h-4 w-4" />
                              Unenroll
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center py-8 text-center">
                  <GraduationCap className="h-12 w-12 text-muted-foreground mb-4" />
                  <h3 className="text-lg font-medium mb-1">No Enrollments</h3>
                  <p className="text-muted-foreground mb-4">This student is not enrolled in any courses yet.</p>
                  <Button>Enroll in a Course</Button>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="payments" className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle>Payment History</CardTitle>
                <Button variant="outline" size="sm">
                  <Download className="mr-2 h-4 w-4" />
                  Export
                </Button>
              </div>
              <CardDescription>All payments made by the student</CardDescription>
            </CardHeader>
            <CardContent>
              {payments.length > 0 ? (
                <div className="space-y-4">
                  {payments.map((payment, index) => (
                    <div
                      key={payment.id}
                      className={`rounded-lg border p-4 ${
                        index % 3 === 0
                          ? "bg-purple-50/50 border-purple-100"
                          : index % 3 === 1
                            ? "bg-cyan-50/50 border-cyan-100"
                            : "bg-rose-50/50 border-rose-100"
                      }`}
                    >
                      <div className="flex items-start justify-between mb-2">
                        <div>
                          <h3 className="font-medium">${payment.amount}</h3>
                          <p className="text-sm text-muted-foreground">{payment.description}</p>
                        </div>
                        <Badge
                          variant="outline"
                          className={
                            payment.status === "completed"
                              ? "bg-green-50 text-green-700 border-green-200"
                              : payment.status === "pending"
                                ? "bg-amber-50 text-amber-700 border-amber-200"
                                : "bg-red-50 text-red-700 border-red-200"
                          }
                        >
                          {payment.status === "completed"
                            ? "Completed"
                            : payment.status === "pending"
                              ? "Pending"
                              : "Failed"}
                        </Badge>
                      </div>

                      <div className="mt-2 flex flex-wrap gap-2 text-xs text-muted-foreground">
                        <div className="flex items-center">
                          <Calendar className="mr-1 h-3 w-3" />
                          Date: {new Date(payment.date).toLocaleDateString()}
                        </div>
                        <div className="flex items-center">
                          <CreditCard className="mr-1 h-3 w-3" />
                          Method: {payment.payment_method.replace("_", " ")}
                        </div>
                        <div className="flex items-center">
                          <FileText className="mr-1 h-3 w-3" />
                          Order ID: #{payment.order_id}
                        </div>
                      </div>

                      <div className="mt-3 flex justify-end gap-2">
                        <Button variant="outline" size="sm">
                          <FileText className="mr-1 h-3 w-3" />
                          View Receipt
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center py-8 text-center">
                  <CreditCard className="h-12 w-12 text-muted-foreground mb-4" />
                  <h3 className="text-lg font-medium mb-1">No Payments</h3>
                  <p className="text-muted-foreground mb-4">This student has not made any payments yet.</p>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="activity" className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle>Activity Log</CardTitle>
              <CardDescription>Recent student activity and system events</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="relative pl-6 border-l">
                {/* Activity log items */}
                <div className="mb-8 relative">
                  <div className="absolute -left-[25px] p-1 rounded-full bg-blue-100 border-2 border-white">
                    <BookOpen className="h-4 w-4 text-blue-600" />
                  </div>
                  <div className="mb-1">
                    <span className="font-medium">Completed Lesson 5</span>
                    <span className="text-xs text-muted-foreground ml-2">Today, 10:45 AM</span>
                  </div>
                  <p className="text-sm text-muted-foreground">
                    Completed "Advanced Memory Techniques" in Super Memory Mastery course
                  </p>
                </div>

                <div className="mb-8 relative">
                  <div className="absolute -left-[25px] p-1 rounded-full bg-green-100 border-2 border-white">
                    <CheckCircle className="h-4 w-4 text-green-600" />
                  </div>
                  <div className="mb-1">
                    <span className="font-medium">Passed Quiz</span>
                    <span className="text-xs text-muted-foreground ml-2">Yesterday, 3:20 PM</span>
                  </div>
                  <p className="text-sm text-muted-foreground">Scored 92% on "Memory Techniques Assessment" quiz</p>
                </div>

                <div className="mb-8 relative">
                  <div className="absolute -left-[25px] p-1 rounded-full bg-amber-100 border-2 border-white">
                    <CreditCard className="h-4 w-4 text-amber-600" />
                  </div>
                  <div className="mb-1">
                    <span className="font-medium">Payment Completed</span>
                    <span className="text-xs text-muted-foreground ml-2">Apr 1, 2024</span>
                  </div>
                  <p className="text-sm text-muted-foreground">Paid $1,898 for Super Memory Mastery Course</p>
                </div>

                <div className="mb-8 relative">
                  <div className="absolute -left-[25px] p-1 rounded-full bg-purple-100 border-2 border-white">
                    <GraduationCap className="h-4 w-4 text-purple-600" />
                  </div>
                  <div className="mb-1">
                    <span className="font-medium">Enrolled in Course</span>
                    <span className="text-xs text-muted-foreground ml-2">Feb 15, 2024</span>
                  </div>
                  <p className="text-sm text-muted-foreground">Enrolled in "Super Memory Mastery" course</p>
                </div>

                <div className="relative">
                  <div className="absolute -left-[25px] p-1 rounded-full bg-blue-100 border-2 border-white">
                    <User className="h-4 w-4 text-blue-600" />
                  </div>
                  <div className="mb-1">
                    <span className="font-medium">Account Created</span>
                    <span className="text-xs text-muted-foreground ml-2">
                      {new Date(student.created_at).toLocaleDateString()}
                    </span>
                  </div>
                  <p className="text-sm text-muted-foreground">Student account was created</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
