// app/(root)/reset-password/page.tsx
'use client';

import { Suspense } from 'react'; // <-- Import Suspense
import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Eye, EyeOff, Lock, AlertCircle, Loader2, Shield, Check, ArrowLeft } from 'lucide-react';
import toast from 'react-hot-toast';

// Create a separate component that uses useSearchParams
function ResetPasswordForm() {
  const router = useRouter();
  const searchParams = useSearchParams(); // <-- Now safely used inside Suspense
  
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isValidating, setIsValidating] = useState(true);
  const [isValidToken, setIsValidToken] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  
  const [formData, setFormData] = useState({
    password: '',
    confirmPassword: '',
  });

  const email = searchParams.get('email');
  const token = searchParams.get('token');

  // Use useCallback to memoize the function
  const validateResetToken = useCallback(async () => {
    if (!email || !token) {
      setIsValidating(false);
      setIsValidToken(false);
      toast.error('Invalid reset link');
      return;
    }

    try {
      const response = await fetch('/api/frontend/user/auth/validate-reset-token', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, token }),
      });

      const data = await response.json();
      
      if (data.success) {
        setIsValidToken(true);
      } else {
        setIsValidToken(false);
        toast.error(data.message || 'Invalid or expired reset link');
      }
    } catch (error) {
      console.error('Token validation error:', error);
      setIsValidToken(false);
      toast.error('Failed to validate reset link');
    } finally {
      setIsValidating(false);
    }
  }, [email, token]);

  useEffect(() => {
    validateResetToken();
  }, [validateResetToken]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));
    
    // Clear error when user starts typing
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  const validateForm = () => {
    const newErrors: Record<string, string> = {};

    if (!formData.password) {
      newErrors.password = 'Password is required';
    } else if (formData.password.length < 8) {
      newErrors.password = 'Password must be at least 8 characters';
    } else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(formData.password)) {
      newErrors.password = 'Password must contain uppercase, lowercase, and number';
    }

    if (!formData.confirmPassword) {
      newErrors.confirmPassword = 'Please confirm your password';
    } else if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = 'Passwords do not match';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    setIsLoading(true);
    
    try {
      const response = await fetch('/api/frontend/user/auth/reset-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: email,
          token: token,
          newPassword: formData.password,
        }),
      });

      const data = await response.json();
      
      if (data.success) {
        toast.success('Password reset successfully!');
        
        // Redirect to login after 2 seconds
        setTimeout(() => {
          router.push('/login?reset=true');
        }, 2000);
      } else {
        setErrors({ submit: data.message || 'Failed to reset password' });
      }
    } catch (error) {
      console.error('Reset password error:', error);
      setErrors({ submit: 'An error occurred. Please try again.' });
    } finally {
      setIsLoading(false);
    }
  };

  const passwordStrength = formData.password.length > 0 ? 
    formData.password.length < 8 ? 'Weak' :
    /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(formData.password) ? 'Strong' : 'Medium'
    : '';

  const passwordRequirements = [
    { text: 'At least 8 characters', met: formData.password.length >= 8 },
    { text: 'One lowercase letter', met: /[a-z]/.test(formData.password) },
    { text: 'One uppercase letter', met: /[A-Z]/.test(formData.password) },
    { text: 'One number', met: /\d/.test(formData.password) },
  ];

  if (isValidating) {
    return (
      <div className="text-center">
        <div className="mb-8">
          <div className="flex justify-center mb-6">
            <div className="h-12 w-12 rounded-xl bg-linear-to-r from-blue-600 to-purple-600 flex items-center justify-center">
              <div className="h-6 w-6 text-white font-bold">N</div>
            </div>
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mb-3">Validating Reset Link</h1>
          <p className="text-gray-600">Please wait while we verify your reset link...</p>
        </div>
        <div className="bg-white py-10 px-8 shadow-lg rounded-2xl border border-gray-200">
          <Loader2 className="h-12 w-12 text-blue-600 animate-spin mx-auto mb-6" />
          <p className="text-gray-600">Checking link validity...</p>
        </div>
      </div>
    );
  }

  if (!isValidToken) {
    return (
      <div className="text-center">
        <div className="mb-10">
          <div className="flex justify-center mb-6">
            <div className="h-12 w-12 rounded-xl bg-linear-to-r from-blue-600 to-purple-600 flex items-center justify-center">
              <div className="h-6 w-6 text-white font-bold">N</div>
            </div>
          </div>
          <h1 className="text-3xl font-bold text-gray-900 mb-3">Invalid Reset Link</h1>
          <p className="text-gray-600">
            This password reset link is invalid or has expired.
          </p>
        </div>

        <div className="bg-white py-10 px-8 shadow-lg rounded-2xl border border-gray-200">
          <div className="mb-8 text-center">
            <div className="h-16 w-16 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-6">
              <AlertCircle className="h-8 w-8 text-red-600" />
            </div>
            <h2 className="text-xl font-semibold text-gray-900 mb-3">
              Link Expired or Invalid
            </h2>
            <p className="text-gray-600">
              Password reset links are valid for 10 minutes only. Please request a new reset link.
            </p>
          </div>

          <div className="space-y-4">
            <Link
              href="/forgot-password"
              className="w-full flex justify-center items-center py-3.5 px-4 border border-transparent rounded-xl shadow-sm text-sm font-medium text-white bg-linear-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all hover:shadow-md"
            >
              Request New Reset Link
            </Link>
            <Link
              href="/login"
              className="w-full flex justify-center items-center py-3 px-4 border border-gray-300 rounded-xl shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all"
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              Back to Login
            </Link>
          </div>

          <div className="mt-8 pt-6 border-t border-gray-200">
            <div className="flex items-center text-sm text-gray-600">
              <Shield className="h-4 w-4 mr-2 text-gray-400" />
              <span>For security, reset links expire after 10 minutes.</span>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full max-w-md">
      {/* Back Button */}
      <div className="mb-8">
        <Link
          href="/login"
          className="inline-flex items-center text-sm font-medium text-gray-600 hover:text-gray-900"
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          Back to login
        </Link>
      </div>

      <div className="text-center mb-10">
        <div className="flex justify-center mb-6">
          <div className="h-12 w-12 rounded-xl bg-linear-to-r from-blue-600 to-purple-600 flex items-center justify-center">
            <div className="h-6 w-6 text-white font-bold">N</div>
          </div>
        </div>
        <h1 className="text-3xl font-bold text-gray-900 mb-3">Create New Password</h1>
        <p className="text-gray-600">
          Enter a new password for your account
        </p>
        {email && (
          <p className="text-sm text-gray-500 mt-2">
            Account: <span className="font-medium">{email}</span>
          </p>
        )}
      </div>

      {/* Form Card */}
      <div className="bg-white py-10 px-8 shadow-lg rounded-2xl border border-gray-200">
        {errors.submit && (
          <div className="mb-6 p-4 rounded-lg bg-red-50 border border-red-200">
            <div className="flex items-center">
              <AlertCircle className="h-5 w-5 text-red-500 mr-3" />
              <p className="text-sm text-red-700">{errors.submit}</p>
            </div>
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-6">
          {/* New Password Field */}
          <div>
            <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
              New Password
            </label>
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Lock className="h-5 w-5 text-gray-400" />
              </div>
              <input
                id="password"
                name="password"
                type={showPassword ? 'text' : 'password'}
                autoComplete="new-password"
                value={formData.password}
                onChange={handleChange}
                className={`block w-full pl-10 pr-10 py-3.5 border ${
                  errors.password ? 'border-red-300' : 'border-gray-300'
                } rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors`}
                placeholder="••••••••"
                disabled={isLoading}
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600"
                disabled={isLoading}
              >
                {showPassword ? (
                  <EyeOff className="h-5 w-5" />
                ) : (
                  <Eye className="h-5 w-5" />
                )}
              </button>
            </div>
            
            {/* Password Strength */}
            {formData.password && (
              <div className="mt-3">
                <div className="flex items-center justify-between text-sm mb-1">
                  <span className="text-gray-600">Password strength:</span>
                  <span className={`font-medium ${
                    passwordStrength === 'Strong' ? 'text-green-600' :
                    passwordStrength === 'Medium' ? 'text-yellow-600' :
                    'text-red-600'
                  }`}>
                    {passwordStrength}
                  </span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div 
                    className={`h-2 rounded-full transition-all duration-300 ${
                      passwordStrength === 'Strong' ? 'w-full bg-green-500' :
                      passwordStrength === 'Medium' ? 'w-2/3 bg-yellow-500' :
                      'w-1/3 bg-red-500'
                    }`}
                  />
                </div>
              </div>
            )}
            
            {errors.password && (
              <p className="mt-2 text-sm text-red-600 flex items-center">
                <AlertCircle className="h-4 w-4 mr-1" />
                {errors.password}
              </p>
            )}
          </div>

          {/* Confirm Password Field */}
          <div>
            <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 mb-2">
              Confirm New Password
            </label>
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Lock className="h-5 w-5 text-gray-400" />
              </div>
              <input
                id="confirmPassword"
                name="confirmPassword"
                type={showConfirmPassword ? 'text' : 'password'}
                autoComplete="new-password"
                value={formData.confirmPassword}
                onChange={handleChange}
                className={`block w-full pl-10 pr-10 py-3.5 border ${
                  errors.confirmPassword ? 'border-red-300' : 'border-gray-300'
                } rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors`}
                placeholder="••••••••"
                disabled={isLoading}
              />
              <button
                type="button"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600"
                disabled={isLoading}
              >
                {showConfirmPassword ? (
                  <EyeOff className="h-5 w-5" />
                ) : (
                  <Eye className="h-5 w-5" />
                )}
              </button>
            </div>
            {errors.confirmPassword && (
              <p className="mt-2 text-sm text-red-600 flex items-center">
                <AlertCircle className="h-4 w-4 mr-1" />
                {errors.confirmPassword}
              </p>
            )}
          </div>

          {/* Password Requirements */}
          <div className="p-4 bg-gray-50 rounded-xl border border-gray-200">
            <p className="text-sm font-medium text-gray-900 mb-3">Password must contain:</p>
            <div className="space-y-2">
              {passwordRequirements.map((req, index) => (
                <div key={index} className="flex items-center">
                  <div className={`flex h-5 w-5 items-center justify-center rounded-full mr-3 ${
                    req.met ? 'bg-green-100 text-green-600' : 'bg-gray-100 text-gray-400'
                  }`}>
                    <Check className="h-3 w-3" />
                  </div>
                  <span className={`text-sm ${req.met ? 'text-green-600' : 'text-gray-600'}`}>
                    {req.text}
                  </span>
                </div>
              ))}
            </div>
          </div>

          {/* Submit Button */}
          <button
            type="submit"
            disabled={isLoading}
            className="w-full flex justify-center items-center py-3.5 px-4 border border-transparent rounded-xl shadow-sm text-sm font-medium text-white bg-linear-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all hover:shadow-md active:scale-[0.98]"
          >
            {isLoading ? (
              <>
                <Loader2 className="animate-spin h-5 w-5 mr-2" />
                Resetting Password...
              </>
            ) : (
              'Reset Password'
            )}
          </button>
        </form>

        {/* Security Info */}
        <div className="mt-8 pt-6 border-t border-gray-200">
          <div className="flex items-start text-sm text-gray-600">
            <Shield className="h-4 w-4 mr-3 mt-0.5 text-gray-400" />
            <span>
              After resetting your password, you`ll be redirected to login. Use your new password to sign in.
            </span>
          </div>
        </div>
      </div>

      {/* Help Link */}
      <div className="mt-8 text-center">
        <p className="text-sm text-gray-600">
          Need help?{' '}
          <Link href="/contact" className="font-medium text-blue-600 hover:text-blue-500">
            Contact support
          </Link>
        </p>
      </div>
    </div>
  );
}

// Main page component with Suspense
export default function ResetPasswordPage() {
  return (
    <div className="min-h-[calc(100vh-4rem)] flex items-center justify-center p-6">
      <Suspense fallback={
        <div className="text-center">
          <div className="mb-8">
            <div className="flex justify-center mb-6">
              <div className="h-12 w-12 rounded-xl bg-linear-to-r from-blue-600 to-purple-600 flex items-center justify-center">
                <div className="h-6 w-6 text-white font-bold">N</div>
              </div>
            </div>
            <h1 className="text-2xl font-bold text-gray-900 mb-3">Loading Reset Password</h1>
            <p className="text-gray-600">Please wait...</p>
          </div>
          <div className="bg-white py-10 px-8 shadow-lg rounded-2xl border border-gray-200">
            <Loader2 className="h-12 w-12 text-blue-600 animate-spin mx-auto mb-6" />
            <p className="text-gray-600">Preparing the password reset form...</p>
          </div>
        </div>
      }>
        <ResetPasswordForm />
      </Suspense>
    </div>
  );
}