'use client';

import {useState} from 'react';
import {useRouter} from 'next/navigation';
import Image from 'next/image';
import {BrandLogo, BrandMark} from '@/components/brand/BrandLogo';

const HERO_IMAGE_URL =
  'https://images.unsplash.com/photo-1556742049-0a670fc8078a?q=80&w=1400&auto=format&fit=crop';
const HERO_FALLBACK_URL =
  'https://images.unsplash.com/photo-1441986300917-64674bd600d8?q=80&w=1400&auto=format&fit=crop';

function GoogleIcon() {
  return (
    <svg width={18} height={18} viewBox="0 0 24 24">
      <path
        fill="#4285F4"
        d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
      />
      <path
        fill="#34A853"
        d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
      />
      <path
        fill="#FBBC05"
        d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l2.85-2.22.81-.63z"
      />
      <path
        fill="#EA4335"
        d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"
      />
    </svg>
  );
}

function MicrosoftIcon() {
  return (
    <svg width={18} height={18} viewBox="0 0 23 23">
      <path fill="#f35325" d="M1 1h10v10H1z" />
      <path fill="#81bc06" d="M12 1h10v10H1z" />
      <path fill="#05a6f0" d="M1 12h10v10H1z" />
      <path fill="#ffba08" d="M12 12h10v10H1z" />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg
      width={13}
      height={13}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      className="text-white"
    >
      <polyline points="20 6 9 17 4 12" />
    </svg>
  );
}

export function LoginSplit() {
  const router = useRouter();
  const [heroSrc, setHeroSrc] = useState(HERO_IMAGE_URL);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(false);
  const [errors, setErrors] = useState<{email?: string; password?: string}>({});
  const [isLoading, setIsLoading] = useState(false);

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    const next: typeof errors = {};
    if (!/^\S+@\S+\.\S+$/.test(email)) {
      next.email = 'Enter a valid email address';
    }
    if (password.length < 8) {
      next.password = 'Password must be at least 8 characters';
    }
    setErrors(next);
    if (Object.keys(next).length > 0) return;

    setIsLoading(true);
    setTimeout(() => {
      setIsLoading(false);
      router.push('/dashboard');
    }, 700);
  };

  return (
    <div className="min-h-screen w-full relative flex items-center justify-center p-4 sm:p-6 lg:p-10 bg-[#0C0D12] overflow-hidden selection:bg-white selection:text-black">
      {/* Rich Ambient Background Layers */}
      <div
        className="absolute inset-0 pointer-events-none"
        style={{
          backgroundImage: `
            radial-gradient(circle at 50% -10%, rgba(255, 255, 255, 0.09) 0%, transparent 55%),
            radial-gradient(circle at 85% 20%, rgba(245, 158, 11, 0.06) 0%, transparent 45%),
            radial-gradient(circle at 15% 80%, rgba(99, 102, 241, 0.06) 0%, transparent 50%)
          `,
        }}
      />
      <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,transparent_0%,rgba(0,0,0,0.6)_100%)] pointer-events-none" />

      {/* Main Split Container */}
      <div className="w-full max-w-[1360px] min-h-[760px] lg:h-[82vh] lg:max-h-[840px] rounded-[24px] bg-[#14151B]/95 border border-white/[0.1] shadow-[0_40px_100px_-20px_rgba(0,0,0,0.85)] backdrop-blur-2xl flex flex-col md:flex-row overflow-hidden relative z-10">
        
        {/* LEFT PANEL: Enterprise Visual (55% Desktop / 40% Tablet / Hidden Mobile) */}
        <div className="hidden md:flex md:w-[40%] lg:w-[55%] h-full p-3 relative">
          <div className="w-full h-full rounded-[20px] overflow-hidden relative border border-white/10 bg-[#090A0E]">
            {/* Main Retail Store Hero Image */}
            <Image
              src={heroSrc}
              alt="Loyaly Merchant Operating System"
              fill
              priority
              sizes="(max-width: 768px) 0vw, (max-width: 1024px) 40vw, 55vw"
              className="object-cover object-center"
              onError={() => {
                setHeroSrc(HERO_FALLBACK_URL);
              }}
            />

            {/* Subtle Gradient Overlays */}
            <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent pointer-events-none" />
            <div className="absolute inset-0 bg-gradient-to-l from-[#0E0E10]/70 via-transparent to-transparent pointer-events-none" />

            {/* Clean Enterprise Brand Watermark (Bottom-Left) */}
            <div className="absolute bottom-6 left-6 flex items-center gap-2.5 px-3.5 py-2 rounded-xl bg-black/50 backdrop-blur-md border border-white/10 text-white/80">
              <BrandMark size={16} priority />
              <span className="text-[11px] font-medium tracking-wide text-neutral-300">
                Loyaly.ai · Merchant Operating System
              </span>
            </div>
          </div>
        </div>

        {/* RIGHT PANEL: Authentication (45% Desktop / 60% Tablet / 100% Mobile) */}
        <div className="w-full md:w-[60%] lg:w-[45%] h-full p-8 sm:p-10 lg:p-12 flex flex-col justify-between overflow-y-auto">
          {/* Top Brand Header */}
          <div className="flex items-center justify-between gap-4 mb-8">
            <div className="flex items-center gap-3">
              <BrandLogo height={42} priority />
              <div className="h-4 w-px bg-white/20" />
              <span className="text-xs font-semibold tracking-wide text-neutral-400 uppercase">
                Merchant OS
              </span>
            </div>
            <span className="px-2.5 py-0.5 text-[10px] font-semibold tracking-wider uppercase rounded-full bg-white/[0.06] border border-white/10 text-neutral-300">
              v2.4 Enterprise
            </span>
          </div>

          {/* Form Content */}
          <div className="my-auto py-4">
            <div className="mb-8">
              <h1 className="text-3xl sm:text-4xl font-bold tracking-tight text-white mb-2.5">
                Welcome back
              </h1>
              <p className="text-sm text-neutral-400 leading-relaxed max-w-md">
                Access your Merchant Operating System to manage stores, rewards, staff and AI insights.
              </p>
            </div>

            <form onSubmit={handleLogin} noValidate className="space-y-4">
              <div>
                <label className="block text-xs font-medium text-neutral-300 mb-1.5">
                  Email address
                </label>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="name@company.com"
                  className={`w-full h-11 px-3.5 rounded-xl bg-white/[0.04] border ${
                    errors.email ? 'border-red-500/80' : 'border-white/10'
                  } text-white text-sm placeholder:text-neutral-500 focus:outline-none focus:border-white/30 focus:ring-1 focus:ring-white/20 transition-all`}
                />
                {errors.email && (
                  <p className="text-xs text-red-400 mt-1">{errors.email}</p>
                )}
              </div>

              <div>
                <label className="block text-xs font-medium text-neutral-300 mb-1.5">
                  Password
                </label>
                <input
                  type="password"
                  value={password}
                  onChange={(e) => {
                    setPassword(e.target.value);
                    setErrors({});
                  }}
                  placeholder="Enter your password"
                  className={`w-full h-11 px-3.5 rounded-xl bg-white/[0.04] border ${
                    errors.password ? 'border-red-500/80' : 'border-white/10'
                  } text-white text-sm placeholder:text-neutral-500 focus:outline-none focus:border-white/30 focus:ring-1 focus:ring-white/20 transition-all`}
                />
                {errors.password && (
                  <p className="text-xs text-red-400 mt-1">{errors.password}</p>
                )}
              </div>

              {/* Controls Row */}
              <div className="flex items-center justify-between pt-1">
                <label className="flex items-center gap-2 cursor-pointer group">
                  <input
                    type="checkbox"
                    checked={rememberMe}
                    onChange={(e) => setRememberMe(e.target.checked)}
                    className="w-4 h-4 rounded border-white/20 bg-white/5 text-white focus:ring-0 focus:ring-offset-0 cursor-pointer accent-white"
                  />
                  <span className="text-xs text-neutral-300 group-hover:text-white transition-colors">
                    Remember me
                  </span>
                </label>

                <a
                  href="#"
                  className="text-xs text-neutral-400 hover:text-white transition-colors font-medium"
                >
                  Forgot password?
                </a>
              </div>

              {/* Primary CTA */}
              <button
                type="submit"
                disabled={isLoading}
                className="w-full h-11 mt-2 rounded-xl bg-white text-black font-semibold text-sm hover:bg-neutral-200 active:scale-[0.99] transition-all shadow-md shadow-white/5 flex items-center justify-center gap-2 disabled:opacity-70"
              >
                {isLoading ? (
                  <span className="inline-block w-4 h-4 border-2 border-black/30 border-t-black rounded-full animate-spin" />
                ) : (
                  <>
                    Continue
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                      <path d="M5 12h14M12 5l7 7-7 7" />
                    </svg>
                  </>
                )}
              </button>

              {/* OAuth Divider */}
              <div className="relative my-5 text-center">
                <div className="absolute inset-0 flex items-center">
                  <div className="w-full border-t border-white/[0.08]" />
                </div>
                <span className="relative px-3 text-xs text-neutral-500 bg-[#14151B]">
                  or continue with
                </span>
              </div>

              {/* OAuth Buttons */}
              <div className="grid grid-cols-2 gap-3">
                <button
                  type="button"
                  className="h-11 rounded-xl bg-white/[0.04] border border-white/10 hover:bg-white/[0.08] hover:border-white/20 text-white text-xs font-medium transition-all flex items-center justify-center gap-2.5"
                >
                  <GoogleIcon />
                  Google
                </button>
                <button
                  type="button"
                  className="h-11 rounded-xl bg-white/[0.04] border border-white/10 hover:bg-white/[0.08] hover:border-white/20 text-white text-xs font-medium transition-all flex items-center justify-center gap-2.5"
                >
                  <MicrosoftIcon />
                  Microsoft
                </button>
              </div>
            </form>
          </div>

          {/* Bottom Footer Access Note */}
          <div className="pt-6 border-t border-white/[0.06] mt-4">
            <p className="text-xs text-neutral-400">
              Need access?{' '}
              <a href="#" className="text-white hover:underline font-medium">
                Contact your organization administrator.
              </a>
            </p>
          </div>
        </div>

      </div>

      {/* Page Footer Terms */}
      <div className="absolute bottom-3 text-center w-full pointer-events-auto">
        <p className="text-[11px] text-neutral-500">
          By continuing, you agree to Loyaly&apos;s{' '}
          <a href="#" className="text-neutral-400 hover:text-white transition-colors underline">
            Terms of Service
          </a>{' '}
          and{' '}
          <a href="#" className="text-neutral-400 hover:text-white transition-colors underline">
            Privacy Policy
          </a>
          .
        </p>
      </div>
    </div>
  );
}
