'use client';
import React, { useState } from 'react';
import { auth } from '@/app/firebase/config';
import { signInWithEmailAndPassword, createUserWithEmailAndPassword } from 'firebase/auth';
import GoogleSignInButton from '../firebase/components/GoogleSignInButton';
import { useRouter } from 'next/navigation';
import { LoginSologin, RegisterSologin } from '../sologin';
import SignInWithGithub from '../firebase/components/GithubSignInButton';
import Button from '../widgets/LoginButton';
import Head from 'next/head';

const AuthTabs = () => {
  const [activeTab, setActiveTab] = useState<'signin' | 'signup'>('signin');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const router = useRouter();

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

  const handleAuth = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    try {
      if (activeTab === 'signin') {
        const userCredential = await signInWithEmailAndPassword(auth, email, password);
        console.log('User signed in:', userCredential.user);
        await LoginSologin(userCredential.user);
      } else {
        const userCredential = await createUserWithEmailAndPassword(auth, email, password);
        console.log('User signed up:', userCredential.user);
        await RegisterSologin(userCredential.user);
      }
      onAuthSuccess();
      setEmail('');
      setPassword('');
      setError(null);
      setIsModalOpen(false); // Close the modal on success
    } catch (err: any) {
      const errorCode = err.code;
      switch (errorCode) {
        case 'auth/user-not-found':
          setError('User not found. Please check your email.');
          break;
        case 'auth/email-already-in-use':
          setError('This email is already registered. Try signing in.');
          break;
        case 'auth/wrong-password':
          setError('Incorrect email or password.');
          break;
        default:
          setError('An unexpected error occurred. Please try again.');
      }
    }
  };

  return (
    <>
      <Head>
        <title>Login · W3B Games</title>
        <link
          href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
          rel="stylesheet"
        />
      </Head>

      <main className="flex min-h-screen w-full relative overflow-hidden font-inter">
        <div className="flex flex-col w-full h-screen">
          <div className="flex-[3] bg-[#0F0F0F]"></div>
          <div className="flex-[4] bg-black"></div>
        </div>
        <div className="absolute inset-x-0 top-0 flex items-center justify-center pointer-events-none h-[86vh]">
          <h2 className="text-[10vw] font-bold whitespace-nowrap bg-clip-text text-transparent bg-[linear-gradient(to_bottom,black_50%,#0F0F0F_50%)]">
            METAHUNT
          </h2>
        </div>
        <div className="absolute inset-x-10 top-10 flex w-24 h-24">
          <img src="./logos/logo.png" />
        </div>
        <div className="absolute inset-0 flex justify-center items-center">
          <div className="text-center w-full px-6 relative top-[10vh]">
            <div className="mt-6 flex justify-center ">
              <div className="bg-blue-500 rounded-full hover:scale-110 transition-all duration-300">
                <Button onClick={() => setIsModalOpen(true)} text="LOG IN / REGISTER" />
              </div>
            </div>
          </div>
        </div>
      </main>

      {/* Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-gray-800 p-8 rounded-lg shadow-lg w-full sm:w-96 relative">
            <button
              className="absolute top-3 right-3 text-gray-400 hover:text-white"
              onClick={() => setIsModalOpen(false)}
            >
              ✕
            </button>
            <div className="flex border-b border-gray-600 mb-6">
              <button
                className={`flex-1 py-2 text-center ${
                  activeTab === 'signin'
                    ? 'text-white border-b-2 border-blue-500'
                    : 'text-gray-400 hover:text-white'
                }`}
                onClick={() => setActiveTab('signin')}
              >
                Sign In
              </button>
              <button
                className={`flex-1 py-2 text-center ${
                  activeTab === 'signup'
                    ? 'text-white border-b-2 border-blue-500'
                    : 'text-gray-400 hover:text-white'
                }`}
                onClick={() => setActiveTab('signup')}
              >
                Sign Up
              </button>
            </div>
            <form onSubmit={handleAuth}>
              <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"
              >
                {activeTab === 'signin' ? 'Sign In' : 'Sign Up'}
              </button>
            </form>
            <div className="h-10"></div>
            <GoogleSignInButton onLoginSuccess={onAuthSuccess} />
            <SignInWithGithub onLoginSuccess={onAuthSuccess} />
          </div>
        </div>
      )}
    </>
  );
};

export default AuthTabs;
