import React, { useState } from "react";
import { useNavigate } from 'react-router-dom';
import town from '../assets/town.jpg';
import { GoogleOAuthProvider, GoogleLogin } from '@react-oauth/google';

export default function Register() {

  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const GOOGLE_CLIENT_ID = "764706231535-61o8hs5bui31at36psk5ar8kbcfvsmnj.apps.googleusercontent.com";

  const navigate = useNavigate();
  
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    termsAccepted: false,
  });

  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const togglePassword = () => {
    setShowPassword((prev) => !prev);
  };

  const toggleConfirmPassword = () => {
    setShowConfirmPassword((prev) => !prev);
  };

  const handleChange = (e) => {
    const { name, value, checked, type } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');
  
    if (formData.password !== formData.confirmPassword) {
      return setError("Passwords do not match");
    }
  
    if (!formData.termsAccepted) {
      return setError("You must accept the terms");
    }
  
    try {
      
      const response = await fetch(`${import.meta.env.VITE_APP_API_BASE_URL}/signup/`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          username: formData.username,
          email: formData.email,
          password: formData.password,
          confirm_password: formData.confirmPassword,
        }),
      });

      if (response.ok) {
        setSuccess("Registration successful! Please check your email to activate your account.");
        setFormData({
          username: '',
          email: '',
          password: '',
          confirmPassword: '',
          termsAccepted: false,
        });
      } else {
        const data = await response.json();
        if (data?.error === 'Account is not activated. Please check your email for the activation link.') {
          setError(data.error);
        } else if (data?.password) {
          setError(data.password.join('\n')); 
        } else if (data?.email) {
          setError(`Email error: ${data.email.join(' ')}`);
        } else if (data?.username) {
          setError(`Username error: ${data.username.join(' ')}`);
        } else {
          const errorMessage = data?.detail || JSON.stringify(data) || "Something went wrong.";
          setError(errorMessage);
        }
      }
    } catch (err) {
      console.error(err);
      setError("Network error. Try again.");
    }
  };

  const handleGoogleSignupSuccess = async (credentialResponse) => {
    try {
    
      await axios.post(`${process.env.REACT_APP_API_BASE_URL}/google-auth/`, {
        access_token: credentialResponse.credential,
      });
      setSuccess("Google registration successful! You can now log in.");
      navigate('/');
    } catch (error) {
      console.error("Google sign up failed", error);
      setError("Google sign up failed. Please try again.");
    }
  };

  return (
    <GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
    <div className="relative min-h-screen flex items-center justify-center overflow-hidden">
      {/* Background image */}
      <div
        className="absolute inset-0 w-full h-full z-0"
        style={{ 
          backgroundImage: `linear-gradient(rgba(59, 130, 246, 0.25), rgba(59, 130, 246, 0.25)), url(${town})`, 
          backgroundSize: 'cover', 
          backgroundPosition: 'center'
        }}
        aria-hidden="true"
      />
      <div className="relative z-20 w-full max-w-xl min-h-[350px] p-4 md:p-8 bg-white/90 rounded-2xl shadow-2xl animate-fade-in-up flex flex-col gap-2 justify-center" style={{height:'auto'}}>
        <h2 className="text-3xl font-extrabold mb-4 text-blue-800 text-center drop-shadow">Register</h2>
        <form className="space-y-4" onSubmit={handleSubmit}>
          <div>
            <label className="block text-blue-900 font-semibold mb-1">Username</label>
            <input
              type="text"
              name="username"
              value={formData.username}
              onChange={handleChange}
               className="w-full px-4 py-2 border border-blue-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 bg-blue-50/60 transition"
             />
          </div>
          <div>
            <label className="block text-blue-900 font-semibold mb-1">Email</label>
            <input
  type="email"
  name="email"
  value={formData.email}
  onChange={handleChange}
  className="w-full px-4 py-2 border border-blue-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 bg-blue-50/60 transition"
/>
          </div>
          <div>
            <label className="block text-blue-900 font-semibold mb-1">Password</label>
            <input
  type={showPassword ? "text" : "password"}
  name="password"
  value={formData.password}
  onChange={handleChange}
  className="w-full px-4 py-2 border border-blue-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 bg-blue-50/60 transition"
/>
          </div>
          <div>
            <label className="block text-blue-900 font-semibold mb-1">Confirm Password</label>
            <input
  type={showConfirmPassword ? "text" : "password"}
  name="confirmPassword"
  value={formData.confirmPassword}
  onChange={handleChange}
  className="w-full px-4 py-2 border border-blue-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 bg-blue-50/60 transition"
/>
          </div>

          {/* Start of the converted Terms and Conditions block (MUI -> Tailwind) */}
          <div className="flex items-center justify-center p-3 rounded-xl border border-blue-300 bg-blue-50/50 shadow-inner">
            <input
              type="checkbox"
              name="termsAccepted"
              checked={formData.termsAccepted}
              onChange={handleChange}
              id="terms-switch"
              className="h-5 w-5 text-blue-600 bg-white border-gray-300 rounded focus:ring-blue-500 cursor-pointer"
            />
            <label htmlFor="terms-switch" className="ml-3 text-sm text-gray-700 font-medium">
              I agree to the{' '}
              <a href="/terms" 
                 onClick={(e) => {e.preventDefault(); console.log('Navigate to Terms');}} 
                 className="text-blue-600 hover:text-blue-700 hover:underline font-semibold transition"
              >
                Terms & Conditions
              </a>
            </label>
          </div>
          {/* End of the converted block */}
          {error && <p className="text-red-600 text-sm">{error}</p>}
         {success && <p className="text-green-600 text-sm">{success}</p>}

          <button type="submit" className="w-full bg-gradient-to-r from-blue-700 to-blue-500 text-white py-2 rounded-lg font-bold shadow hover:from-blue-800 hover:to-blue-600 transition mb-2">Register</button>

          <div className="flex justify-center mt-4">
  <GoogleLogin
    clientId={GOOGLE_CLIENT_ID}
    buttonText="Sign up with Google"
    onSuccess={handleGoogleSignupSuccess}
    onFailure={() => setError("Google sign up failed")}
    cookiePolicy={'single_host_origin'}
  />
</div>
          <div className="text-sm text-center text-blue-900">
            Already have an account? <a href="/login" className="text-blue-600 hover:underline font-semibold">Login</a>
          </div>
        </form>
      </div>
    </div>
    </GoogleOAuthProvider>
  );
}
