"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { Plus, Pencil, Trash2 } from "lucide-react"
import { Modal } from "@/components/ui/modal"
import { Button } from "@/components/ui/button"
import { Field, FormError, TextInput, Textarea } from "@/components/ui/form"
import { createRole, updateRole, deleteRole } from "@/app/(admin)/roles/actions"
import i18n from "@/lib/i18n";

type Role = {
  id: string
  code: string
  name: string
  description: string | null
  user_count: number | null
}

export function CreateRoleButton() {
  const [open, setOpen] = React.useState(false)
  const [pending, setPending] = React.useState(false)
  const [error, setError] = React.useState<string | null>(null)
  const router = useRouter()

  return (
    <>
      <Button type="button" onClick={() => setOpen(true)}>
        <Plus className="h-4 w-4" />
        {i18n.t('components.admin.role-editor.text_19')}</Button>
      <Modal
        open={open}
        onClose={() => setOpen(false)}
        title={i18n.t('components.admin.role-editor.text_1')}
        description={i18n.t('components.admin.role-editor.text_2')}
        size="md"
      >
        <form
          action={async (fd) => {
            setPending(true)
            setError(null)
            const res = await createRole(fd)
            setPending(false)
            if (!res.ok) return setError(res.error)
            setOpen(false)
            router.refresh()
          }}
          className="space-y-4"
        >
          <Field label={i18n.t('components.admin.role-editor.text_3')} htmlFor="code" required hint={i18n.t('components.admin.role-editor.text_4')}>
            <TextInput id="code" name="code" placeholder="treasury_lead" required />
          </Field>
          <Field label={i18n.t('components.admin.role-editor.text_5')} htmlFor="name" required>
            <TextInput id="name" name="name" placeholder={i18n.t('components.admin.role-editor.text_6')} required />
          </Field>
          <Field label={i18n.t('components.admin.role-editor.text_7')} htmlFor="description">
            <Textarea id="description" name="description" placeholder={i18n.t('components.admin.role-editor.text_8')} />
          </Field>
          <FormError message={error} />
          <div className="flex items-center justify-start gap-2 pt-2">
            <Button type="submit" disabled={pending}>
              {pending ? i18n.t('components.admin.role-editor.text_9') : i18n.t('components.admin.role-editor.text_10')}
            </Button>
            <Button type="button" variant="outline" onClick={() => setOpen(false)} disabled={pending}>
              {i18n.t('components.admin.role-editor.text_20')}</Button>
          </div>
        </form>
      </Modal>
    </>
  )
}

export function EditRoleButton({ role }: { role: Role }) {
  const [open, setOpen] = React.useState(false)
  const [pending, setPending] = React.useState(false)
  const [error, setError] = React.useState<string | null>(null)
  const router = useRouter()

  const isSuperAdmin = role.code === "super_admin"

  return (
    <>
      <Button type="button" variant="outline" size="sm" onClick={() => setOpen(true)}>
        <Pencil className="h-3.5 w-3.5" />
        {i18n.t('components.admin.role-editor.text_21')}</Button>
      <Modal
        open={open}
        onClose={() => setOpen(false)}
        title={i18n.t('components.admin.role-editor.text_edit', { name: role.name })}
        size="md"
      >
        <form
          action={async (fd) => {
            setPending(true)
            setError(null)
            const res = await updateRole(fd)
            setPending(false)
            if (!res.ok) return setError(res.error)
            setOpen(false)
            router.refresh()
          }}
          className="space-y-4"
        >
          <input type="hidden" name="id" value={role.id} />
          <Field label={i18n.t('components.admin.role-editor.text_11')}>
            <TextInput value={role.code} disabled />
          </Field>
          <Field label={i18n.t('components.admin.role-editor.text_12')} htmlFor="name" required>
            <TextInput id="name" name="name" defaultValue={role.name} required disabled={isSuperAdmin} />
          </Field>
          <Field label={i18n.t('components.admin.role-editor.text_13')} htmlFor="description">
            <Textarea
              id="description"
              name="description"
              defaultValue={role.description ?? ""}
              disabled={isSuperAdmin}
            />
          </Field>
          {isSuperAdmin ? (
            <FormError message={i18n.t('components.admin.role-editor.text_14')} />
          ) : (
            <FormError message={error} />
          )}
          <div className="flex items-center justify-start gap-2 pt-2">
            <Button type="submit" disabled={pending || isSuperAdmin}>
              {pending ? i18n.t('components.admin.role-editor.text_15') : i18n.t('components.admin.role-editor.text_16')}
            </Button>
            <Button type="button" variant="outline" onClick={() => setOpen(false)} disabled={pending}>
              {i18n.t('components.admin.role-editor.text_22')}</Button>
          </div>
        </form>
      </Modal>
    </>
  )
}

export function DeleteRoleButton({ role }: { role: Role }) {
  const [open, setOpen] = React.useState(false)
  const [pending, setPending] = React.useState(false)
  const [error, setError] = React.useState<string | null>(null)
  const router = useRouter()

  const isSuperAdmin = role.code === "super_admin"
  const hasUsers = (role.user_count ?? 0) > 0

  return (
    <>
      <Button
        type="button"
        variant="ghost"
        size="sm"
        onClick={() => setOpen(true)}
        disabled={isSuperAdmin}
        className="text-destructive hover:bg-destructive/10"
      >
        <Trash2 className="h-3.5 w-3.5" />
        {i18n.t('components.admin.role-editor.text_23')}</Button>
      <Modal
        open={open}
        onClose={() => setOpen(false)}
        title={i18n.t('components.admin.role-editor.text_delete', { name: role.name })}
        size="sm"
      >
        <form
          action={async (fd) => {
            setPending(true)
            setError(null)
            const res = await deleteRole(fd)
            setPending(false)
            if (!res.ok) return setError(res.error)
            setOpen(false)
            router.refresh()
          }}
          className="space-y-4"
        >
          <input type="hidden" name="id" value={role.id} />
          <p className="text-sm text-muted-foreground">
            {i18n.t('components.admin.role-editor.text_24')}<span className="font-medium text-foreground">{role.name}</span>{i18n.t('components.admin.role-editor.text_25')}</p>
          {hasUsers ? (
            <FormError message={i18n.t('components.admin.role-editor.text_linked', { count: role.user_count })} />
          ) : null}
          <FormError message={error} />
          <div className="flex items-center justify-start gap-2 pt-2">
            <Button type="submit" variant="danger" disabled={pending || hasUsers}>
              {pending ? i18n.t('components.admin.role-editor.text_17') : i18n.t('components.admin.role-editor.text_18')}
            </Button>
            <Button type="button" variant="outline" onClick={() => setOpen(false)} disabled={pending}>
              {i18n.t('components.admin.role-editor.text_26')}</Button>
          </div>
        </form>
      </Modal>
    </>
  )
}
