"use client"

import { supabase } from "@/lib/supabase/browser-client"
import { usePathname } from "next/navigation" // 导入 usePathname
import { useRouter } from "next/navigation"
import { FC, useState } from "react"
import { Button } from "../ui/button"
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "../ui/dialog"
import { Input } from "../ui/input"
import { toast } from "sonner"

interface ChangePasswordProps {}

export const ChangePassword: FC<ChangePasswordProps> = () => {
  const router = useRouter()
  const pathname = usePathname() // 获取当前路径

  

  const [newPassword, setNewPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")

  const handleResetPassword = async () => {
    if (!newPassword) return toast.info("Please enter your new password.")

    await supabase.auth.updateUser({ password: newPassword })

    toast.success("Password changed successfully.")

    // 提取当前路径中的 locale 部分
    const locale = pathname.split("/")[1] || "en"  // 获取路径中的 locale 部分，如果没有则默认为 "en"
    
    // 将 locale 添加到跳转 URL 中
    return router.push(`/${locale}/login`)
  }

  return (
    <Dialog open={true}>
      <DialogContent className="h-[240px] w-[400px] p-4">
        <DialogHeader>
          <DialogTitle>Change Password</DialogTitle>
        </DialogHeader>

        <Input
          id="password"
          placeholder="New Password"
          type="password"
          value={newPassword}
          onChange={e => setNewPassword(e.target.value)}
        />

        <Input
          id="confirmPassword"
          placeholder="Confirm New Password"
          type="password"
          value={confirmPassword}
          onChange={e => setConfirmPassword(e.target.value)}
        />

        <DialogFooter>
          <Button onClick={handleResetPassword}>Confirm Change</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
