'use client';

import React, { useState, useEffect, Suspense } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuth } from '@/context/AuthContext';
import { Header } from '@/components/Header';
import { Footer } from '@/components/Footer';
import { Loader2, Lock, Mail, Smartphone, KeyRound, CheckCircle2, AlertCircle, Eye, EyeOff, User } from 'lucide-react';

function LoginPageContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirect = searchParams.get('redirect') || '/dashboard';
  const { user, login, sendOtp, verifyOtp, loading: authLoading } = useAuth();
  
  // Credentials Login States
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);
  const [error, setError] = useState('');
  const [submitting, setSubmitting] = useState(false);

  // OTP Login States
  const [phone, setPhone] = useState('');
  const [otpCode, setOtpCode] = useState('');
  const [otpSent, setOtpSent] = useState(false);
  const [otpTimer, setOtpTimer] = useState(0);
  const [otpMessage, setOtpMessage] = useState('');
  const [otpError, setOtpError] = useState('');
  const [otpSubmitting, setOtpSubmitting] = useState(false);

  // Redirect if already logged in
  useEffect(() => {
    if (user) {
      if (user.role === 'reseller') {
        router.push('/reseller/dashboard');
      } else {
        router.push(redirect);
      }
    }
  }, [user, router, redirect]);

  // OTP Resend Timer
  useEffect(() => {
    if (otpSent && otpTimer > 0) {
      const timer = setTimeout(() => setOtpTimer(prev => prev - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [otpSent, otpTimer]);

  const handleCredentialsSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSubmitting(true);

    try {
      await login({ email, password });
      router.push(redirect);
    } catch (err: any) {
      setError(err.errors?.email?.[0] || err.message || 'Login failed. Please check your credentials.');
    } finally {
      setSubmitting(false);
    }
  };

  const handleSendOtp = async (e: React.MouseEvent) => {
    e.preventDefault();
    setOtpError('');
    setOtpMessage('');
    
    // Validate Bangladeshi Phone Number Format
    const phoneRegex = /^(?:\+8801|8801|01)[3-9]\d{8}$/;
    if (!phoneRegex.test(phone)) {
      setOtpError('দয়া করে সঠিক মোবাইল নম্বর দিন (যেমন: 017XXXXXXXX)');
      return;
    }

    setOtpSubmitting(true);
    try {
      const res = await sendOtp(phone);
      setOtpSent(true);
      setOtpTimer(60);
      setOtpMessage(res.message || 'OTP successfully sent.');
    } catch (err: any) {
      setOtpError(err.message || 'OTP পাঠাতে ব্যর্থ হয়েছে। আবার চেষ্টা করুন।');
    } finally {
      setOtpSubmitting(false);
    }
  };

  const handleVerifyOtp = async (e: React.FormEvent) => {
    e.preventDefault();
    setOtpError('');
    
    if (!otpCode || otpCode.length < 4) {
      setOtpError('দয়া করে সঠিক ওটিপি (OTP) কোড দিন।');
      return;
    }

    setOtpSubmitting(true);
    try {
      await verifyOtp(phone, otpCode);
      router.push(redirect);
    } catch (err: any) {
      setOtpError(err.errors?.code?.[0] || err.message || 'ওটিপি মিলছে না। আবার চেষ্টা করুন।');
    } finally {
      setOtpSubmitting(false);
    }
  };

  const handleGoogleLogin = () => {
    alert('Google Login is currently in sandbox mode. Please use Phone OTP or Credentials to login.');
  };

  if (authLoading && !submitting && !otpSubmitting) {
    return (
      <>
        <Header />
        <main className="bg-slate-50 min-h-screen pt-4 sm:pt-12 pb-16 flex flex-col items-center justify-start animate-pulse">
          <div className="max-w-4xl w-full px-4 mt-2 sm:mt-6">
            <div className="bg-white border border-slate-200/60 rounded-3xl shadow-sm p-6 sm:p-8 space-y-6">
              
              {/* Top Signin Header Skeleton */}
              <div className="flex items-center justify-center gap-4 pb-6 border-b border-slate-100">
                <div className="h-12 w-12 rounded-2xl bg-slate-200"></div>
                <div className="text-left space-y-2 flex-1 max-w-[200px]">
                  <div className="h-7 bg-slate-300 rounded w-20"></div>
                  <div className="h-4 bg-slate-150 rounded w-36"></div>
                </div>
              </div>

              {/* Dual Panel Login Layout Skeleton */}
              <div className="grid grid-cols-1 lg:grid-cols-11 items-stretch gap-6 lg:gap-0">
                
                {/* Left Panel: Mobile OTP Login */}
                <div className="lg:col-span-5 bg-slate-50 border border-slate-200/50 p-6 rounded-2xl flex flex-col justify-between space-y-4">
                  <div className="space-y-4">
                    <div className="h-5 bg-slate-300 rounded w-36 pb-2 border-b border-slate-200/50"></div>
                    <div className="h-11 bg-white border border-slate-200 rounded-xl w-full"></div>
                    <div className="h-11 bg-slate-300 rounded-xl w-full"></div>
                  </div>
                  <div className="h-3.5 bg-slate-200 rounded w-full mt-4"></div>
                </div>

                {/* Center OR Column */}
                <div className="lg:col-span-1 flex items-center justify-center py-2 lg:py-0">
                  <div className="relative w-full lg:h-full flex lg:flex-col items-center justify-center">
                    <div className="hidden lg:block w-px bg-slate-200 h-full"></div>
                    <span className="bg-white border border-slate-200 rounded-full h-9 w-9 flex items-center justify-center text-xs text-slate-400 font-medium shadow-xs">OR</span>
                  </div>
                </div>

                {/* Right Panel: Credentials Login */}
                <div className="lg:col-span-5 bg-slate-50 border border-slate-200/50 p-6 rounded-2xl flex flex-col justify-between space-y-4">
                  <div className="space-y-4">
                    <div className="h-5 bg-slate-300 rounded w-36 pb-2 border-b border-slate-200/50"></div>
                    <div className="h-11 bg-white border border-slate-200 rounded-xl w-full"></div>
                    <div className="h-11 bg-white border border-slate-200 rounded-xl w-full"></div>
                    <div className="flex justify-between">
                      <div className="h-4 bg-slate-200 rounded w-20"></div>
                      <div className="h-4 bg-slate-200 rounded w-24"></div>
                    </div>
                    <div className="h-11 bg-slate-300 rounded-xl w-full"></div>
                  </div>
                  <div className="h-3.5 bg-slate-200 rounded w-full mt-4"></div>
                </div>

              </div>

              {/* Bottom Social Skeleton */}
              <div className="flex flex-col items-center justify-center pt-4 border-t border-slate-100 gap-5">
                <div className="h-4 bg-slate-200 rounded w-28"></div>
                <div className="h-12 w-12 rounded-full bg-slate-200"></div>
                <div className="h-4 bg-slate-200 rounded w-44"></div>
              </div>

            </div>
          </div>
        </main>
        <Footer />
      </>
    );
  }

  return (
    <>
      <Header />
      <main className="bg-slate-50 min-h-screen pt-4 sm:pt-12 pb-16 flex flex-col items-center justify-start">
        <div className="max-w-4xl w-full px-4 mt-2 sm:mt-6">
          <div className="bg-white border border-slate-200/60 rounded-3xl shadow-sm overflow-hidden p-6 sm:p-8 space-y-6">
            
            {/* Top Signin Logo & Header (Exactly as Ghorer Bazar screenshot - Slightly larger font size & unbolded) */}
            <div className="flex items-center justify-center gap-4 pb-6 border-b border-slate-100">
              <div className="h-12 w-12 rounded-2xl bg-secondary flex items-center justify-center text-white shadow-md shadow-secondary/20">
                {/* Custom keys icon or User icon */}
                <svg className="h-6 w-6 stroke-white fill-none" viewBox="0 0 24 24" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
                  <circle cx="9" cy="7" r="4" />
                  <path d="M22 11h-4" />
                  <path d="M22 15h-6" />
                </svg>
              </div>
              <div className="text-left">
                <h1 className="font-open-sans text-[18px] md:text-[24px] font-bold text-slate-800 leading-tight">Signin</h1>
                <p className="font-open-sans text-[14px] font-normal text-slate-500 mt-1">Access your account securely</p>
              </div>
            </div>

            {/* Error alerts */}
            {(error || otpError) && (
              <div className="bg-rose-50 border border-rose-250 text-rose-600 px-4 py-3 rounded-2xl text-sm font-medium flex items-center gap-2.5">
                <AlertCircle className="h-5 w-5 shrink-0" />
                <span>{error || otpError}</span>
              </div>
            )}

            {/* Success alerts */}
            {otpMessage && (
              <div className="bg-emerald-50 border border-emerald-250 text-emerald-700 px-4 py-3 rounded-2xl text-sm font-medium flex items-start gap-2.5">
                <CheckCircle2 className="h-5 w-5 shrink-0 text-emerald-600 mt-0.5" />
                <span>{otpMessage}</span>
              </div>
            )}

            {/* Dual Panel Login Layout */}
            <div className="grid grid-cols-1 lg:grid-cols-11 items-stretch gap-6 lg:gap-0">
              
              {/* Left Column: Login with Mobile Number */}
              <div className="lg:col-span-5 bg-slate-50 border border-slate-200/50 p-6 rounded-2xl flex flex-col justify-between">
                <div>
                  <h2 className="font-open-sans text-[15px] md:text-[16px] font-semibold text-slate-800 mb-5 pb-2 border-b border-slate-200/50">
                    Login With Mobile Number
                  </h2>

                  {!otpSent ? (
                    <div className="space-y-4">
                      <div className="relative">
                        <span className="absolute left-3.5 top-3.5 text-slate-400">
                          <Smartphone className="h-5 w-5 text-secondary" />
                        </span>
                        <input
                          type="tel"
                          required
                          placeholder="01*********"
                          value={phone}
                          onChange={(e) => setPhone(e.target.value)}
                          className="w-full font-open-sans text-[14px] font-normal pl-11 pr-4 py-3 bg-white border border-slate-200 rounded-xl focus:border-secondary focus:ring-1 focus:ring-secondary focus:outline-none font-mono"
                        />
                      </div>

                      <button
                        type="button"
                        onClick={handleSendOtp}
                        disabled={otpSubmitting || !phone}
                        className="w-full py-3 bg-secondary hover:bg-secondary-dark disabled:opacity-50 text-white font-open-sans text-[15px] font-semibold rounded-xl shadow-xs transition-colors cursor-pointer"
                      >
                        {otpSubmitting ? (
                          <span className="flex items-center justify-center gap-2">
                            <Loader2 className="h-4 w-4 animate-spin" />
                            Sending...
                          </span>
                        ) : (
                          <span>Send OTP</span>
                        )}
                      </button>
                    </div>
                  ) : (
                    <form onSubmit={handleVerifyOtp} className="space-y-4">
                      <div className="relative">
                        <span className="absolute left-3.5 top-3.5 text-slate-400">
                          <KeyRound className="h-5 w-5 text-secondary" />
                        </span>
                        <input
                          type="text"
                          required
                          maxLength={6}
                          placeholder="Enter OTP Code"
                          value={otpCode}
                          onChange={(e) => setOtpCode(e.target.value)}
                          className="w-full font-open-sans text-[14px] font-normal pl-11 pr-4 py-3 bg-white border border-slate-200 rounded-xl focus:border-secondary focus:ring-1 focus:ring-secondary focus:outline-none tracking-widest text-center font-mono"
                        />
                      </div>

                      <div className="flex justify-between items-center font-open-sans text-[13px] md:text-[14px] font-medium text-slate-500">
                        <span>Mobile: <strong className="font-mono text-slate-700">{phone}</strong></span>
                        {otpTimer > 0 ? (
                          <span>Resend in {otpTimer}s</span>
                        ) : (
                          <button
                            type="button"
                            onClick={handleSendOtp}
                            className="text-secondary hover:underline cursor-pointer font-semibold"
                          >
                            Resend OTP
                          </button>
                        )}
                      </div>

                      <div className="flex gap-2">
                        <button
                          type="button"
                          onClick={() => {
                            setOtpSent(false);
                            setOtpCode('');
                            setOtpError('');
                            setOtpMessage('');
                          }}
                          className="w-1/3 py-3 border border-slate-200 hover:bg-white text-slate-600 font-open-sans text-[13px] md:text-[14px] font-medium rounded-xl transition-colors cursor-pointer bg-white"
                        >
                          Back
                        </button>
                        <button
                          type="submit"
                          disabled={otpSubmitting || otpCode.length < 4}
                          className="w-2/3 py-3 bg-secondary hover:bg-secondary-dark disabled:opacity-50 text-white font-open-sans text-[15px] font-semibold rounded-xl shadow-xs transition-colors cursor-pointer"
                        >
                          {otpSubmitting ? (
                            <span className="flex items-center justify-center gap-2">
                              <Loader2 className="h-4 w-4 animate-spin" />
                              Verifying...
                            </span>
                          ) : (
                            <span>Verify & Login</span>
                          )}
                        </button>
                      </div>
                    </form>
                  )}
                </div>

                <div className="font-open-sans text-[13px] font-normal text-slate-400 mt-6 leading-relaxed">
                  * Password-free login. First time login automatically creates a new account.
                </div>
              </div>

              {/* Center OR Separator Column */}
              <div className="lg:col-span-1 flex items-center justify-center py-2 lg:py-0">
                <div className="relative w-full lg:h-full flex lg:flex-col items-center justify-center">
                  <div className="hidden lg:block w-px bg-slate-200 h-full"></div>
                  <div className="lg:hidden h-px bg-slate-200 w-full"></div>
                  <span className="absolute bg-white border border-slate-200 rounded-full h-9 w-9 flex items-center justify-center text-xs font-medium text-slate-400 shadow-xs">
                    OR
                  </span>
                </div>
              </div>

              {/* Right Column: Login with Credentials */}
              <div className="lg:col-span-5 bg-slate-50 border border-slate-200/50 p-6 rounded-2xl flex flex-col justify-between">
                <form onSubmit={handleCredentialsSubmit} className="space-y-4">
                  <h2 className="font-open-sans text-[15px] md:text-[16px] font-semibold text-slate-800 mb-1">
                    Login With Credentials
                  </h2>
                  <div className="h-0.5 bg-slate-200/50 mb-5"></div>
                  
                  {/* Email Input */}
                  <div className="relative">
                    <span className="absolute left-3.5 top-3.5 text-slate-400">
                      <User className="h-5 w-5 text-secondary" />
                    </span>
                    <input
                      type="email"
                      required
                      placeholder="Email or phone number"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="w-full font-open-sans text-[14px] font-normal pl-11 pr-4 py-3 bg-white border border-slate-200 rounded-xl focus:border-secondary focus:ring-1 focus:ring-secondary focus:outline-none"
                    />
                  </div>

                  {/* Password Input */}
                  <div className="relative">
                    <span className="absolute left-3.5 top-3.5 text-slate-400">
                      <Lock className="h-5 w-5 text-secondary" />
                    </span>
                    <input
                      type={showPassword ? 'text' : 'password'}
                      required
                      placeholder="Password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="w-full font-open-sans text-[14px] font-normal pl-11 pr-10 py-3 bg-white border border-slate-200 rounded-xl focus:border-secondary focus:ring-1 focus:ring-secondary focus:outline-none"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-3.5 text-slate-400 hover:text-slate-600 focus:outline-none"
                    >
                      {showPassword ? (
                        <EyeOff className="h-5 w-5" />
                      ) : (
                        <Eye className="h-5 w-5" />
                      )}
                    </button>
                  </div>

                  {/* Remember Me and Forgot Password */}
                  <div className="flex items-center justify-between font-open-sans text-[13px] md:text-[14px] font-normal">
                    <label className="flex items-center gap-1.5 text-slate-500 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={rememberMe}
                        onChange={(e) => setRememberMe(e.target.checked)}
                        className="rounded border-slate-300 text-secondary focus:ring-secondary h-4 w-4"
                      />
                      <span>Remember me</span>
                    </label>
                    <Link href="/forgot-password" className="text-secondary hover:underline font-semibold">
                      Forgotten password?
                    </Link>
                  </div>

                  {/* Submit Button */}
                  <button
                    type="submit"
                    disabled={submitting}
                    className="w-full py-3 bg-secondary hover:bg-secondary-dark disabled:opacity-50 text-white font-open-sans text-[15px] font-semibold rounded-xl shadow-xs transition-colors cursor-pointer"
                  >
                    {submitting ? (
                      <span className="flex items-center justify-center gap-2">
                        <Loader2 className="h-4 w-4 animate-spin" />
                        Logging in...
                      </span>
                    ) : (
                      <span>Login</span>
                    )}
                  </button>
                </form>

                <div className="font-open-sans text-[13px] font-normal text-slate-400 mt-6 leading-relaxed">
                  * Authenticate using your registered email and secure password.
                </div>
              </div>

            </div>

            {/* Bottom social login (or signin with Google) */}
            <div className="flex flex-col items-center justify-center pt-4 border-t border-slate-100 gap-5">
              
              <div className="relative w-full flex items-center justify-center">
                <div className="absolute inset-0 flex items-center">
                  <div className="w-full border-t border-slate-100"></div>
                </div>
                <span className="relative bg-white px-4 text-xs font-medium text-slate-400 tracking-wider uppercase">
                  or signin with
                </span>
              </div>

              {/* Circular Google login icon wrapper */}
              <button
                onClick={handleGoogleLogin}
                className="h-12 w-12 rounded-full border border-slate-200 hover:bg-slate-50 flex items-center justify-center shadow-xs transition-all bg-white cursor-pointer"
                title="Sign in with Google"
              >
                <svg className="h-5 w-5" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path d="M21.35,11.1H12v2.7h5.38c-0.24,1.28 -0.96,2.37 -2.04,3.1v2.57h3.3c1.93,-1.78 3.04,-4.4 3.04,-7.43c0,-0.34 -0.03,-0.67 -0.08,-0.94Z" fill="#4285f4" />
                  <path d="M12,20.7c2.35,0 4.32,-0.78 5.76,-2.12l-3.3,-2.57c-0.91,0.61 -2.08,0.97 -3.46,0.97c-2.66,0 -4.92,-1.8 -5.72,-4.21H1.83v2.57c1.44,2.86 4.39,4.8 7.85,4.8Z" fill="#34a853" />
                  <path d="M6.28,12.77c-0.2,-0.61 -0.32,-1.27 -0.32,-1.94s0.12,-1.33 0.32,-1.94V6.32H1.83c-0.67,1.34 -1.05,2.85 -1.05,4.45s0.38,3.11 1.05,4.45l4.45,-3.45Z" fill="#fbbc05" />
                  <path d="M12,5.2c1.28,0 2.43,0.44 3.34,1.3l2.5,-2.5C16.31,2.56 14.34,1.8 12,1.8c-3.46,0 -6.41,1.94 -7.85,4.8l4.45,3.45c0.8,-2.41 3.06,-4.21 5.72,-4.21Z" fill="#ea4335" />
                </svg>
              </button>

              <div className="font-open-sans text-[14px] font-normal text-slate-500">
                Don&apos;t have any account?{' '}
                <Link href="/register" className="font-semibold text-secondary hover:underline">
                  Register account
                </Link>
              </div>

            </div>

          </div>
        </div>
      </main>
      <Footer />
    </>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center bg-slate-50">
        <Loader2 className="h-8 w-8 animate-spin text-secondary" />
      </div>
    }>
      <LoginPageContent />
    </Suspense>
  );
}
