"use client"

import { useRouter } from "next/navigation"
import { Shield } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/components/ui/dialog"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import { useActionMutation } from "@/shared/hooks/use-action-mutation"
import { useTranslations } from "next-intl"

import { createRoleAction, updateRoleAction } from "../actions"
import type { RoleRecord } from "../types"

interface RoleFormDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  /** When provided, the dialog is in edit mode. */
  editRole?: RoleRecord | null
}

/**
 * Create or edit a role. In edit mode for the `admin` role, the name field is
 * disabled (admin role name is locked).
 */
export function RoleFormDialog({ open, onOpenChange, editRole }: RoleFormDialogProps) {
  const router = useRouter()
  const t = useTranslations("rbac")
  const isEdit = Boolean(editRole)
  const isAdmin = editRole?.name === "admin"

  const createMutation = useActionMutation({
    successMessage: t("messages.created"),
    onSuccess: () => {
      onOpenChange(false)
      router.refresh()
    },
  })

  const updateMutation = useActionMutation({
    successMessage: t("messages.updated"),
    onSuccess: () => {
      onOpenChange(false)
      router.refresh()
    },
  })

  const isWorking = createMutation.isWorking || updateMutation.isWorking

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>): void => {
    e.preventDefault()
    const formData = new FormData(e.currentTarget)

    if (isEdit && editRole) {
      void updateMutation.mutate(() => updateRoleAction(editRole.id, undefined, formData))
    } else {
      void createMutation.mutate(() => createRoleAction(undefined, formData))
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5" />
            {isEdit
              ? t("roles.editRoleTitle", { name: editRole?.name ?? "" })
              : t("roles.createTitle")}
          </DialogTitle>
          <DialogDescription>
            {isEdit ? t("roles.editDescription") : t("roles.createDescription")}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="role-name">{t("roles.name")}</Label>
            <Input
              id="role-name"
              name="name"
              defaultValue={editRole?.name ?? ""}
              placeholder={t("roles.namePlaceholder")}
              disabled={isAdmin || isWorking}
              required
              minLength={2}
              maxLength={50}
              pattern="^[a-z0-9_]+$"
              title={t("roles.namePatternTitle")}
            />
            {isAdmin && (
              <p className="text-xs text-muted-foreground">
                {t("roles.adminNameLocked")}
              </p>
            )}
          </div>
          <div className="space-y-2">
            <Label htmlFor="role-description">{t("roles.descriptionLabel")}</Label>
            <Textarea
              id="role-description"
              name="description"
              defaultValue={editRole?.description ?? ""}
              placeholder={t("roles.descriptionPlaceholder")}
              disabled={isWorking}
              maxLength={255}
              rows={3}
            />
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={isWorking}
            >
              {t("actions.cancel")}
            </Button>
            <Button type="submit" disabled={isWorking}>
              {isWorking
                ? t("actions.saving")
                : isEdit
                  ? t("actions.save")
                  : t("roles.create")}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
