"use client"

import { useActionState, useEffect, useMemo, useRef, useState } from "react"
import { useFormStatus } from "react-dom"
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; label: string; barClassName: string; indicatorClassName: string }> = {
  weak: { value: 33, label: "Weak", barClassName: "h-2", indicatorClassName: "bg-red-500" },
  medium: { value: 66, label: "Medium", barClassName: "h-2", indicatorClassName: "bg-yellow-500" },
  strong: { value: 100, label: "Strong", barClassName: "h-2", indicatorClassName: "bg-green-500" },
}

function SubmitButton() {
  const { pending } = useFormStatus()
  return (
    <Button type="submit" disabled={pending}>
      {pending ? (
        <>
          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          Updating...
        </>
      ) : (
        <>
          <KeyRound className="mr-2 h-4 w-4" />
          Update Password
        </>
      )}
    </Button>
  )
}

export function PasswordChangeForm() {
  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 ?? "Password changed successfully")
      formRef.current?.reset()
    } else if (state?.message) {
      toast.error(state.message)
    }
  }, [state])

  return (
    <Card>
      <CardHeader>
        <CardTitle>Change Password</CardTitle>
        <CardDescription>
          Choose a strong password to keep your account secure.
        </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">Current Password</Label>
            <div className="relative">
              <Input
                id="currentPassword"
                name="currentPassword"
                type={showCurrent ? "text" : "password"}
                placeholder="Enter current password"
                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)}
                tabIndex={-1}
              >
                {showCurrent ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </Button>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="newPassword">New Password</Label>
            <div className="relative">
              <Input
                id="newPassword"
                name="newPassword"
                type={showNew ? "text" : "password"}
                placeholder="Enter new password"
                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)}
                tabIndex={-1}
              >
                {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">Password strength</span>
                  <span className="font-medium">{meta.label}</span>
                </div>
                <Progress value={meta.value} className={meta.barClassName} indicatorClassName={meta.indicatorClassName} />
              </div>
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="confirmPassword">Confirm New Password</Label>
            <div className="relative">
              <Input
                id="confirmPassword"
                name="confirmPassword"
                type={showConfirm ? "text" : "password"}
                placeholder="Re-enter new password"
                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)}
                tabIndex={-1}
              >
                {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">Password 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>
  )
}
