"use client"

import * as React from "react"
import Link from "next/link"
import { useRouter, useSearchParams } from "next/navigation"
import { Search, Users, Upload, MoreHorizontal, Trash2, Pencil, UserCog } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Badge } from "@/shared/components/ui/badge"
import { Card, CardContent } from "@/shared/components/ui/card"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/components/ui/alert-dialog"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { formatDate } from "@/shared/lib/utils"
import { useActionMutation } from "@/shared/hooks/use-action-mutation"
import { useTranslations } from "next-intl"
import {
  UserRoleAssignDialog,
  type AssignableRole,
} from "@/modules/rbac/components/user-role-assign-dialog"
import { deleteUserAction } from "../actions"

interface AdminUserListItem {
  id: string
  name: string | null
  email: string
  roles: string[]
  phone: string | null
  createdAt: Date
}

interface AdminUsersViewProps {
  users: AdminUserListItem[]
  roleOptions: string[]
  page: number
  pageSize: number
  total: number
  totalPages: number
  search: string
  roleFilter: string
  /** All roles (with id/name/isSystem/isEnabled) for the assign dialog. */
  assignableRoles?: AssignableRole[]
}

export function AdminUsersView({
  users,
  roleOptions,
  page,
  pageSize,
  total,
  totalPages,
  search,
  roleFilter,
  assignableRoles,
}: AdminUsersViewProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const t = useTranslations("users")
  const [searchInput, setSearchInput] = React.useState(search)
  const [deleteUserId, setDeleteUserId] = React.useState<string | null>(null)
  const [assignTarget, setAssignTarget] = React.useState<AdminUserListItem | null>(null)

  const deleteMutation = useActionMutation({
    successMessage: t("messages.deleted"),
    onSuccess: () => {
      setDeleteUserId(null)
      router.refresh()
    },
  })

  const updateParams = React.useCallback(
    (updates: Record<string, string | undefined>) => {
      const params = new URLSearchParams(searchParams.toString())
      for (const [key, value] of Object.entries(updates)) {
        if (value === undefined || value === "") {
          params.delete(key)
        } else {
          params.set(key, value)
        }
      }
      // 重置搜索条件时重置页码
      if (updates.search !== undefined || updates.role !== undefined) {
        params.delete("page")
      }
      router.push(`/admin/users?${params.toString()}`)
    },
    [router, searchParams]
  )

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault()
    updateParams({ search: searchInput, page: undefined })
  }

  const handleDelete = (): void => {
    if (!deleteUserId) return
    void deleteMutation.mutate(() => deleteUserAction(deleteUserId))
  }

  const start = total === 0 ? 0 : (page - 1) * pageSize + 1
  const end = Math.min(page * pageSize, total)

  return (
    <div className="flex h-full flex-col space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">{t("title")}</h2>
          <p className="text-muted-foreground">{t("adminDescription")}</p>
        </div>
        <Button asChild>
          <Link href="/admin/users/import">
            <Upload className="mr-2 h-4 w-4" />
            {t("importButton")}
          </Link>
        </Button>
      </div>

      <Card className="shadow-none">
        <CardContent className="pt-6">
          <form onSubmit={handleSearch} className="flex flex-col gap-3 md:flex-row md:items-center">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder={t("searchPlaceholder")}
                value={searchInput}
                onChange={(e) => setSearchInput(e.target.value)}
                className="pl-9"
              />
            </div>
            <Select
              value={roleFilter || "all"}
              onValueChange={(v) => updateParams({ role: v === "all" ? undefined : v, page: undefined })}
            >
              <SelectTrigger className="w-full md:w-48">
                <SelectValue placeholder={t("allRoles")} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">{t("allRoles")}</SelectItem>
                {roleOptions.map((r) => (
                  <SelectItem key={r} value={r}>
                    {r}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Button type="submit">{t("search")}</Button>
            {(search || roleFilter) && (
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  setSearchInput("")
                  updateParams({ search: undefined, role: undefined, page: undefined })
                }}
              >
                {t("reset")}
              </Button>
            )}
          </form>
        </CardContent>
      </Card>

      <Card className="shadow-none">
        <CardContent className="pt-6">
          {users.length === 0 ? (
            <EmptyState
              icon={Users}
              title={t("emptyTitle")}
              description={search || roleFilter ? t("emptyFilteredDescription") : t("emptyDescription")}
            />
          ) : (
            <>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>{t("columns.name")}</TableHead>
                      <TableHead>{t("columns.email")}</TableHead>
                      <TableHead>{t("columns.role")}</TableHead>
                      <TableHead>{t("columns.phone")}</TableHead>
                      <TableHead>{t("columns.createdAt")}</TableHead>
                      <TableHead className="w-[60px]">{t("columns.actions")}</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {users.map((u) => (
                      <TableRow key={u.id}>
                        <TableCell className="font-medium">{u.name || "-"}</TableCell>
                        <TableCell className="text-muted-foreground">{u.email}</TableCell>
                        <TableCell>
                          <div className="flex flex-wrap gap-1">
                            {u.roles.length === 0 ? (
                              <Badge variant="secondary">{t("unassigned")}</Badge>
                            ) : (
                              u.roles.map((r) => (
                                <Badge key={r} variant="secondary">{r}</Badge>
                              ))
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="text-muted-foreground">{u.phone || "-"}</TableCell>
                        <TableCell className="text-muted-foreground">{formatDate(u.createdAt)}</TableCell>
                        <TableCell>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon">
                                <MoreHorizontal className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem>
                                <Pencil className="mr-2 h-4 w-4" />
                                {t("actions.edit")}
                              </DropdownMenuItem>
                              {assignableRoles && (
                                <DropdownMenuItem onClick={() => setAssignTarget(u)}>
                                  <UserCog className="mr-2 h-4 w-4" />
                                  {t("actions.assignRoles")}
                                </DropdownMenuItem>
                              )}
                              <DropdownMenuItem
                                className="text-destructive"
                                onClick={() => setDeleteUserId(u.id)}
                              >
                                <Trash2 className="mr-2 h-4 w-4" />
                                {t("actions.delete")}
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              <div className="flex items-center justify-between pt-4">
                <p className="text-sm text-muted-foreground">
                  {t("pagination.info", { start, end, total })}
                </p>
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={page <= 1}
                    onClick={() => updateParams({ page: String(page - 1) })}
                  >
                    {t("pagination.prev")}
                  </Button>
                  <span className="text-sm text-muted-foreground">
                    {t("pagination.pageInfo", { page, totalPages })}
                  </span>
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={page >= totalPages}
                    onClick={() => updateParams({ page: String(page + 1) })}
                  >
                    {t("pagination.next")}
                  </Button>
                </div>
              </div>
            </>
          )}
        </CardContent>
      </Card>

      <AlertDialog open={!!deleteUserId} onOpenChange={(v) => !v && setDeleteUserId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("deleteConfirmTitle")}</AlertDialogTitle>
            <AlertDialogDescription>
              {t("deleteConfirmDescription")}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={deleteMutation.isWorking}>{t("actions.cancel")}</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={deleteMutation.isWorking}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {deleteMutation.isWorking ? t("actions.deleting") : t("actions.confirmDelete")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {assignableRoles && assignTarget && (
        <UserRoleAssignDialog
          open={true}
          onOpenChange={(v) => !v && setAssignTarget(null)}
          userId={assignTarget.id}
          userName={assignTarget.name ?? ""}
          userEmail={assignTarget.email}
          allRoles={assignableRoles}
          currentRoleNames={assignTarget.roles}
        />
      )}
    </div>
  )
}
