"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { Pencil, ShieldOff, ShieldCheck } from "lucide-react"
import { Modal } from "@/components/ui/modal"
import { Button } from "@/components/ui/button"
import { Field, FormError, Select, TextInput } from "@/components/ui/form"
import { setAdminUserStatus, updateAdminUser } from "@/app/(admin)/roles/actions"
import i18n from "@/lib/i18n";

type AdminUser = {
  id: string
  email: string | null
  full_name: string | null
  role: string
  status: string
}

const ROLE_OPTIONS = [
  { value: "super_admin", label: i18n.t('components.admin.user-editor.text_1') },
  { value: "operations", label: i18n.t('components.admin.user-editor.text_2') },
  { value: "compliance", label: i18n.t('components.admin.user-editor.text_3') },
  { value: "finance", label: i18n.t('components.admin.user-editor.text_4') },
  { value: "support", label: i18n.t('components.admin.user-editor.text_5') },
]

const STATUS_OPTIONS = [
  { value: "active", label: i18n.t('components.admin.user-editor.text_6') },
  { value: "suspended", label: i18n.t('components.admin.user-editor.text_7') },
  { value: "invited", label: i18n.t('components.admin.user-editor.text_8') },
]

export function EditUserButton({ user }: { user: AdminUser }) {
  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" variant="outline" size="sm" onClick={() => setOpen(true)}>
        <Pencil className="h-3.5 w-3.5" />
        {i18n.t('components.admin.user-editor.text_16')}</Button>
      <Modal
        open={open}
        onClose={() => setOpen(false)}
        title={i18n.t('components.admin.user-editor.text_9')}
        description={user.email ?? ""}
        size="md"
      >
        <form
          action={async (fd) => {
            setPending(true)
            setError(null)
            const res = await updateAdminUser(fd)
            setPending(false)
            if (!res.ok) return setError(res.error)
            setOpen(false)
            router.refresh()
          }}
          className="space-y-4"
        >
          <input type="hidden" name="id" value={user.id} />
          <Field label={i18n.t('components.admin.user-editor.text_10')}>
            <TextInput value={user.email ?? ""} disabled />
          </Field>
          <Field label={i18n.t('components.admin.user-editor.text_11')} htmlFor="full_name">
            <TextInput id="full_name" name="full_name" defaultValue={user.full_name ?? ""} />
          </Field>
          <div className="grid grid-cols-2 gap-4">
            <Field label={i18n.t('components.admin.user-editor.text_12')} htmlFor="role" required>
              <Select id="role" name="role" defaultValue={user.role}>
                {ROLE_OPTIONS.map((r) => (
                  <option key={r.value} value={r.value}>
                    {r.label}
                  </option>
                ))}
              </Select>
            </Field>
            <Field label={i18n.t('components.admin.user-editor.text_13')} htmlFor="status" required>
              <Select id="status" name="status" defaultValue={user.status}>
                {STATUS_OPTIONS.map((s) => (
                  <option key={s.value} value={s.value}>
                    {s.label}
                  </option>
                ))}
              </Select>
            </Field>
          </div>
          <FormError message={error} />
          <div className="flex items-center justify-start gap-2 pt-2">
            <Button type="submit" disabled={pending}>
              {pending ? i18n.t('components.admin.user-editor.text_14') : i18n.t('components.admin.user-editor.text_15')}
            </Button>
            <Button type="button" variant="outline" onClick={() => setOpen(false)} disabled={pending}>
              {i18n.t('components.admin.user-editor.text_17')}</Button>
          </div>
        </form>
      </Modal>
    </>
  )
}

export function ToggleUserStatusButton({ user }: { user: AdminUser }) {
  const [pending, setPending] = React.useState(false)
  const router = useRouter()
  const isActive = user.status === "active"

  return (
    <Button
      type="button"
      variant="ghost"
      disabled={pending}
      onClick={async () => {
        setPending(true)
        const fd = new FormData()
        fd.set("id", user.id)
        fd.set("status", isActive ? "suspended" : "active")
        await setAdminUserStatus(fd)
        setPending(false)
        router.refresh()
      }}
      className={isActive ? "text-destructive hover:bg-destructive/10" : "text-emerald-700 hover:bg-emerald-50"}
    >
      {isActive ? (
        <>
          <ShieldOff className="h-3.5 w-3.5" />
          {i18n.t('components.admin.user-editor.text_18')}</>
      ) : (
        <>
          <ShieldCheck className="h-3.5 w-3.5" />
          {i18n.t('components.admin.user-editor.text_19')}</>
      )}
    </Button>
  )
}

export function InviteUserNote() {
  return (
    <div className="rounded-md border border-dashed border-border bg-muted/30 p-3 text-xs text-muted-foreground">
      {i18n.t('components.admin.user-editor.text_20')}{" "}
      <a className="font-medium text-gold-700 underline underline-offset-2" href="/auth/sign-up">
        /auth/sign-up
      </a>
      {i18n.t('components.admin.user-editor.text_21')}</div>
  )
}
