'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { api, apiPaths } from '@/lib/api';
import { saveToken } from '@/lib/auth';

export default function ResetPasswordPage() {
  const router = useRouter();
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [passwordError, setPasswordError] = useState('');
  const [confirmError, setConfirmError] = useState('');
  const [submitError, setSubmitError] = useState('');
  const [resetToken, setResetToken] = useState('');

  useEffect(() => {
    const token = sessionStorage.getItem('reset_token');
    if (!token) {
      router.push('/forgot-password');
      return;
    }
    setResetToken(token);
  }, [router]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!password || !confirmPassword) { setError('الرجاء إدخال كلمة المرور'); return; }
    if (password !== confirmPassword) { setError('كلمتا المرور غير متطابقتين'); return; }
    if (password.length < 6) { setError('يجب أن تكون كلمة المرور 6 أحرف على الأقل'); return; }

    setError('');
    setLoading(true);

    const res = await api.postWithBearer<{ token?: string }>(
      apiPaths.user.resetPassword,
      { password, password_confirmation: confirmPassword },
      resetToken
    );

    setLoading(false);

    if (res.key === 'success') {
      sessionStorage.removeItem('reset_token');
      sessionStorage.removeItem('reset_phone');
      sessionStorage.removeItem('reset_country_code');

      const newToken = res.data?.token;
      if (newToken) {
        saveToken(newToken);
      }

      router.push('/login?reset=success');
    } else {
      setSubmitError(res.msg || 'حدث خطأ، يرجى المحاولة مجدداً');
    }
  };

  return (
    <div dir="rtl" className="min-h-screen bg-gradient-to-br from-blue-600 to-blue-800 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        <div className="bg-white rounded-2xl shadow-2xl p-8">
          <div className="text-center mb-8">
            <div className="w-16 h-16 bg-green-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
              <i className="ri-lock-2-line text-3xl text-green-600"></i>
            </div>
            <h1 className="text-2xl font-bold text-gray-900">تعيين كلمة مرور جديدة</h1>
            <p className="text-gray-500 mt-2">أدخل كلمة مرور جديدة لحسابك</p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-5">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">كلمة المرور الجديدة</label>
              <div className="relative">
                <input
                  type={showPassword ? 'text' : 'password'}
                  value={password}
                  onChange={(e) => {
                    setPassword(e.target.value);
                    setPasswordError('');
                  }}
                  placeholder="6 أحرف على الأقل"
                  className={`w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 pl-10 ${
                    passwordError ? 'border-red-500 ring-1 ring-red-500/20' : 'border-gray-200'
                  }`}
                  aria-invalid={!!passwordError}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 cursor-pointer"
                >
                  <i className={showPassword ? 'ri-eye-off-line' : 'ri-eye-line'}></i>
                </button>
              </div>
              {passwordError ? <p className="text-red-600 text-sm mt-1">{passwordError}</p> : null}
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">تأكيد كلمة المرور</label>
              <input
                type={showPassword ? 'text' : 'password'}
                value={confirmPassword}
                onChange={(e) => {
                  setConfirmPassword(e.target.value);
                  setConfirmError('');
                }}
                placeholder="أعد إدخال كلمة المرور"
                className={`w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                  confirmError ? 'border-red-500 ring-1 ring-red-500/20' : 'border-gray-200'
                }`}
                aria-invalid={!!confirmError}
              />
              {confirmError ? <p className="text-red-600 text-sm mt-1">{confirmError}</p> : null}
            </div>

            {submitError && (
              <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm flex items-center gap-2">
                <i className="ri-error-warning-line"></i>
                {submitError}
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              className="w-full bg-green-600 text-white py-3.5 rounded-xl font-semibold hover:bg-green-700 disabled:bg-gray-300 transition-colors"
            >
              {loading ? (
                <span className="flex items-center justify-center gap-2">
                  <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                  جاري الحفظ...
                </span>
              ) : (
                'حفظ كلمة المرور'
              )}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
