"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { Link2, Pencil, Plus, Users as UsersIcon } from "lucide-react"

import { rolesApi } from "@/lib/api/roles"
import { usersApi } from "@/lib/api/users"
import { employeeCrossLinkApi } from "@/lib/api/employees"
import { errorMessage, fieldErrors } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { PaginationMeta } from "@/types/common"
import { Role } from "@/types/rbac"
import { EmployeeMatch } from "@/types/hrm"
import { ManagedUser, UserTypeOption } from "@/types/users"

import { Button, buttonVariants } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"

const PAGE_SIZE = 10

export default function UsersPage() {
  const [users, setUsers] = useState<ManagedUser[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [roles, setRoles] = useState<Role[]>([])
  const [userTypes, setUserTypes] = useState<UserTypeOption[]>([])
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)

  const [open, setOpen] = useState(false)
  const [username, setUsername] = useState("")
  const [fullName, setFullName] = useState("")
  const [email, setEmail] = useState("")
  const [mobileNumber, setMobileNumber] = useState("")
  const [nic, setNic] = useState("")
  const [roleId, setRoleId] = useState<string>("")
  const [userTypeId, setUserTypeId] = useState("")
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  // Advisory cross-link suggestion: does a Staff record already exist with this email?
  const [staffMatch, setStaffMatch] = useState<EmployeeMatch | null>(null)
  const [checkingEmail, setCheckingEmail] = useState(false)

  async function checkEmail(value: string) {
    if (!value.trim()) { setStaffMatch(null); return }
    setCheckingEmail(true)
    try {
      const { match } = await employeeCrossLinkApi.findStaffByEmail(value.trim())
      setStaffMatch(match)
    } catch {
      setStaffMatch(null)
    } finally {
      setCheckingEmail(false)
    }
  }

  function load() {
    usersApi
      .list({ page, pageSize: PAGE_SIZE })
      .then((res) => {
        setUsers(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => setError(errorMessage(err)))
  }

  useEffect(load, [page])

  useEffect(() => {
    rolesApi.list({ pageSize: 200, status: "Active" }).then((res) => setRoles(res.items)).catch(() => setRoles([]))
  }, [])

  useEffect(() => {
    usersApi
      .userTypes()
      .then((types) => {
        setUserTypes(types)
        // Only one user type exists today (AuthHex's "Admin"/"dev" seed) — default to it
        // so the admin never has to pick a raw GUID; the select still lets them switch
        // if more types are added later.
        if (types.length > 0) setUserTypeId((current) => current || types[0].userTypeId)
      })
      .catch(() => setUserTypes([]))
  }, [])

  function resetForm() {
    setUsername("")
    setFullName("")
    setEmail("")
    setMobileNumber("")
    setNic("")
    setRoleId("")
    setUserTypeId("")
    setErrors({})
    setStaffMatch(null)
  }

  async function handleCreate() {
    const nextErrors: Record<string, string> = {}
    if (!username.trim()) nextErrors.username = "Username is required"
    if (!fullName.trim()) nextErrors.fullName = "Full name is required"
    if (!email.trim()) nextErrors.email = "Email is required"
    if (!roleId) nextErrors.roleId = "Role is required"
    if (!userTypeId.trim()) nextErrors.userTypeId = "User type is required"
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

    setSubmitting(true)
    try {
      const result = await usersApi.create({
        username: username.trim(),
        fullName: fullName.trim(),
        email: email.trim(),
        mobileNumber: mobileNumber || null,
        nic: nic || null,
        roleId: Number(roleId),
        userTypeId: userTypeId.trim(),
        linkEmployeeId: staffMatch ? staffMatch.employeeId : null,
      })
      toast.success("User created", `Credentials have been emailed to ${result.username}.`)
      setOpen(false)
      resetForm()
      load()
    } catch (err) {
      const fe = fieldErrors(err)
      if (fe) setErrors(fe)
      toast.error("Could not create user", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Users</h1>
          <p className="text-base text-muted-foreground">
            Create accounts and assign roles. New users receive their credentials by email.
          </p>
        </div>

        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger
            render={
              <Button size="lg">
                <Plus className="size-5" />
                New User
              </Button>
            }
          />
          <DialogContent className="sm:max-w-md">
            <DialogHeader className="items-center text-center">
              <DialogTitle>New user</DialogTitle>
              <DialogDescription>Created in both the auth service and here; password is emailed.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field data-invalid={!!errors.username}>
                <FieldLabel htmlFor="u-username">Username</FieldLabel>
                <Input id="u-username" value={username} onChange={(e) => setUsername(e.target.value)} aria-invalid={!!errors.username} />
                <FieldError errors={[errors.username ? { message: errors.username } : undefined]} />
              </Field>
              <Field data-invalid={!!errors.fullName}>
                <FieldLabel htmlFor="u-fullname">Full name</FieldLabel>
                <Input id="u-fullname" value={fullName} onChange={(e) => setFullName(e.target.value)} aria-invalid={!!errors.fullName} />
                <FieldError errors={[errors.fullName ? { message: errors.fullName } : undefined]} />
              </Field>
              <Field data-invalid={!!errors.email}>
                <FieldLabel htmlFor="u-email">Email</FieldLabel>
                <Input
                  id="u-email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  onBlur={(e) => checkEmail(e.target.value)}
                  aria-invalid={!!errors.email}
                />
                <FieldError errors={[errors.email ? { message: errors.email } : undefined]} />
                {checkingEmail && <p className="text-sm text-muted-foreground">Checking for an existing staff record…</p>}
                {staffMatch && (
                  <div className="flex items-center gap-2 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2 text-sm">
                    <Link2 className="size-4 shrink-0 text-primary" />
                    <span>
                      Staff record <strong>{staffMatch.employeeCode}</strong> ({staffMatch.fullName}) matches this email — it will be linked to this user.
                    </span>
                  </div>
                )}
              </Field>
              <Field>
                <FieldLabel htmlFor="u-mobile">Mobile number (optional)</FieldLabel>
                <Input id="u-mobile" value={mobileNumber} onChange={(e) => setMobileNumber(e.target.value)} />
              </Field>
              <Field>
                <FieldLabel htmlFor="u-nic">NIC (optional)</FieldLabel>
                <Input id="u-nic" value={nic} onChange={(e) => setNic(e.target.value)} />
              </Field>
              <Field data-invalid={!!errors.roleId}>
                <FieldLabel htmlFor="u-role">Role</FieldLabel>
                <Select value={roleId || undefined} onValueChange={(v) => setRoleId(v ?? "")}>
                  <SelectTrigger id="u-role">
                    <SelectValue placeholder="Select a role" />
                  </SelectTrigger>
                  <SelectContent>
                    {roles.map((r) => (
                      <SelectItem key={r.roleId} value={String(r.roleId)}>
                        {r.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FieldError errors={[errors.roleId ? { message: errors.roleId } : undefined]} />
              </Field>
              <Field data-invalid={!!errors.userTypeId}>
                <FieldLabel htmlFor="u-usertype">User type</FieldLabel>
                <Select value={userTypeId || undefined} onValueChange={(v) => setUserTypeId(v ?? "")}>
                  <SelectTrigger id="u-usertype">
                    <SelectValue placeholder="Select a user type" />
                  </SelectTrigger>
                  <SelectContent>
                    {userTypes.map((t) => (
                      <SelectItem key={t.userTypeId} value={t.userTypeId}>
                        {t.code ?? t.userTypeId}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FieldError errors={[errors.userTypeId ? { message: errors.userTypeId } : undefined]} />
              </Field>
            </FieldGroup>
            <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-center">
              <Button variant="outline" className="w-full sm:w-auto sm:min-w-36" onClick={() => setOpen(false)} disabled={submitting}>
                Cancel
              </Button>
              <Button className="w-full sm:w-auto sm:min-w-36" onClick={handleCreate} disabled={submitting}>
                {submitting ? "Creating…" : "Create"}
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {error && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>
      )}

      {!error && users === null && (
        <div className="flex flex-col gap-3">
          {Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full" />
          ))}
        </div>
      )}

      {!error && users !== null && users.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <UsersIcon className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No users yet.</p>
        </div>
      )}

      {!error && users !== null && users.length > 0 && (
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Username</TableHead>
              <TableHead className="h-12 px-3 text-sm">Display name</TableHead>
              <TableHead className="h-12 px-3 text-sm">Role</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {users.map((u) => (
              <TableRow key={u.userId}>
                <TableCell className="px-3 py-3.5 font-medium">{u.username}</TableCell>
                <TableCell className="px-3 py-3.5">{u.displayName}</TableCell>
                <TableCell className="px-3 py-3.5">{u.roleName ?? "—"}</TableCell>
                <TableCell className="px-3 py-3.5">
                  <Badge
                    variant="outline"
                    className={cn(
                      "h-6 w-fit justify-center border-transparent px-2.5 text-sm",
                      u.status === "Active" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground"
                    )}
                  >
                    {u.status}
                  </Badge>
                </TableCell>
                <TableCell className="px-3 py-3.5">
                  <Link
                    href={`/dashboard/settings/users/${u.userId}`}
                    className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }))}
                    aria-label={`Edit ${u.username}`}
                  >
                    <Pencil className="size-4" />
                  </Link>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}

      {pagination && pagination.totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">
            Showing {(pagination.page - 1) * pagination.pageSize + 1}–
            {Math.min(pagination.page * pagination.pageSize, pagination.totalItems)} of {pagination.totalItems}
          </p>
          <div className="flex items-center gap-2">
            <Button type="button" variant="outline" size="sm" disabled={pagination.page <= 1} onClick={() => setPage((p) => Math.max(1, p - 1))}>
              Previous
            </Button>
            <span className="text-sm text-muted-foreground">
              Page {pagination.page} of {pagination.totalPages}
            </span>
            <Button
              type="button"
              variant="outline"
              size="sm"
              disabled={pagination.page >= pagination.totalPages}
              onClick={() => setPage((p) => Math.min(pagination.totalPages, p + 1))}
            >
              Next
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}
