"use client"

import type React from "react"

import { useState } 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 { createUser } from "@/services/users/query"
import { getRoles } from "@/services/roles/query"
import { assignRoleToUser } from "@/services/role_users/query"

export default function AddUserPage() {
  const router = useRouter()
  const roles = getRoles()

  const [formData, setFormData] = useState({
    name: "",
    email: "",
    status: "active",
    avatar: "/placeholder.svg?key=drpqs",
    selectedRoles: [] as number[],
    sendWelcomeEmail: true,
  })

  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 = (e: React.FormEvent) => {
    e.preventDefault()

    // Create the user
    const newUser = createUser({
      name: formData.name,
      email: formData.email,
      status: formData.status,
      avatar: formData.avatar,
    })

    // Assign roles
    formData.selectedRoles.forEach((roleId) => {
      assignRoleToUser(newUser.id, roleId)
    })

    // Redirect to the user detail page
    router.push(`/admin/users/${newUser.id}`)
  }

  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">Add New User</h1>
        <p className="text-gray-600">Create a new user account</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>Enter the basic information for the new 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 className="flex items-center space-x-2 pt-4">
                    <Checkbox
                      id="sendWelcomeEmail"
                      checked={formData.sendWelcomeEmail}
                      onCheckedChange={(checked) =>
                        setFormData((prev) => ({
                          ...prev,
                          sendWelcomeEmail: checked as boolean,
                        }))
                      }
                    />
                    <Label htmlFor="sendWelcomeEmail">Send welcome email with login instructions</Label>
                  </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>Assign roles to the new user</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {roles.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")}>
            Cancel
          </Button>
          <Button type="submit">
            <Save className="h-4 w-4 mr-2" />
            Create User
          </Button>
        </div>
      </form>
    </div>
  )
}
