'use client';

import { useState, use, useEffect } from 'react';
import { signIn, getSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useRememberMe } from '@/hooks/useRememberMe';
import './login.css';

const loginSchema = z.object({
  email: z.string().email('Please enter a valid email address'),
  password: z.string().min(6, 'Password must be at least 6 characters'),
  remember: z.boolean().optional(),
});

type LoginFormData = z.infer<typeof loginSchema>;

interface LoginPageProps {
  params: Promise<{
    locale: string;
  }>;
}

export default function LoginPage({ params }: LoginPageProps) {
  const { locale } = use(params);
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { rememberedEmail, handleRememberMe } = useRememberMe();

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      remember: !!rememberedEmail,
    },
  });


  // Pre-fill email if remembered
  useEffect(() => {
    if (rememberedEmail) {
      setValue('email', rememberedEmail);
      setValue('remember', true);
    }
  }, [rememberedEmail, setValue]);

  const onSubmit = async (data: LoginFormData) => {
    setIsLoading(true);
    setError(null);

    try {
      // Handle remember me functionality
      handleRememberMe(data.email, data.remember || false);

      const result = await signIn('credentials', {
        email: data.email,
        password: data.password,
        remember: data.remember ? 'true' : 'false',
        redirect: false,
      });

      if (result?.error) {
        setError('Invalid email or password');
      } else {
        // Redirect based on user role (this will be determined after sign in)
        const session = await getSession();
        if (session?.user) {
          const role = (session.user as { role: string }).role.toLowerCase();
          if (role === 'client') {
            router.push(`/${locale}/client/my-projects`);
          } else {
            router.push(`/${locale}/freelancer/my-projects`);
          }
        }
      }
    } catch {
      setError('An error occurred. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleSocialLogin = async (provider: 'google' | 'facebook') => {
    setIsLoading(true);
    try {
      await signIn(provider, {
        callbackUrl: `/${locale}/freelancer/my-projects`,
      });
    } catch {
      setError('An error occurred with social login');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <section className="login-wrapper py-100">
      <div className="container">
        <div className="row">
          <div className="col-12 col-md-6">
            <div className="title">
              <h1>
                Hii Chris! It&apos;s Great to have you on board.
              </h1>
            </div>
            <div className="discription">
              <p>
                Take a few minutes to update your profile and increase your visibility, 
                attract better clients, and get matched with the right projects faster.
              </p>
            </div>
            <div className="login-img mb-2">
              <Image 
                src="/assets/image/login-img.svg" 
                className="img-fluid" 
                alt="login img"
                width={0}
                height={0}
                sizes="100vw"
                style={{ width: '100%', height: 'auto' }}
              />
            </div>
          </div>
          <div className="col-12 col-md-6">
            <div className="login-form">
              <h2>
                Glad to see you again!
              </h2>
              <div className="discription">
                <p>
                  Let&apos;s help you land more projects — start by updating your details.
                </p>
              </div>
              <div className="form-wrap">
                <form onSubmit={handleSubmit(onSubmit)}>
                  {error && (
                    <div className="alert alert-danger" role="alert">
                      {error}
                    </div>
                  )}
                  <div className="mb-20">
                    <label htmlFor="Email" className="form-label">
                      Email Address
                      {rememberedEmail && (
                        <small className="text-primary ms-2">
                          <i className="bi bi-check-circle"></i> Remembered
                        </small>
                      )}
                    </label>
                    <div className="input-icon">
                      <Image 
                        src="/assets/image/email.svg" 
                        className="icon" 
                        alt="email"
                        width={0}
                        height={0}
                        sizes="100vw"
                        style={{ width: 'auto', height: 'auto' }}
                      />
                      <input 
                        type="email" 
                        className={`form-control ${errors.email ? 'is-invalid' : ''} ${rememberedEmail ? 'border-primary' : ''}`}
                        id="Email" 
                        placeholder="Enter Email Address"
                        {...register('email')}
                        disabled={isLoading}
                      />
                    </div>
                    {errors.email && (
                      <div className="form-text error-text">{errors.email.message}</div>
                    )}
                    {rememberedEmail && !errors.email && (
                      <div className="form-text text-primary">
                        <small>This email was remembered from your last login</small>
                      </div>
                    )}
                  </div>
                  <div className="mb-20">
                    <label htmlFor="Password" className="form-label">Password</label>
                    <div className="input-icon">
                      <Image 
                        src="/assets/image/lock.svg" 
                        className="icon" 
                        alt="password"
                        width={0}
                        height={0}
                        sizes="100vw"
                        style={{ width: 'auto', height: 'auto' }}
                      />
                      <input 
                        type={showPassword ? 'text' : 'password'}
                        className={`form-control ${errors.password ? 'is-invalid' : ''}`}
                        id="Password" 
                        placeholder="Enter Password"
                        {...register('password')}
                        disabled={isLoading}
                      />
                      <div 
                        className="password-show-hide"
                        onClick={() => setShowPassword(!showPassword)}
                        style={{ cursor: 'pointer' }}
                      >
                        {/* <Image 
                          src="/assets/image/eye.svg" 
                          className="icon" 
                          alt="show/hide password"
                          width={0}
                          height={0}
                          sizes="100vw"
                          style={{ width: 'auto', height: 'auto' }}
                        /> */}

                        <Image 
                              src={showPassword ? "/assets/image/eye-slash.svg" : "/assets/image/eye.svg"} 
                              className="icon" 
                              alt={showPassword ? "hide password" : "show password"}
                              width={16}
                              height={16}
                            />
                      </div>
                    </div>
                    {errors.password && (
                      <div className="form-text error-text">{errors.password.message}</div>
                    )}
                  </div>
                  <div className="flex-box">
                    <div className="form-check form-switch">
                      <input 
                        className="form-check-input" 
                        type="checkbox" 
                        role="switch" 
                        id="remember"
                        {...register('remember')}
                        disabled={isLoading}
                      />
                      <label className="form-check-label" htmlFor="remember">
                        Remember Me
                      </label>
                    </div>
                    <Link href={`/${locale}/forgot-password`} className="forgot-link">
                      Forgot Password?
                    </Link>
                  </div>
                  <button 
                    type="submit" 
                    className="w-100 custom-btn secondary-btn"
                    disabled={isLoading}
                  >
                    {isLoading ? 'Logging in...' : 'Log in'}
                  </button>
                </form>
                <div className="form-sub-box">
                  <p>
                    Don&apos;t Have an Account?{' '}
                    <Link href={`/${locale}/signup`} className="primary-text">
                      Sign Up!
                    </Link>
                  </p>
                  <div className="line">
                    <span>OR</span>
                  </div>
                  <div className="social-media-account">
                    <ul>
                      <li>
                        <a 
                          href="#"
                          onClick={(e) => {
                            e.preventDefault();
                            handleSocialLogin('google');
                          }}
                          className="social-btn"
                        >
                          <Image 
                            src="/assets/image/google.svg" 
                            alt="google"
                            width={0}
                            height={0}
                            sizes="100vw"
                            style={{ width: 'auto', height: 'auto' }}
                          />
                        </a>
                      </li>
                      <li>
                        <a 
                          href="#"
                          onClick={(e) => {
                            e.preventDefault();
                            handleSocialLogin('facebook');
                          }}
                          className="social-btn"
                        >
                          <Image 
                            src="/assets/image/facebook.svg" 
                            alt="facebook"
                            width={0}
                            height={0}
                            sizes="100vw"
                            style={{ width: 'auto', height: 'auto' }}
                          />
                        </a>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
