"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import Image from "next/image"
import { ArrowLeft, Mail, Calendar, Clock, CheckCircle2, XCircle, Edit, Trash2, Plus, X, Save } from "lucide-react"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"

import { getUserById } from "@/services/users/query"
import { getUserRoles, assignRoleToUser, removeRoleFromUser } from "@/services/role_users/query"
import { getRoles } from "@/services/roles/query"

export default function UserDetailPage({ params }: { params: { id: string } }) {
  const router = useRouter()
  const userId = Number.parseInt(params.id)

  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [user, setUser] = useState<any>(null)
  const [userRoles, setUserRoles] = useState<any[]>([])
  const [allRoles, setAllRoles] = useState<any[]>([])
  const [isRoleModalOpen, setIsRoleModalOpen] = useState(false)
  const [selectedRole, setSelectedRole] = useState<string>("")
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        setIsLoading(true)

        // Fetch user data
        const fetchedUser = await getUserById(userId)
        if (!fetchedUser) {
          router.push("/admin/users")
          return
        }

        // Fetch user roles and all roles
        const [fetchedUserRoles, fetchedAllRoles] = await Promise.all([getUserRoles(userId), getRoles()])

        setUser(fetchedUser)
        setUserRoles(Array.isArray(fetchedUserRoles) ? fetchedUserRoles : [])
        setAllRoles(Array.isArray(fetchedAllRoles) ? fetchedAllRoles : [])

        console.log("[user-detail][data]", {
          user: fetchedUser,
          userRoles: fetchedUserRoles,
          allRoles: fetchedAllRoles,
        })
      } catch (error) {
        console.error("[user-detail][error]", error)
        setError("Failed to load user data")
      } finally {
        setIsLoading(false)
      }
    }

    fetchUserData()
  }, [userId, router])

  const handleAddRole = async () => {
    if (!selectedRole) return

    try {
      const roleId = Number.parseInt(selectedRole)
      await assignRoleToUser(userId, roleId)
      const updatedRoles = await getUserRoles(userId)
      setUserRoles(Array.isArray(updatedRoles) ? updatedRoles : [])
      setIsRoleModalOpen(false)
      setSelectedRole("")
    } catch (error) {
      console.error("[user-detail][add-role-error]", error)
    }
  }

  const handleRemoveRole = async (roleId: number) => {
    try {
      await removeRoleFromUser(userId, roleId)
      const updatedRoles = await getUserRoles(userId)
      setUserRoles(Array.isArray(updatedRoles) ? updatedRoles : [])
    } catch (error) {
      console.error("[user-detail][remove-role-error]", error)
    }
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "active":
        return (
          <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
            <CheckCircle2 className="h-3 w-3 mr-1" />
            Active
          </Badge>
        )
      case "inactive":
        return (
          <Badge variant="outline" className="bg-red-50 text-red-700 border-red-200">
            <XCircle className="h-3 w-3 mr-1" />
            Inactive
          </Badge>
        )
      default:
        return null
    }
  }

  const getRoleBadge = (role: any) => {
    let badgeClass = ""

    switch (role.name) {
      case "admin":
        badgeClass = "bg-purple-50 text-purple-700 border-purple-200"
        break
      case "instructor":
        badgeClass = "bg-blue-50 text-blue-700 border-blue-200"
        break
      case "student":
        badgeClass = "bg-primary-light text-secondary border-primary-light"
        break
      default:
        badgeClass = "bg-gray-50 text-gray-700 border-gray-200"
    }

    return badgeClass
  }

  if (isLoading) {
    return (
      <div className="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-primary mx-auto mb-4"></div>
          <p className="text-gray-600">Loading user data...</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <p className="text-red-600 mb-4">{error}</p>
          <Button onClick={() => window.location.reload()}>Retry</Button>
        </div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <p className="text-gray-600 mb-4">User not found</p>
          <Button onClick={() => router.push("/admin/users")}>Back to Users</Button>
        </div>
      </div>
    )
  }

  return (
    <div>
      <div className="mb-6">
        <Button variant="ghost" className="mb-4" onClick={() => router.push("/admin/users")}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          Back to Users
        </Button>
        <h1 className="text-3xl font-bold font-heading mb-2">{user.name}</h1>
        <div className="flex items-center gap-2">
          {getStatusBadge(user.status)}
          <p className="text-gray-600">User ID: {user.id}</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
        {/* User Profile Card */}
        <Card className="border-0 bg-white">
          <CardHeader className="pb-2">
            <CardTitle className="text-xl font-heading">Profile</CardTitle>
            <CardDescription>User information and details</CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col items-center text-center">
            <div className="relative h-32 w-32 rounded-full overflow-hidden mb-4">
              <Image src={user.avatar || "/placeholder.svg"} alt={user.name} fill className="object-cover" />
            </div>
            <h3 className="text-xl font-bold mb-1">{user.name}</h3>
            <div className="flex items-center text-gray-600 mb-4">
              <Mail className="h-4 w-4 mr-1" />
              {user.email}
            </div>
            <div className="w-full space-y-2 text-left">
              <div className="flex justify-between py-2 border-b border-gray-100">
                <span className="text-gray-600">Status</span>
                <span>{getStatusBadge(user.status)}</span>
              </div>
              <div className="flex justify-between py-2 border-b border-gray-100">
                <span className="text-gray-600">Created</span>
                <span className="flex items-center">
                  <Calendar className="h-4 w-4 mr-1 text-gray-500" />
                  {new Date(user.created_at).toLocaleDateString()}
                </span>
              </div>
              <div className="flex justify-between py-2 border-b border-gray-100">
                <span className="text-gray-600">Last Updated</span>
                <span className="flex items-center">
                  <Clock className="h-4 w-4 mr-1 text-gray-500" />
                  {new Date(user.updated_at).toLocaleDateString()}
                </span>
              </div>
            </div>
          </CardContent>
          <CardFooter className="flex justify-between">
            <Button variant="outline" className="w-full mr-2">
              <Edit className="h-4 w-4 mr-2" />
              Edit Profile
            </Button>
            <Dialog open={isDeleteModalOpen} onOpenChange={setIsDeleteModalOpen}>
              <DialogTrigger asChild>
                <Button variant="destructive" className="w-full">
                  <Trash2 className="h-4 w-4 mr-2" />
                  Delete User
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Delete User</DialogTitle>
                  <DialogDescription>
                    Are you sure you want to delete this user? This action cannot be undone.
                  </DialogDescription>
                </DialogHeader>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setIsDeleteModalOpen(false)}>
                    Cancel
                  </Button>
                  <Button variant="destructive" onClick={() => router.push("/admin/users")}>
                    Delete User
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </CardFooter>
        </Card>

        {/* Role Management Card */}
        <Card className="border-0 bg-white">
          <CardHeader className="pb-2">
            <div className="flex justify-between items-start">
              <div>
                <CardTitle className="text-xl font-heading">Roles</CardTitle>
                <CardDescription>Manage user roles and permissions</CardDescription>
              </div>
              <Dialog open={isRoleModalOpen} onOpenChange={setIsRoleModalOpen}>
                <DialogTrigger asChild>
                  <Button size="sm">
                    <Plus className="h-4 w-4 mr-2" />
                    Assign Role
                  </Button>
                </DialogTrigger>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>Assign Role</DialogTitle>
                    <DialogDescription>Select a role to assign to this user.</DialogDescription>
                  </DialogHeader>
                  <div className="py-4">
                    <Select value={selectedRole} onValueChange={setSelectedRole}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select a role" />
                      </SelectTrigger>
                      <SelectContent>
                        {allRoles
                          .filter((role) => !userRoles.some((userRole) => userRole.id === role.id))
                          .map((role) => (
                            <SelectItem key={role.id} value={role.id.toString()}>
                              {role.display_name}
                            </SelectItem>
                          ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <DialogFooter>
                    <Button variant="outline" onClick={() => setIsRoleModalOpen(false)}>
                      Cancel
                    </Button>
                    <Button onClick={handleAddRole}>Assign Role</Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {userRoles.length === 0 ? (
                <div className="text-center py-8 text-gray-500">No roles assigned to this user</div>
              ) : (
                userRoles.map((role) => (
                  <div
                    key={role.id}
                    className={`flex items-center justify-between p-3 rounded-md ${getRoleBadge(role)}`}
                  >
                    <div>
                      <h4 className="font-medium">{role.display_name}</h4>
                      <p className="text-xs">{role.description}</p>
                    </div>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8 text-gray-500 hover:text-red-600"
                      onClick={() => handleRemoveRole(role.id)}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>

        {/* Activity Card */}
        <Card className="border-0 bg-white">
          <CardHeader className="pb-2">
            <CardTitle className="text-xl font-heading">Recent Activity</CardTitle>
            <CardDescription>User's recent actions and events</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="text-center py-8 text-gray-500">No recent activity to display</div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Tabs for Additional Information */}
      <Tabs defaultValue="details" className="mb-6">
        <TabsList className="bg-gray-100">
          <TabsTrigger value="details">User Details</TabsTrigger>
          <TabsTrigger value="security">Security</TabsTrigger>
          <TabsTrigger value="logs">Audit Logs</TabsTrigger>
        </TabsList>

        <TabsContent value="details" className="mt-6">
          <Card className="border-0 bg-white">
            <CardHeader>
              <CardTitle className="text-xl font-heading">Additional Details</CardTitle>
              <CardDescription>Extended user information</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div>
                    <h3 className="text-sm font-medium text-gray-500 mb-1">Contact Information</h3>
                    <div className="space-y-2">
                      <div className="flex justify-between py-2 border-b border-gray-100">
                        <span className="text-gray-600">Email</span>
                        <span>{user.email}</span>
                      </div>
                      <div className="flex justify-between py-2 border-b border-gray-100">
                        <span className="text-gray-600">Phone</span>
                        <span>Not provided</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="space-y-4">
                  <div>
                    <h3 className="text-sm font-medium text-gray-500 mb-1">Account Information</h3>
                    <div className="space-y-2">
                      <div className="flex justify-between py-2 border-b border-gray-100">
                        <span className="text-gray-600">User ID</span>
                        <span>{user.id}</span>
                      </div>
                      <div className="flex justify-between py-2 border-b border-gray-100">
                        <span className="text-gray-600">Created</span>
                        <span>{new Date(user.created_at).toLocaleDateString()}</span>
                      </div>
                      <div className="flex justify-between py-2 border-b border-gray-100">
                        <span className="text-gray-600">Last Updated</span>
                        <span>{new Date(user.updated_at).toLocaleDateString()}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
            <CardFooter>
              <Button variant="outline" className="ml-auto">
                <Save className="h-4 w-4 mr-2" />
                Save Changes
              </Button>
            </CardFooter>
          </Card>
        </TabsContent>

        <TabsContent value="security" className="mt-6">
          <Card className="border-0 bg-white">
            <CardHeader>
              <CardTitle className="text-xl font-heading">Security Settings</CardTitle>
              <CardDescription>Manage user security and access</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-6">
                <div>
                  <h3 className="text-sm font-medium text-gray-500 mb-3">Password Management</h3>
                  <Button>Reset Password</Button>
                </div>
                <div>
                  <h3 className="text-sm font-medium text-gray-500 mb-3">Account Status</h3>
                  <div className="flex items-center gap-4">
                    <Button variant={user.status === "active" ? "outline" : "default"}>Activate Account</Button>
                    <Button variant={user.status === "inactive" ? "outline" : "destructive"}>Deactivate Account</Button>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="logs" className="mt-6">
          <Card className="border-0 bg-white">
            <CardHeader>
              <CardTitle className="text-xl font-heading">Audit Logs</CardTitle>
              <CardDescription>User activity and system logs</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="text-center py-8 text-gray-500">No audit logs available for this user</div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
