"use client"
import { usePage } from "@inertiajs/react"
import { useState } from "react"
import { Input } from "@/Components/UI/Input"
import { Button } from "@/Components/UI/Button"
import { Eye, EyeOff, ArrowLeft } from "lucide-react"
import AuthLayout from "@/Layouts/AuthLayout"
import { router } from "@inertiajs/react"
import useTranslate from "@/hooks/useTranslate";

export default function CreateNewPassword() {
    const { errors } = usePage().props
    const [password, setPassword] = useState("")
    const [confirmPassword, setConfirmPassword] = useState("")
    const [showPassword, setShowPassword] = useState(false)
    const [showConfirmPassword, setShowConfirmPassword] = useState(false)
    const [message, setMessage] = useState("")
    const [isSubmitting, setIsSubmitting] = useState(false)

    const t = useTranslate()

    const handleBack = () => {

        window.history.back()
    }

    const getPasswordStrength = (pwd) => {
        let strength = 0
        if (pwd.length >= 8) strength++
        if (/[a-z]/.test(pwd) && /[A-Z]/.test(pwd)) strength++
        if (/\d/.test(pwd)) strength++
        if (/[^a-zA-Z0-9]/.test(pwd)) strength++

        let strengthText = "Weak"
        let strengthColor = "bg-red-500"
        if (strength === 1) {
            strengthText = "Fair"
            strengthColor = "bg-orange-500"
        } else if (strength === 2) {
            strengthText = "Good"
            strengthColor = "bg-yellow-500"
        } else if (strength >= 3) {
            strengthText = "Strong"
            strengthColor = "bg-green-500"
        }
        if (pwd.length === 0) {
            strengthText = ""
            strengthColor = "bg-gray-300"
        }

        return { strength, strengthText, strengthColor }
    }

    const { strength, strengthText, strengthColor } = getPasswordStrength(password)

    const handleSubmit = (e) => {
        e.preventDefault()
        setIsSubmitting(true)
        if (password !== confirmPassword) {
            setMessage(t("Passwords do not match."))
            setIsSubmitting(false)
            return
        }
        if (strength < 3) {
            setMessage(t("Password is not strong enough."))
            setIsSubmitting(false)
            return
        }

        const url = route("auth.password.update")
        router.post(url, { password: password, password_confirmation: confirmPassword }, {
            onFinish: () => setIsSubmitting(false),
            onError: () => setIsSubmitting(false),
        })


    }

    return (
        <AuthLayout>
            <div className="relative">
                {" "}
                {/* Added relative positioning for the arrow */}
                <Button
                    variant="ghost"
                    size="icon"
                    onClick={handleBack}
                    className="absolute -top-2 -left-2 text-gray-600 dark:text-gray-200 hover:bg-gray-100"
                    aria-label="Go back"
                >
                    <ArrowLeft className="h-6 w-6" />
                </Button>
                <h1 className="text-2xl font-bold mb-4 text-center text-gray-700 dark:text-gray-200 dark:text-gray-200">{t("Create New Password")}</h1>
                <p className="text-center text-gray-600 dark:text-gray-200 mb-8">{t("Send your email account to reset password & make new password")}</p>
                <form onSubmit={handleSubmit}>
                    <div className="mb-6">
                        <label htmlFor="new-password" className="block mb-2 text-sm font-semibold text-gray-700 dark:text-gray-200">
                            {t("New Password")}
                        </label>
                        <div className="relative">
                            <Input
                                type={showPassword ? "text" : "password"}
                                id="new-password"
                                name="new-password"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                placeholder={t("Enter your new password")}
                                required
                                className="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary dark:bg-zinc-800 dark:border-zinc-600 dark:text-white pr-10"
                                disabled={isSubmitting}
                            />
                            <button
                                type="button"
                                onClick={() => setShowPassword(!showPassword)}
                                className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-500 dark:text-gray-300 hover:text-primary dark:hover:text-primary transition-colors"
                                aria-label={showPassword ? "Hide password" : "Show password"}
                                disabled={isSubmitting}
                            >
                                {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                            </button>
                            {errors.password && <p className="mt-2 text-red-600 text-sm">{errors.password}</p>}
                        </div>
                        <p className="text-xs text-gray-500 dark:text-gray-300 mt-2">{t("Min 8 Characters with a combination of letters and numbers")}</p>
                        <div className="flex items-center gap-1 mt-2">
                            {Array.from({ length: 4 }).map((_, i) => (
                                <div
                                    key={i}
                                    className={`h-2 flex-1 rounded-full ${i < strength ? strengthColor : "bg-gray-200"
                                        } transition-colors duration-300`}
                                />
                            ))}
                            <span
                                className={`text-xs font-semibold ml-2 ${strengthText === "Strong" ? "text-green-500" : "text-gray-500 dark:text-gray-300"}`}
                            >
                                {strengthText}
                            </span>
                        </div>
                    </div>
                    <div className="mb-6">
                        <label htmlFor="confirm-password" className="block mb-2 text-sm font-semibold text-gray-700 dark:text-gray-200">
                            {t("Repeat Password")}
                        </label>
                        <div className="relative">
                            <Input
                                type={showConfirmPassword ? "text" : "password"}
                                id="confirm-password"
                                name="confirm-password"
                                value={confirmPassword}
                                onChange={(e) => setConfirmPassword(e.target.value)}
                                placeholder={t("Confirm your new password")}
                                required
                                className="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary dark:bg-zinc-800 dark:border-zinc-600 dark:text-white pr-10"
                                disabled={isSubmitting}
                            />
                            <button
                                type="button"
                                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                                className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-500 dark:text-gray-300 hover:text-primary dark:hover:text-primary transition-colors"
                                aria-label={showConfirmPassword ? "Hide password" : "Show password"}
                                disabled={isSubmitting}
                            >
                                {showConfirmPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                            </button>
                            {errors.password_confirmation && <p className="mt-2 text-red-600 text-sm">{errors.password_confirmation}</p>}
                        </div>
                    </div>
                    <Button
                        type="submit"
                        isLoading={isSubmitting}
                        className="w-full bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary shadow-md hover:shadow-lg transition-all duration-200"
                    >
                        {isSubmitting ? t("Setting password...") : t("Continue")}
                    </Button>
                </form>
                {message && (
                    <p
                        className={`mt-4 text-center text-sm ${message.includes("match") || message.includes("strong") ? "text-red-600" : "text-green-600"}`}
                    >
                        {message}
                    </p>
                )}
            </div>
        </AuthLayout>
    )
}
