"use client"

import { useActionState, useEffect, useMemo, useRef, useState } from "react"
import { useFormStatus } from "react-dom"
import { useTranslations } from "next-intl"
import { Eye, EyeOff, KeyRound, Loader2 } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Progress } from "@/shared/components/ui/progress"
import { changePasswordAction } from "@/modules/settings/actions-password"
import {
  getPasswordStrength,
  PASSWORD_REQUIREMENT_HINTS,
  type PasswordStrength,
} from "@/shared/lib/password-policy"
import type { ActionState } from "@/shared/types/action-state"

const STRENGTH_META: Record<PasswordStrength, { value: number; labelKey: string; barClassName: string; indicatorClassName: string }> = {
  weak: { value: 33, labelKey: "security.changePassword.strengthWeak", barClassName: "h-2", indicatorClassName: "bg-red-500" },
  medium: { value: 66, labelKey: "security.changePassword.strengthMedium", barClassName: "h-2", indicatorClassName: "bg-yellow-500" },
  strong: { value: 100, labelKey: "security.changePassword.strengthStrong", barClassName: "h-2", indicatorClassName: "bg-green-500" },
}

function SubmitButton() {
  const { pending } = useFormStatus()
  const t = useTranslations("settings.security.changePassword")
  return (
    <Button type="submit" disabled={pending}>
      {pending ? (
        <>
          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          {t("updating")}
        </>
      ) : (
        <>
          <KeyRound className="mr-2 h-4 w-4" />
          {t("submit")}
        </>
      )}
    </Button>
  )
}

export function PasswordChangeForm() {
  const t = useTranslations("settings.security.changePassword")
  const [state, formAction] = useActionState<ActionState<null>, FormData>(
    changePasswordAction,
    { success: false, data: null }
  )
  const [newPassword, setNewPassword] = useState("")
  const [showCurrent, setShowCurrent] = useState(false)
  const [showNew, setShowNew] = useState(false)
  const [showConfirm, setShowConfirm] = useState(false)
  const formRef = useRef<HTMLFormElement>(null)

  const strength = useMemo(() => getPasswordStrength(newPassword), [newPassword])
  const meta = STRENGTH_META[strength]

  useEffect(() => {
    if (state?.success) {
      toast.success(state.message ?? t("success"))
      formRef.current?.reset()
    } else if (state?.message) {
      toast.error(state.message)
    }
  }, [state, t])

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("title")}</CardTitle>
        <CardDescription>{t("description")}</CardDescription>
      </CardHeader>
      <form ref={formRef} id="password-change-form" action={formAction} onReset={() => setNewPassword("")}>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="currentPassword">{t("current")}</Label>
            <div className="relative">
              <Input
                id="currentPassword"
                name="currentPassword"
                type={showCurrent ? "text" : "password"}
                placeholder={t("currentPlaceholder")}
                required
                autoComplete="current-password"
              />
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                onClick={() => setShowCurrent((v) => !v)}
                aria-label={showCurrent ? "Hide password" : "Show password"}
              >
                {showCurrent ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </Button>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="newPassword">{t("new")}</Label>
            <div className="relative">
              <Input
                id="newPassword"
                name="newPassword"
                type={showNew ? "text" : "password"}
                placeholder={t("newPlaceholder")}
                required
                autoComplete="new-password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
              />
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                onClick={() => setShowNew((v) => !v)}
                aria-label={showNew ? "Hide password" : "Show password"}
              >
                {showNew ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </Button>
            </div>
            {newPassword.length > 0 && (
              <div className="space-y-1">
                <div className="flex items-center justify-between text-xs">
                  <span className="text-muted-foreground">{t("strength")}</span>
                  <span className="font-medium">{t(meta.labelKey)}</span>
                </div>
                <Progress value={meta.value} className={meta.barClassName} indicatorClassName={meta.indicatorClassName} />
              </div>
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="confirmPassword">{t("confirm")}</Label>
            <div className="relative">
              <Input
                id="confirmPassword"
                name="confirmPassword"
                type={showConfirm ? "text" : "password"}
                placeholder={t("confirmPlaceholder")}
                required
                autoComplete="new-password"
              />
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                onClick={() => setShowConfirm((v) => !v)}
                aria-label={showConfirm ? "Hide password" : "Show password"}
              >
                {showConfirm ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </Button>
            </div>
          </div>

          <div className="rounded-md border bg-muted/30 p-3">
            <div className="text-xs font-medium text-muted-foreground">{t("requirements")}</div>
            <ul className="mt-1.5 grid gap-1 text-xs text-muted-foreground">
              {PASSWORD_REQUIREMENT_HINTS.map((hint) => (
                <li key={hint} className="flex items-center gap-1.5">
                  <span className="h-1 w-1 rounded-full bg-muted-foreground" />
                  {hint}
                </li>
              ))}
            </ul>
          </div>
        </CardContent>
        <CardFooter className="flex justify-end border-t px-6 py-4">
          <SubmitButton />
        </CardFooter>
      </form>
    </Card>
  )
}
