'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { useSession } from 'next-auth/react';
import Image from 'next/image';
import ClientSidebar from '@/components/client/ClientSidebar';
import { useToast } from '@/components/ui/ToastContext';
import './change-password.css';

export default function ChangePassword() {
  const params = useParams();
  const locale = params.locale as string;
  const { showSuccess, showError } = useToast();
  const { data: session } = useSession();

  const [formData, setFormData] = useState({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });
  const [isLoading, setIsLoading] = useState(false);
  const [showPasswords, setShowPasswords] = useState({
    oldPassword: false,
    newPassword: false,
    confirmPassword: false
  });
  const [touchedFields, setTouchedFields] = useState({
    oldPassword: false,
    newPassword: false,
    confirmPassword: false
  });
  const [isOAuthUser, setIsOAuthUser] = useState(false);

  useEffect(() => {
    // Check if user signed in with OAuth
    if (session?.user) {
      const provider = (session.user as { provider?: string }).provider;
      setIsOAuthUser(provider === 'google' || provider === 'facebook');
    }
  }, [session]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleInputBlur = (field: keyof typeof touchedFields) => {
    setTouchedFields(prev => ({
      ...prev,
      [field]: true
    }));
  };

  const togglePasswordVisibility = (field: keyof typeof showPasswords) => {
    setShowPasswords(prev => ({
      ...prev,
      [field]: !prev[field]
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validation
    if (formData.newPassword !== formData.confirmPassword) {
      showError('New password and confirm password do not match', 'Validation Error');
      return;
    }

    if (formData.newPassword.length < 8) {
      showError('New password must be at least 8 characters long', 'Validation Error');
      return;
    }

    if (formData.oldPassword === formData.newPassword) {
      showError('New password must be different from old password', 'Validation Error');
      return;
    }

    setIsLoading(true);

    try {
      const response = await fetch('/api/auth/change-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          oldPassword: formData.oldPassword,
          newPassword: formData.newPassword,
        }),
      });

      if (response.ok) {
        showSuccess('Password changed successfully!', 'Success');
        setFormData({
          oldPassword: '',
          newPassword: '',
          confirmPassword: ''
        });
        setTouchedFields({
          oldPassword: false,
          newPassword: false,
          confirmPassword: false
        });
      } else {
        const errorData = await response.json();
        // showError(errorData.message || 'Failed to change password', 'Error');
      }
    } catch (error) {
      console.error('Password change error:', error);
      showError('An error occurred while changing password', 'Error');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <section className="profile-wrapper create-project-wrapper py-60">
      <div className="container">
        <div className="row">
          <div className="col-12 col-md-4 col-xl-3">
            <ClientSidebar locale={locale} />
          </div>
          <div className="col-12 col-md-8 col-xl-9">
            <div className="content-box">
              <div className="tab-title">
                <h5>Change Password</h5>
              </div>
              <div className="form-wrap">
                {isOAuthUser ? (
                  <div className="alert alert-info">
                    <h6>Password Change Not Available</h6>
                    <p>You signed in using a social login (Google/Facebook). Password changes are not available for social login accounts. If you need to secure your account, please contact our support team.</p>
                  </div>
                ) : (
                  <form onSubmit={handleSubmit}>
                  <div className="form-group">
                    <div className="mb-20">
                      <label htmlFor="oldPassword" className="form-label">Old Password <span className='text-danger'>*</span></label>
                      <div className="input-icon">
                        <input
                          type={showPasswords.oldPassword ? "text" : "password"}
                          className={`form-control ${touchedFields.oldPassword ? 'touched' : ''}`}
                          name="oldPassword"
                          id="oldPassword"
                          placeholder="Enter Old Password"
                          value={formData.oldPassword}
                          onChange={handleInputChange}
                          onBlur={() => handleInputBlur('oldPassword')}
                          required
                        />
                        <div 
                          className="password-show-hide"
                          onClick={() => togglePasswordVisibility('oldPassword')}
                        >
                          {/* <img 
                            src="/assets/image/eye.svg" 
                            className="icon" 
                            alt="toggle password visibility"
                          /> */}

                          <Image 
                              src={showPasswords.oldPassword ? "/assets/image/eye-slash.svg" : "/assets/image/eye.svg"} 
                              className="icon" 
                              alt={showPasswords.oldPassword ? "hide password" : "show password"}
                              width={20}
                              height={20}
                            />
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <div className="form-group">
                    <div className="mb-20">
                      <label htmlFor="newPassword" className="form-label">New Password <span className='text-danger'>*</span></label>
                      <div className="input-icon">
                        <input
                          type={showPasswords.newPassword ? "text" : "password"}
                          className={`form-control ${touchedFields.newPassword ? 'touched' : ''}`}
                          name="newPassword"
                          id="newPassword"
                          placeholder="Enter New Password"
                          value={formData.newPassword}
                          onChange={handleInputChange}
                          onBlur={() => handleInputBlur('newPassword')}
                          required
                        />
                        <div 
                          className="password-show-hide"
                          onClick={() => togglePasswordVisibility('newPassword')}
                        >
                          {/* <img 
                            src="/assets/image/eye.svg" 
                            className="icon" 
                            alt="toggle password visibility"
                          /> */}

                          <Image 
                              src={showPasswords.newPassword ? "/assets/image/eye-slash.svg" : "/assets/image/eye.svg"} 
                              className="icon" 
                              alt={showPasswords.newPassword ? "hide password" : "show password"}
                              width={20}
                              height={20}
                            />
                        </div>
                      </div>
                    </div>

                    <div className="mb-20">
                      <label htmlFor="confirmPassword" className="form-label">Confirm New Password <span className='text-danger'>*</span></label>
                      <div className="input-icon">
                        <input
                          type={showPasswords.confirmPassword ? "text" : "password"}
                          className={`form-control ${touchedFields.confirmPassword ? 'touched' : ''}`}
                          name="confirmPassword"
                          id="confirmPassword"
                          placeholder="Confirm New Password"
                          value={formData.confirmPassword}
                          onChange={handleInputChange}
                          onBlur={() => handleInputBlur('confirmPassword')}
                          required
                        />
                        <div 
                          className="password-show-hide"
                          onClick={() => togglePasswordVisibility('confirmPassword')}
                        >
                          {/* <img 
                            src="/assets/image/eye.svg" 
                            className="icon" 
                            alt="toggle password visibility"
                          /> */}
                          <Image 
                              src={showPasswords.confirmPassword ? "/assets/image/eye-slash.svg" : "/assets/image/eye.svg"} 
                              className="icon" 
                              alt={showPasswords.confirmPassword ? "hide password" : "show password"}
                              width={20}
                              height={20}
                            />
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <button
                    type="submit"
                    className="w-100 custom-btn secondary-btn"
                    disabled={isLoading}
                  >
                    {isLoading ? 'Updating...' : 'Update'}
                  </button>
                </form>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}