"use client"

import { useState, useEffect } from "react"
import Link from "next/link"
import Image from "next/image"
import { useRouter } from "next/navigation"
import {
  ArrowLeft,
  Edit,
  Mail,
  Phone,
  Calendar,
  BookOpen,
  Users,
  Star,
  Award,
  Clock,
  BarChart,
  MessageSquare,
  FileText,
  Trash2,
  MoreHorizontal,
  Filter,
  FileDown,
  User,
  AlertTriangle,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { getInstructorById } from "@/services/instructors/query"
import { getCourses } from "@/services/courses/query"
import { Separator } from "@/components/ui/separator"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"

export default function InstructorDetailPage({ params }: { params: { id: string } }) {
  const router = useRouter()
  const instructorId = Number.parseInt(params.id)

  const [instructor, setInstructor] = useState<any>(null)
  const [courses, setCourses] = useState<any[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState("courses")

  // Fetch instructor and courses data
  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true)
        setError(null)

        const [instructorData, coursesData] = await Promise.all([getInstructorById(instructorId), getCourses()])

        if (instructorData) {
          setInstructor(instructorData)
          console.log("[brief][instructor]", {
            id: instructorData.id,
            title: instructorData.name,
          })
        } else {
          setError("Instructor not found")
        }

        const validCourses = Array.isArray(coursesData) ? coursesData : []
        setCourses(validCourses)
      } catch (err) {
        console.error("Failed to fetch data:", err)
        setError("Failed to load instructor data")
      } finally {
        setIsLoading(false)
      }
    }

    fetchData()
  }, [instructorId])

  // For demo purposes, randomly assign some courses to this instructor
  const instructorCourses = courses.filter(() => Math.random() > 0.5)

  if (isLoading) {
    return (
      <div className="p-6 flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-muted-foreground">Loading instructor data...</p>
        </div>
      </div>
    )
  }

  if (error || !instructor) {
    return (
      <div className="p-6">
        <Alert variant="destructive">
          <AlertTriangle className="h-4 w-4" />
          <AlertTitle>Error</AlertTitle>
          <AlertDescription>{error || "Instructor not found. Please check the ID and try again."}</AlertDescription>
        </Alert>
        <Button className="mt-4" variant="outline" onClick={() => router.push("/admin/instructors")}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back to Instructors
        </Button>
      </div>
    )
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-center">
        <div className="flex items-center space-x-2">
          <Button variant="outline" size="icon" onClick={() => router.push("/admin/instructors")}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold tracking-tight">{instructor.name}</h1>
            <p className="text-muted-foreground">{instructor.summary || "Professional Instructor"}</p>
          </div>
        </div>
        <div className="flex items-center space-x-2">
          <Link href={`/admin/instructors/${instructorId}/edit`}>
            <Button className="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700">
              <Edit className="mr-2 h-4 w-4" />
              Edit Instructor
            </Button>
          </Link>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline">Actions</Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem>
                <Mail className="mr-2 h-4 w-4" />
                Send Email
              </DropdownMenuItem>
              <DropdownMenuItem>
                <FileText className="mr-2 h-4 w-4" />
                Generate Report
              </DropdownMenuItem>
              <DropdownMenuItem className="text-red-600 hover:text-red-700 focus:text-red-700">
                <Trash2 className="mr-2 h-4 w-4" />
                Delete Instructor
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Instructor Profile Card - Blue Theme */}
        <Card className="lg:col-span-1 overflow-hidden border-blue-100">
          <div className="h-3 bg-gradient-to-r from-blue-500 to-indigo-600"></div>
          <CardHeader className="pb-2">
            <CardTitle>Instructor Profile</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex flex-col items-center text-center">
              <div className="h-32 w-32 rounded-full overflow-hidden bg-muted mb-4 border-4 border-blue-100">
                {instructor.avatar ? (
                  <Image
                    src={instructor.avatar || "/placeholder.svg"}
                    alt={instructor.name}
                    width={128}
                    height={128}
                    className="h-full w-full object-cover"
                  />
                ) : (
                  <div className="h-full w-full flex items-center justify-center bg-blue-50">
                    <User className="h-16 w-16 text-blue-400" />
                  </div>
                )}
              </div>
              <h3 className="text-xl font-bold">{instructor.name}</h3>
              <p className="text-sm text-muted-foreground mb-2">{instructor.summary || "Professional Instructor"}</p>

              <div className="flex items-center space-x-1 text-amber-500">
                {Array(5)
                  .fill(0)
                  .map((_, i) => (
                    <Star key={i} className="h-4 w-4 fill-current" />
                  ))}
              </div>
              <p className="text-xs text-muted-foreground mt-1">Top Rated Instructor</p>
            </div>

            <Separator />

            <div className="space-y-3">
              <div className="flex items-center text-sm">
                <Mail className="mr-2 h-4 w-4 text-blue-600" />
                <span>{instructor.email}</span>
              </div>
              {instructor.phone && (
                <div className="flex items-center text-sm">
                  <Phone className="mr-2 h-4 w-4 text-blue-600" />
                  <span>{instructor.phone}</span>
                </div>
              )}
              <div className="flex items-center text-sm">
                <Calendar className="mr-2 h-4 w-4 text-blue-600" />
                <span>Joined {new Date(instructor.created_at).toLocaleDateString()}</span>
              </div>
              <div className="flex items-center text-sm">
                <BookOpen className="mr-2 h-4 w-4 text-blue-600" />
                <span>{instructorCourses.length} Courses</span>
              </div>
              <div className="flex items-center text-sm">
                <Users className="mr-2 h-4 w-4 text-blue-600" />
                <span>{Math.floor(Math.random() * 500) + 100} Students</span>
              </div>
            </div>

            <Separator />

            <div className="space-y-2">
              <h4 className="font-medium text-sm">Expertise</h4>
              <div className="flex flex-wrap gap-2">
                <Badge variant="outline" className="bg-blue-50 text-blue-700 hover:bg-blue-100 border-blue-200">
                  Memory Training
                </Badge>
                <Badge variant="outline" className="bg-purple-50 text-purple-700 hover:bg-purple-100 border-purple-200">
                  Speed Reading
                </Badge>
                <Badge variant="outline" className="bg-green-50 text-green-700 hover:bg-green-100 border-green-200">
                  Mind Mapping
                </Badge>
                <Badge variant="outline" className="bg-amber-50 text-amber-700 hover:bg-amber-100 border-amber-200">
                  Cognitive Development
                </Badge>
              </div>
            </div>

            <Separator />

            <div className="space-y-2">
              <h4 className="font-medium text-sm">Achievements</h4>
              <div className="space-y-2">
                <div className="flex items-center text-sm">
                  <Award className="mr-2 h-4 w-4 text-amber-500" />
                  <span>Top Instructor Award 2023</span>
                </div>
                <div className="flex items-center text-sm">
                  <Star className="mr-2 h-4 w-4 text-amber-500" />
                  <span>4.9 Average Rating</span>
                </div>
              </div>
            </div>

            <Separator />

            <div className="space-y-2">
              <h4 className="font-medium text-sm">System Information</h4>
              <div className="space-y-1 text-xs text-muted-foreground">
                <p>Instructor ID: {instructor.id}</p>
                <p>User ID: {instructor.user_id}</p>
                <p>Last Updated: {new Date(instructor.updated_at).toLocaleDateString()}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="lg:col-span-2 space-y-6">
          {/* Overview Cards */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* Students Card - Green Theme */}
            <Card className="border-green-100">
              <div className="h-2 bg-gradient-to-r from-green-400 to-emerald-500"></div>
              <CardContent className="pt-4">
                <div className="flex justify-between items-start">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">Total Students</p>
                    <h3 className="text-2xl font-bold mt-1">{Math.floor(Math.random() * 500) + 100}</h3>
                  </div>
                  <div className="h-10 w-10 rounded-full bg-green-100 flex items-center justify-center">
                    <Users className="h-5 w-5 text-green-600" />
                  </div>
                </div>
                <div className="text-xs text-green-600 mt-2 flex items-center">
                  <span className="font-medium">↑ 12%</span>
                  <span className="text-muted-foreground ml-1">from last month</span>
                </div>
              </CardContent>
            </Card>

            {/* Courses Card - Amber Theme */}
            <Card className="border-amber-100">
              <div className="h-2 bg-gradient-to-r from-amber-400 to-orange-500"></div>
              <CardContent className="pt-4">
                <div className="flex justify-between items-start">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">Active Courses</p>
                    <h3 className="text-2xl font-bold mt-1">{instructorCourses.length}</h3>
                  </div>
                  <div className="h-10 w-10 rounded-full bg-amber-100 flex items-center justify-center">
                    <BookOpen className="h-5 w-5 text-amber-600" />
                  </div>
                </div>
                <div className="text-xs text-amber-600 mt-2 flex items-center">
                  <span className="font-medium">New course</span>
                  <span className="text-muted-foreground ml-1">added this week</span>
                </div>
              </CardContent>
            </Card>

            {/* Rating Card - Purple Theme */}
            <Card className="border-purple-100">
              <div className="h-2 bg-gradient-to-r from-purple-400 to-pink-500"></div>
              <CardContent className="pt-4">
                <div className="flex justify-between items-start">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">Average Rating</p>
                    <h3 className="text-2xl font-bold mt-1">4.9</h3>
                  </div>
                  <div className="h-10 w-10 rounded-full bg-purple-100 flex items-center justify-center">
                    <Star className="h-5 w-5 text-purple-600" />
                  </div>
                </div>
                <div className="text-xs text-purple-600 mt-2 flex items-center">
                  <span className="font-medium">↑ 0.2</span>
                  <span className="text-muted-foreground ml-1">from last quarter</span>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Tabs Section */}
          <Card>
            <CardHeader className="pb-0">
              <CardTitle>Instructor Details</CardTitle>
            </CardHeader>
            <CardContent className="pt-6">
              <Tabs defaultValue="courses" onValueChange={setActiveTab}>
                <TabsList className="grid w-full grid-cols-3 mb-6">
                  <TabsTrigger value="courses">Courses</TabsTrigger>
                  <TabsTrigger value="students">Students</TabsTrigger>
                  <TabsTrigger value="activity">Activity</TabsTrigger>
                </TabsList>

                <TabsContent value="courses" className="space-y-4">
                  <div className="flex justify-between items-center">
                    <h3 className="text-lg font-medium">Instructor's Courses</h3>
                    <Button variant="outline" size="sm">
                      <BookOpen className="mr-2 h-4 w-4" />
                      Assign Course
                    </Button>
                  </div>

                  {instructorCourses.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground">
                      No courses assigned to this instructor yet.
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 gap-4">
                      {instructorCourses.map((course, index) => {
                        // Alternate between different color themes
                        const colorThemes = [
                          { border: "border-blue-100", bg: "bg-blue-50", text: "text-blue-700", icon: "text-blue-600" },
                          {
                            border: "border-green-100",
                            bg: "bg-green-50",
                            text: "text-green-700",
                            icon: "text-green-600",
                          },
                          {
                            border: "border-amber-100",
                            bg: "bg-amber-50",
                            text: "text-amber-700",
                            icon: "text-amber-600",
                          },
                        ]
                        const theme = colorThemes[index % colorThemes.length]

                        return (
                          <div
                            key={course.id}
                            className={`border rounded-lg p-4 ${theme.border} hover:shadow-md transition-shadow`}
                          >
                            <div className="flex items-start justify-between">
                              <div className="flex items-start space-x-3">
                                <div className={`h-12 w-12 rounded-lg ${theme.bg} flex items-center justify-center`}>
                                  <BookOpen className={`h-6 w-6 ${theme.icon}`} />
                                </div>
                                <div>
                                  <h4 className="font-medium">{course.title}</h4>
                                  <p className="text-sm text-muted-foreground line-clamp-1">{course.description}</p>
                                  <div className="flex items-center mt-1 space-x-2">
                                    <Badge
                                      variant="outline"
                                      className={`${theme.bg} ${theme.text} hover:${theme.bg} border-${theme.border}`}
                                    >
                                      ${course.price}
                                    </Badge>
                                    <Badge
                                      variant="outline"
                                      className="bg-gray-50 text-gray-700 hover:bg-gray-100 border-gray-200"
                                    >
                                      {Math.floor(Math.random() * 50) + 10} Students
                                    </Badge>
                                  </div>
                                </div>
                              </div>
                              <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                  <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                                    <span className="sr-only">Open menu</span>
                                    <MoreHorizontal className="h-4 w-4" />
                                  </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                  <DropdownMenuItem>View Course</DropdownMenuItem>
                                  <DropdownMenuItem>Edit Course</DropdownMenuItem>
                                  <DropdownMenuItem className="text-red-600">Unassign</DropdownMenuItem>
                                </DropdownMenuContent>
                              </DropdownMenu>
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  )}
                </TabsContent>

                <TabsContent value="students" className="space-y-4">
                  <div className="flex justify-between items-center">
                    <h3 className="text-lg font-medium">Students Enrolled</h3>
                    <div className="flex items-center space-x-2">
                      <Button variant="outline" size="sm">
                        <Filter className="mr-2 h-4 w-4" />
                        Filter
                      </Button>
                      <Button variant="outline" size="sm">
                        <FileDown className="mr-2 h-4 w-4" />
                        Export
                      </Button>
                    </div>
                  </div>

                  <div className="rounded-md border">
                    <div className="relative w-full overflow-auto">
                      <table className="w-full caption-bottom text-sm">
                        <thead className="bg-muted/50">
                          <tr>
                            <th className="h-10 px-4 text-left align-middle font-medium">Student</th>
                            <th className="h-10 px-4 text-left align-middle font-medium">Course</th>
                            <th className="h-10 px-4 text-left align-middle font-medium">Progress</th>
                            <th className="h-10 px-4 text-left align-middle font-medium">Enrolled</th>
                            <th className="h-10 px-4 text-right align-middle font-medium">Actions</th>
                          </tr>
                        </thead>
                        <tbody>
                          {Array(5)
                            .fill(0)
                            .map((_, index) => (
                              <tr
                                key={index}
                                className={`${index % 2 === 0 ? "bg-white" : "bg-muted/30"} hover:bg-muted/50`}
                              >
                                <td className="p-4 align-middle">
                                  <div className="flex items-center space-x-3">
                                    <div className="h-8 w-8 rounded-full overflow-hidden bg-muted">
                                      <Image
                                        src={`/diverse-students-studying.png?key=1odls&height=32&width=32&query=student${index}`}
                                        alt="Student"
                                        width={32}
                                        height={32}
                                        className="h-full w-full object-cover"
                                      />
                                    </div>
                                    <div>
                                      <div className="font-medium">Student Name {index + 1}</div>
                                      <div className="text-xs text-muted-foreground">
                                        student{index + 1}@example.com
                                      </div>
                                    </div>
                                  </div>
                                </td>
                                <td className="p-4 align-middle">
                                  <div className="font-medium">
                                    {instructorCourses[index % instructorCourses.length]?.title || "Course Name"}
                                  </div>
                                </td>
                                <td className="p-4 align-middle">
                                  <div className="flex items-center space-x-2">
                                    <div className="w-full max-w-24 h-2 bg-gray-200 rounded-full overflow-hidden">
                                      <div
                                        className="h-full bg-green-500 rounded-full"
                                        style={{ width: `${Math.floor(Math.random() * 100)}%` }}
                                      ></div>
                                    </div>
                                    <span className="text-xs">{Math.floor(Math.random() * 100)}%</span>
                                  </div>
                                </td>
                                <td className="p-4 align-middle">
                                  <div className="text-sm">
                                    {new Date(Date.now() - Math.random() * 10000000000).toLocaleDateString()}
                                  </div>
                                </td>
                                <td className="p-4 align-middle text-right">
                                  <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                                    <MoreHorizontal className="h-4 w-4" />
                                  </Button>
                                </td>
                              </tr>
                            ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </TabsContent>

                <TabsContent value="activity" className="space-y-4">
                  <div className="flex justify-between items-center">
                    <h3 className="text-lg font-medium">Recent Activity</h3>
                    <Button variant="outline" size="sm">
                      <Clock className="mr-2 h-4 w-4" />
                      View All
                    </Button>
                  </div>

                  <div className="space-y-4">
                    {[
                      {
                        icon: BookOpen,
                        color: "text-blue-600",
                        bg: "bg-blue-100",
                        text: "Created a new course",
                        time: "2 hours ago",
                      },
                      {
                        icon: MessageSquare,
                        color: "text-green-600",
                        bg: "bg-green-100",
                        text: "Responded to student questions",
                        time: "1 day ago",
                      },
                      {
                        icon: BarChart,
                        color: "text-purple-600",
                        bg: "bg-purple-100",
                        text: "Reviewed course analytics",
                        time: "2 days ago",
                      },
                      {
                        icon: Users,
                        color: "text-amber-600",
                        bg: "bg-amber-100",
                        text: "Hosted a live session with students",
                        time: "3 days ago",
                      },
                      {
                        icon: FileText,
                        color: "text-cyan-600",
                        bg: "bg-cyan-100",
                        text: "Updated course materials",
                        time: "1 week ago",
                      },
                    ].map((activity, index) => (
                      <div key={index} className="flex items-start space-x-3">
                        <div
                          className={`h-8 w-8 rounded-full ${activity.bg} flex items-center justify-center shrink-0`}
                        >
                          <activity.icon className={`h-4 w-4 ${activity.color}`} />
                        </div>
                        <div>
                          <p className="text-sm">{activity.text}</p>
                          <p className="text-xs text-muted-foreground">{activity.time}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </TabsContent>
              </Tabs>
            </CardContent>
          </Card>

          {/* Biography Card - Cyan Theme */}
          <Card className="border-cyan-100">
            <div className="h-2 bg-gradient-to-r from-cyan-400 to-blue-500"></div>
            <CardHeader>
              <CardTitle>Biography</CardTitle>
              <CardDescription>Professional background and expertise</CardDescription>
            </CardHeader>
            <CardContent>
              <p className="text-sm leading-relaxed">
                {instructor.description ||
                  `${instructor.name} is a highly experienced instructor specializing in cognitive development and memory enhancement techniques. With a background in educational psychology and years of practical experience, they have helped thousands of students improve their mental capabilities and learning efficiency.
                  
                  Their teaching methodology combines theoretical knowledge with practical exercises, ensuring students not only understand the concepts but can apply them effectively in real-world scenarios. Known for their engaging teaching style and personalized approach, they consistently receive excellent feedback from students across all age groups.`}
              </p>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}
