'use client';
import React, { useState } from 'react';
import { app, auth } from '@/app/firebase/config';
import { signInWithEmailAndPassword, getAuth } from 'firebase/auth';
import GoogleSignInButton from '../firebase/components/GoogleSignInButton';
import { useRouter } from 'next/navigation';
import { LoginSologin } from '../sologin';

const SignIn = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    try {
      const userCredential = await signInWithEmailAndPassword(auth, email, password);
      console.log('User signed in:', userCredential.user);
      await LoginSologin(userCredential.user);
      onLoginSuccess();
      setEmail('');
      setPassword('');
      setError(null); // Clear errors on successful login
    } catch (err: any) {
      // Set the error message based on Firebase error codes
      switch (err.code) {
        case 'auth/user-not-found':
          setError('User not found. Please check your email and try again.');
          break;
        case 'auth/invalid-credential':
          setError('Incorrect password. Please try again.');
          break;
        case 'auth/network-request-failed':
          setError('Unable to connect. Please check your internet connection.');
          break;
        default:
          setError('An unexpected error occurred. Please try again.');
          console.error(err.code);
      }
    }
  };


  const onLoginSuccess = ()=>{
    router.push('/');
  }

  return (
    <div className="min-h-screen bg-gray-900 flex items-center justify-center">
      <div className="bg-gray-800 p-8 rounded-lg shadow-lg w-full sm:w-96">
        <h2 className="text-3xl font-bold text-white mb-6">Sign In</h2>
        <form onSubmit={handleSubmit}>
          <div className="mb-4">
            <label className="block text-sm text-gray-300 mb-2" htmlFor="email">
              Email Address
            </label>
            <input
              type="email"
              id="email"
              className="w-full p-3 bg-gray-700 text-white rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Enter your email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
          </div>
          <div className="mb-6">
            <label className="block text-sm text-gray-300 mb-2" htmlFor="password">
              Password
            </label>
            <input
              type="password"
              id="password"
              className="w-full p-3 bg-gray-700 text-white rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Enter your password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </div>
          <button
            type="submit"
            className="w-full py-3 bg-blue-600 text-white rounded-md hover:bg-blue-500 transition duration-300"
          >
            Sign In
          </button>
        </form>
        <p className="mt-4 text-center text-sm text-gray-400">
          Don't have an account?{' '}
          <a href="/signup" className="text-blue-400 hover:underline">
            Sign Up
          </a>
        </p>
        <GoogleSignInButton onLoginSuccess={onLoginSuccess}></GoogleSignInButton>
      </div>

        {/* Error Dialog */}
        {error && (
        <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
          <div className="bg-gray-800 p-6 rounded-lg shadow-lg">
            <h3 className="text-xl font-bold text-white mb-4">Error</h3>
            <p className="text-gray-300">{error}</p>
            <button
              className=" mt-4 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-500"
              onClick={() => setError(null)}
            >
              Close
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default SignIn;
