"use client";

import Image from "next/image";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useState, useRef } from "react";
import { signIn, signUp, verifyOtp } from '@/src/services/web/auth.services';
import { useCustomToast } from '@/src/hooks/web/useCustomToast';
import { z } from 'zod';

// Validation schemas
const signInSchema = z.object({
  signinEmail: z.string().email("Please enter a valid email address"),
});

const signUpSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters"),
  signupEmail: z.string().email("Please enter a valid email address"),
});

type SignInFormData = z.infer<typeof signInSchema>;
type SignUpFormData = z.infer<typeof signUpSchema>;

export default function WebAuth() {
  const router = useRouter();
  const { showToast } = useCustomToast();
  const otpRefs = useRef<Array<HTMLInputElement | null>>([]);
  
  const [loading, setLoading] = useState({ signin: false, signup: false, otp: false });
  const [step, setStep] = useState<'forms' | 'signin-otp' | 'signup-otp'>('forms');
  const [authData, setAuthData] = useState({ email: '', name: '', type: '' });
  const [otp, setOtp] = useState(['', '', '', '', '', '']);

  // Sign In Form Hook
  const {
    register: registerSignIn,
    handleSubmit: handleSubmitSignIn,
    formState: { errors: signinErrors },
  } = useForm<SignInFormData>({
    resolver: zodResolver(signInSchema),
    defaultValues: { signinEmail: "" },
  });

  // Sign Up Form Hook
  const {
    register: registerSignUp,
    handleSubmit: handleSubmitSignUp,
    formState: { errors: signupErrors },
  } = useForm<SignUpFormData>({
    resolver: zodResolver(signUpSchema),
    defaultValues: { name: "", signupEmail: "" },
  });

  const onSignInSubmit = async (data: SignInFormData) => {
    setLoading({ ...loading, signin: true });
    try {
      const response = await signIn({ email: data.signinEmail });
      if (response.data.success) {
        setAuthData({ email: data.signinEmail, name: '', type: 'signin' });
        setStep('signin-otp');
        showToast({
          title: 'Success',
          description: 'Verification code sent to your email',
          type: 'success',
        });
      } else {
        showToast({
          title: 'Error',
          description: response.data.error || 'Failed to send code',
          type: 'error',
        });
      }
    } catch (error: any) {
      if (error?.response?.status === 404) {
        showToast({
          title: 'Account Not Found',
          description: 'Email not registered. Please create an account first.',
          type: 'error',
        });
      } else {
        showToast({
          title: 'Error',
          description: error?.response?.data?.error || 'Failed to send code',
          type: 'error',
        });
      }
    } finally {
      setLoading({ ...loading, signin: false });
    }
  };

  const onSignUpSubmit = async (data: SignUpFormData) => {
    setLoading({ ...loading, signup: true });
    try {
      const response = await signUp({ 
        name: data.name, 
        email: data.signupEmail 
      });
      if (response.data.success) {
        setAuthData({ email: data.signupEmail, name: data.name, type: 'signup' });
        setStep('signup-otp');
        // showToast({
        //   title: 'Success',
        //   description: 'Verification code sent to your email',
        //   type: 'success',
        // });
      } else {
        showToast({
          title: 'Error',
          description: response.data.error || 'Failed to send code',
          type: 'error',
        });
      }
    } catch (error: any) {
      showToast({
        title: 'Error',
        description: error?.response?.data?.error || 'Failed to create account',
        type: 'error',
      });
    } finally {
      setLoading({ ...loading, signup: false });
    }
  };

  const handleOtpChange = (index: number, value: string) => {
    if (value.length > 1) return;
    
    const newOtp = [...otp];
    newOtp[index] = value;
    setOtp(newOtp);

    if (value && index < 5 && otpRefs.current[index + 1]) {
      otpRefs.current[index + 1]?.focus();
    }
  };

  const handleOtpKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Backspace' && !otp[index] && index > 0 && otpRefs.current[index - 1]) {
      otpRefs.current[index - 1]?.focus();
    }
  };

  const handleVerifyOtp = async () => {
    const otpString = otp.join('');
    if (otpString.length !== 6) {
      showToast({
        title: 'Error',
        description: 'Please enter the complete 6-digit code',
        type: 'error',
      });
      return;
    }

    setLoading({ ...loading, otp: true });
    try {
      const response = await verifyOtp({ email: authData.email, otp: otpString });
      if (response.data.success) {
        showToast({
          title: 'Success',
          description: authData.type === 'signup' ? 'Account created successfully!' : 'Login successful!',
          type: 'success',
        });
        router.push('/web-auth/welcome');
      } else {
        showToast({
          title: 'Error',
          description: response.data.error || 'Invalid verification code',
          type: 'error',
        });
      }
    } catch (error: any) {
      showToast({
        title: 'Error',
        description: error?.response?.data?.error || 'Verification failed',
        type: 'error',
      });
    } finally {
      setLoading({ ...loading, otp: false });
    }
  };

  const handleResendCode = async () => {
    if (authData.type === 'signin') {
      await signIn({ email: authData.email });
    } else {
      await signUp({ name: authData.name, email: authData.email });
    }
    showToast({
      title: 'Success',
      description: 'Verification code resent to your email',
      type: 'success',
    });
  };

  const handleBackToForms = () => {
    setStep('forms');
    setOtp(['', '', '', '', '', '']);
    setAuthData({ email: '', name: '', type: '' });
  };

  return (
    <div className="w-full p-5 bg-teal-500 relative overflow-hidden">
      <div
        className="relative z-10 min-h-[100vh] bg-white flex items-center justify-center px-4 sm:px-6 rounded-[5px] bg-no-repeat bg-cover"
        style={{ backgroundImage: "url('/onbording-bg.png')" }}
      >
        <div className="w-full max-w-xl md:max-w-4xl lg:max-w-6xl mt-5 pb-4">
          <div className="flex justify-center mb-6 mt-5">
            <Image src="/lhdc-logo.png" alt="Logo" width={170} height={100} priority />
          </div>
          
          <div className="text-center p-4 mb-8 md:mb-10 service-hs">
            <h2 className="text-lg font-semibold text-gray-800">
              Community Housing Services
            </h2>
            <p className="text-sm text-gray-500 mt-1 max-w-2xl mx-auto">
              Your centralized access to applications, maintenance requests &
              updates
            </p>
          </div>

          {step === 'forms' && (
            <div className="relative grid grid-cols-1 md:grid-cols-2 gap-10 md:gap-16">
              <div className="hidden md:block absolute left-1/2 top-0 h-full w-px border-l border-dashed border-teal-300" />

              {/* SIGN IN FORM */}
              <form onSubmit={handleSubmitSignIn(onSignInSubmit)} className="pe-0 lg:pe-[90px]">
                <h3 className="text-base font-semibold text-gray-800 mb-4">Sign In to Continue</h3>
                <label className="text-sm text-gray-600">Email Address</label>
                <input
                  {...registerSignIn("signinEmail")}
                  placeholder="Enter Email"
                  disabled={loading.signin}
                  className={`mt-1 w-full rounded-md border ${
                    signinErrors.signinEmail ? 'border-red-500' : 'border-gray-300'
                  } px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 disabled:bg-gray-100`}
                />
                {signinErrors.signinEmail && (
                  <p className="text-red-500 text-xs mt-1">{signinErrors.signinEmail.message}</p>
                )}

                <div className="flex items-start gap-2 mt-3">
                  <input type="checkbox" className="mt-1 accent-teal-600" />
                  <p className="text-xs text-gray-500">
                    A 6 digit security code will be sent via email to verify your account
                  </p>
                </div>

                <button 
                  type="submit" 
                  disabled={loading.signin} 
                  className="mt-5 w-full bg-teal-600 hover:bg-teal-700 text-white text-sm font-medium py-2.5 rounded-md transition disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {loading.signin ? "Sending..." : "Send Code"}
                </button>
              </form>

              {/* CREATE ACCOUNT FORM */}
              <form onSubmit={handleSubmitSignUp(onSignUpSubmit)} className="pl-0 md:pl-[90px]">
                <h3 className="text-base font-semibold text-gray-800 mb-4">Create Account</h3>
                
                <label className="text-sm text-gray-600">Full Name</label>
                <input
                  {...registerSignUp("name")}
                  placeholder="Enter Full Name"
                  disabled={loading.signup}
                  className={`mt-1 w-full rounded-md border ${
                    signupErrors.name ? 'border-red-500' : 'border-gray-300'
                  } px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 disabled:bg-gray-100`}
                />
                {signupErrors.name && (
                  <p className="text-red-500 text-xs mt-1">{signupErrors.name.message}</p>
                )}

                <label className="text-sm text-gray-600 mt-4 block">Email Address</label>
                <input
                  {...registerSignUp("signupEmail")}
                  placeholder="Enter Email Address"
                  disabled={loading.signup}
                  className={`mt-1 w-full rounded-md border ${
                    signupErrors.signupEmail ? 'border-red-500' : 'border-gray-300'
                  } px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 disabled:bg-gray-100`}
                />
                {signupErrors.signupEmail && (
                  <p className="text-red-500 text-xs mt-1">{signupErrors.signupEmail.message}</p>
                )}

                <div className="flex items-start gap-2 mt-3">
                  <input type="checkbox" className="mt-1 accent-teal-600" />
                  <p className="text-xs text-gray-500">
                    A 6 digit security code will be sent via email to verify your account
                  </p>
                </div>

                <button 
                  type="submit" 
                  disabled={loading.signup} 
                  className="mt-5 w-full bg-teal-600 hover:bg-teal-700 text-white text-sm font-medium py-2.5 rounded-md transition disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {loading.signup ? "Sending..." : "Send Code"}
                </button>
              </form>
            </div>
          )}

          {(step === 'signin-otp' || step === 'signup-otp') && (
            <div className="flex justify-center">
              <div className="w-full max-w-md bg-white p-6 rounded-lg">
                <div className="text-center mb-6">
                  <button
                    onClick={handleBackToForms}
                    className="text-teal-600 hover:text-teal-700 text-sm font-medium mb-4 flex items-center justify-center gap-2"
                  >
                    ← Back to {step === 'signin-otp' ? 'Sign In' : 'Create Account'}
                  </button>
                  
                  <h3 className="text-lg font-semibold text-gray-800 mb-2">
                    Check your inbox for the code
                  </h3>
                  
                  <p className="text-sm text-gray-500 mb-2">
                    A 6-digit verification code has been sent to:
                  </p>
                  
                  <p className="text-sm font-medium text-gray-700 mb-6">
                    {authData.email}
                  </p>
                </div>

                {/* OTP Inputs */}
                <div className="flex justify-between gap-2 mb-6">
                  {[...Array(6)].map((_, i) => (
                    <input
                      key={i}
                      ref={(el) => { otpRefs.current[i] = el; }}
                      type="text"
                      maxLength={1}
                      inputMode="numeric"
                      value={otp[i]}
                      onChange={(e) => handleOtpChange(i, e.target.value)}
                      onKeyDown={(e) => handleOtpKeyDown(i, e)}
                      disabled={loading.otp}
                      className="w-[14%] h-[50px] rounded-md border border-teal-400 text-center text-lg font-medium focus:outline-none focus:ring-2 focus:ring-teal-500 disabled:bg-gray-100"
                    />
                  ))}
                </div>

                <button
                  onClick={handleVerifyOtp}
                  disabled={loading.otp || otp.join('').length !== 6}
                  className="w-full bg-teal-600 hover:bg-teal-700 text-white text-sm font-medium py-2.5 rounded-md transition mb-4 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {loading.otp ? "Verifying..." : "Verify OTP"}
                </button>

                <p className="text-xs text-gray-500 text-center">
                  Didn't receive an email? Check your spam folder or{' '}
                  <button
                    onClick={handleResendCode}
                    disabled={loading.otp}
                    className="text-teal-600 hover:underline disabled:opacity-50"
                  >
                    resend code
                  </button>
                </p>
              </div>
            </div>
          )}

          {/* Footer */}
          <p className="text-center text-xs text-gray-400 mt-12">
            © 2025 LHDC. All rights reserved
          </p>
        </div>
      </div>
    </div>
  );
}