"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { ArrowLeft, Save } from "lucide-react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Checkbox } from "@/components/ui/checkbox"

import { getUserById, updateUser } from "@/services/users/query"
import { getRoles } from "@/services/roles/query"
import { getUserRoles, assignRoleToUser, removeRoleFromUser } from "@/services/role_users/query"

export default function EditUserPage({ 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 [allRoles, setAllRoles] = useState<any[]>([])

  const [formData, setFormData] = useState({
    name: "",
    email: "",
    status: "active",
    avatar: "",
    selectedRoles: [] as number[],
  })

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        setIsLoading(true)

        // Fetch user and roles
        const [fetchedUser, fetchedRoles, fetchedUserRoles] = await Promise.all([
          getUserById(userId),
          getRoles(),
          getUserRoles(userId),
        ])

        if (!fetchedUser) {
          router.push("/admin/users")
          return
        }

        setFormData({
          name: fetchedUser.name || "",
          email: fetchedUser.email || "",
          status: fetchedUser.status || "active",
          avatar: fetchedUser.avatar || "",
          selectedRoles: Array.isArray(fetchedUserRoles) ? fetchedUserRoles.map((role) => role.id) : [],
        })

        setAllRoles(Array.isArray(fetchedRoles) ? fetchedRoles : [])

        console.log("[user-edit][data]", {
          user: fetchedUser,
          roles: fetchedRoles,
          userRoles: fetchedUserRoles,
        })
      } catch (error) {
        console.error("[user-edit][error]", error)
        setError("Failed to load user data")
      } finally {
        setIsLoading(false)
      }
    }

    fetchUserData()
  }, [userId, router])

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData((prev) => ({ ...prev, [name]: value }))
  }

  const handleStatusChange = (value: string) => {
    setFormData((prev) => ({ ...prev, status: value }))
  }

  const handleRoleToggle = (roleId: number) => {
    setFormData((prev) => {
      const selectedRoles = [...prev.selectedRoles]

      if (selectedRoles.includes(roleId)) {
        return {
          ...prev,
          selectedRoles: selectedRoles.filter((id) => id !== roleId),
        }
      } else {
        return {
          ...prev,
          selectedRoles: [...selectedRoles, roleId],
        }
      }
    })
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    try {
      setIsLoading(true)

      // Update the user
      await updateUser(userId, {
        name: formData.name,
        email: formData.email,
        status: formData.status,
        avatar: formData.avatar,
      })

      // Get current user roles
      const currentRoles = await getUserRoles(userId)
      const currentRoleIds = Array.isArray(currentRoles) ? currentRoles.map((role) => role.id) : []

      // Remove roles that are no longer selected
      const rolesToRemove = currentRoleIds.filter((roleId) => !formData.selectedRoles.includes(roleId))
      const rolesToAdd = formData.selectedRoles.filter((roleId) => !currentRoleIds.includes(roleId))

      // Execute role changes
      await Promise.all([
        ...rolesToRemove.map((roleId) => removeRoleFromUser(userId, roleId)),
        ...rolesToAdd.map((roleId) => assignRoleToUser(userId, roleId)),
      ])

      // Redirect to the user detail page
      router.push(`/admin/users/${userId}`)
    } catch (error) {
      console.error("[user-edit][submit-error]", error)
      setError("Failed to update user")
    } finally {
      setIsLoading(false)
    }
  }

  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>
    )
  }

  return (
    <div>
      <div className="mb-6">
        <Button variant="ghost" className="mb-4" onClick={() => router.push(`/admin/users/${userId}`)}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          Back to User
        </Button>
        <h1 className="text-3xl font-bold font-heading mb-2">Edit User</h1>
        <p className="text-gray-600">Update user information and roles</p>
      </div>

      <form onSubmit={handleSubmit}>
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
          {/* User Information */}
          <Card className="border-0 bg-white lg:col-span-2">
            <CardHeader className="pb-2">
              <CardTitle className="text-xl font-heading">User Information</CardTitle>
              <CardDescription>Update the basic information for this user</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor="name">Full Name</Label>
                    <Input
                      id="name"
                      name="name"
                      placeholder="Enter full name"
                      value={formData.name}
                      onChange={handleInputChange}
                      required
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="email">Email Address</Label>
                    <Input
                      id="email"
                      name="email"
                      type="email"
                      placeholder="Enter email address"
                      value={formData.email}
                      onChange={handleInputChange}
                      required
                    />
                  </div>
                </div>

                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor="status">Status</Label>
                    <Select value={formData.status} onValueChange={handleStatusChange}>
                      <SelectTrigger id="status">
                        <SelectValue placeholder="Select status" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="active">Active</SelectItem>
                        <SelectItem value="inactive">Inactive</SelectItem>
                        <SelectItem value="pending">Pending</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Role Assignment */}
          <Card className="border-0 bg-white">
            <CardHeader className="pb-2">
              <CardTitle className="text-xl font-heading">Role Assignment</CardTitle>
              <CardDescription>Update roles for this user</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {allRoles.map((role) => (
                  <div key={role.id} className="flex items-center space-x-2">
                    <Checkbox
                      id={`role-${role.id}`}
                      checked={formData.selectedRoles.includes(role.id)}
                      onCheckedChange={() => handleRoleToggle(role.id)}
                    />
                    <Label htmlFor={`role-${role.id}`} className="font-medium">
                      {role.display_name}
                    </Label>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Form Actions */}
        <div className="flex justify-end gap-4">
          <Button type="button" variant="outline" onClick={() => router.push(`/admin/users/${userId}`)}>
            Cancel
          </Button>
          <Button type="submit" disabled={isLoading}>
            <Save className="h-4 w-4 mr-2" />
            {isLoading ? "Saving..." : "Save Changes"}
          </Button>
        </div>
      </form>
    </div>
  )
}
