'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { toast } from 'react-hot-toast'
import { Lock, Eye, EyeOff, Save } from 'lucide-react'
import { getApiErrorMessage } from '@/lib/utils/apiError'

export default function ChangePasswordForm() {
  const t = useTranslations('Account.changePassword')
  const [showCurrent, setShowCurrent] = useState(false)
  const [showNew, setShowNew] = useState(false)
  const [showConfirm, setShowConfirm] = useState(false)
  const [formData, setFormData] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: '',
  })
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [saving, setSaving] = useState(false)

  const validate = () => {
    const newErrors: Record<string, string> = {}
    if (!formData.currentPassword) newErrors.currentPassword = t('currentPasswordRequired')
    if (!formData.newPassword) newErrors.newPassword = t('newPasswordRequired')
    else if (formData.newPassword.length < 6) newErrors.newPassword = t('newPasswordTooShort')
    if (formData.newPassword !== formData.confirmPassword) newErrors.confirmPassword = t('passwordsDontMatch')
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!validate()) return

    setSaving(true)
    try {
      const res = await fetch('/api/frontend/auth/change-password', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ currentPassword: formData.currentPassword, newPassword: formData.newPassword }),
      })
      const data = await res.json()
      if (!res.ok || !data.success) {
        toast.error(getApiErrorMessage(data, t('changeFailed')))
        return
      }
      toast.success(t('changed'))
      setFormData({ currentPassword: '', newPassword: '', confirmPassword: '' })
    } catch {
      toast.error(t('networkError'))
    } finally {
      setSaving(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      {/* Current Password */}
      <div>
        <label className="block text-dark font-medium mb-2 text-sm">{t('currentPassword')}</label>
        <div className="relative">
          <Lock size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-custom" />
          <input
            type={showCurrent ? 'text' : 'password'}
            value={formData.currentPassword}
            onChange={(e) => setFormData({ ...formData, currentPassword: e.target.value })}
            className={`w-full pl-10 pr-12 py-2.5 border rounded-lg focus:outline-none focus:ring-1 transition ${
              errors.currentPassword
                ? 'border-red-500 focus:border-red-500 focus:ring-red-500'
                : 'border-gray-200 focus:border-primary focus:ring-primary'
            }`}
          />
          <button
            type="button"
            onClick={() => setShowCurrent(!showCurrent)}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-custom hover:text-primary transition"
          >
            {showCurrent ? <EyeOff size={18} /> : <Eye size={18} />}
          </button>
        </div>
        {errors.currentPassword && <p className="text-red-500 text-xs mt-1">{errors.currentPassword}</p>}
      </div>

      {/* New Password */}
      <div>
        <label className="block text-dark font-medium mb-2 text-sm">{t('newPassword')}</label>
        <div className="relative">
          <Lock size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-custom" />
          <input
            type={showNew ? 'text' : 'password'}
            value={formData.newPassword}
            onChange={(e) => setFormData({ ...formData, newPassword: e.target.value })}
            className={`w-full pl-10 pr-12 py-2.5 border rounded-lg focus:outline-none focus:ring-1 transition ${
              errors.newPassword
                ? 'border-red-500 focus:border-red-500 focus:ring-red-500'
                : 'border-gray-200 focus:border-primary focus:ring-primary'
            }`}
          />
          <button
            type="button"
            onClick={() => setShowNew(!showNew)}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-custom hover:text-primary transition"
          >
            {showNew ? <EyeOff size={18} /> : <Eye size={18} />}
          </button>
        </div>
        {errors.newPassword && <p className="text-red-500 text-xs mt-1">{errors.newPassword}</p>}
      </div>

      {/* Confirm Password */}
      <div>
        <label className="block text-dark font-medium mb-2 text-sm">{t('confirmNewPassword')}</label>
        <div className="relative">
          <Lock size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-custom" />
          <input
            type={showConfirm ? 'text' : 'password'}
            value={formData.confirmPassword}
            onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
            className={`w-full pl-10 pr-12 py-2.5 border rounded-lg focus:outline-none focus:ring-1 transition ${
              errors.confirmPassword
                ? 'border-red-500 focus:border-red-500 focus:ring-red-500'
                : 'border-gray-200 focus:border-primary focus:ring-primary'
            }`}
          />
          <button
            type="button"
            onClick={() => setShowConfirm(!showConfirm)}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-custom hover:text-primary transition"
          >
            {showConfirm ? <EyeOff size={18} /> : <Eye size={18} />}
          </button>
        </div>
        {errors.confirmPassword && <p className="text-red-500 text-xs mt-1">{errors.confirmPassword}</p>}
      </div>

      {/* Submit */}
      <button
        type="submit"
        disabled={saving}
        className="flex items-center gap-2 px-6 py-2.5 bg-gradient-primary text-white rounded-lg font-medium hover:shadow-md transition disabled:opacity-50"
      >
        <Save size={16} />
        {saving ? t('changing') : t('changePassword')}
      </button>
    </form>
  )
}
