'use client';

import { useState, useEffect, useRef, Suspense } from 'react';
import { useAuth } from '@/components/AuthContext';
import { useSearchParams, useRouter } from 'next/navigation';
import { Package, Eye, EyeOff, LogIn, AlertCircle, Mail, Lock, CheckCircle2, ChevronRight } from 'lucide-react';
import Link from 'next/link';

function LoginContent() {
  const { login, ssoLogin, loading: authLoading } = useAuth();
  const apiBase = process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8000/api';
  const backendBaseUrl = apiBase.replace(/\/api$/, '');
  const registerUrl = `${backendBaseUrl}/register`;

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [ssoLoading, setSsoLoading] = useState(false);
  const lastCalledToken = useRef<string | null>(null);

  const searchParams = useSearchParams();
  const ssoToken = searchParams.get('sso_token');

  useEffect(() => {
    if (ssoToken && lastCalledToken.current !== ssoToken) {
      lastCalledToken.current = ssoToken;
      handleSsoLogin(ssoToken);
    }
  }, [ssoToken]);

  const handleSsoLogin = async (token: string) => {
    setSsoLoading(true);
    setError('');
    
    try {
      // Clean query params immediately to prevent back-button token replays and infinite failure loops
      if (typeof window !== 'undefined') {
        const url = new URL(window.location.href);
        url.searchParams.delete('sso_token');
        window.history.replaceState({}, '', url.pathname);
      }
      await ssoLogin(token);
    } catch (err: unknown) {
      if (err && typeof err === 'object' && 'response' in err) {
        const axiosErr = err as { response?: { data?: { message?: string } } };
        setError(axiosErr.response?.data?.message || 'Login otomatis gagal. Silakan masuk manual.');
      } else {
        setError('Gagal melakukan login otomatis. Silakan masuk manual.');
      }
    } finally {
      setSsoLoading(false);
    }
  };

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

    try {
      await login(email, password);
    } catch (err: unknown) {
      if (err && typeof err === 'object' && 'response' in err) {
        const axiosErr = err as { response?: { data?: { message?: string } } };
        setError(axiosErr.response?.data?.message || 'Email atau password salah');
      } else {
        setError('Gagal terhubung ke server');
      }
    } finally {
      setLoading(false);
    }
  };

  if (authLoading || ssoLoading) {
    return (
      <div className="flex h-[100dvh] w-full items-center justify-center bg-slate-50">
        <div className="flex flex-col items-center gap-3">
          <div className="h-10 w-10 animate-spin rounded-full border-3 border-blue-100 border-t-[#005BFF]" />
          <p className="text-sm font-semibold text-[#005BFF]">
            {ssoLoading ? 'Memproses login otomatis ke kasir...' : 'Memuat...'}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-[100dvh] w-full bg-[#FAFBFD] overflow-x-hidden font-sans">
      <div className="flex w-full min-h-[100dvh]">
        
        {/* SISI KIRI: Branding & Visuals (Desktop Only - lg:flex) */}
        <div className="hidden lg:flex lg:flex-[1.1] bg-gradient-to-br from-[#0747a6] via-[#005BFF] to-[#0065ff] relative flex-col justify-between p-16 text-white overflow-hidden">
          
          {/* Decorative ambient glowing patterns */}
          <div className="absolute inset-0 pointer-events-none overflow-hidden">
            <div className="absolute -top-1/4 -left-1/4 w-[60%] h-[60%] rounded-full opacity-20"
              style={{ background: 'radial-gradient(circle, #FFFFFF 0%, transparent 60%)' }}
            />
            <div className="absolute -bottom-10 right-0 w-[40%] h-[40%] rounded-full opacity-15"
              style={{ background: 'radial-gradient(circle, #93C5FD 0%, transparent 70%)' }}
            />
          </div>

          {/* Left Header: Brand Logo */}
          <div className="relative z-10">
            <Link href="https://poskasir.my.id" className="inline-flex items-center gap-3 text-2xl font-extrabold tracking-tight text-white no-underline">
              <span className="w-10 h-10 bg-white/15 border border-white/25 rounded-xl flex items-center justify-center shadow-lg transition-transform hover:scale-105 duration-200">
                <Package className="h-5 w-5 text-white" />
              </span>
              POS Kasir
            </Link>
          </div>

          {/* Left Content: Key Features Highlight */}
          <div className="relative z-10 my-auto max-w-[500px]">
            <h2 className="text-4xl font-extrabold leading-tight tracking-tight mb-6 font-heading">
              Satu Akses Pintar untuk Cabang Toko Anda
            </h2>
            <p className="text-base text-white/85 mb-10 leading-relaxed font-light">
              Kembali ke dashboard kasir online untuk memantau transaksi real-time, mengelola stok multi-gudang, dan meninjau laba bersih berkala toko Anda.
            </p>

            <div className="flex flex-col gap-6">
              {/* Feature Item 1 */}
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0 w-6 h-6 rounded-full bg-white/20 border border-white flex items-center justify-center mt-1">
                  <CheckCircle2 className="h-3.5 w-3.5 text-white stroke-[3]" />
                </div>
                <div>
                  <h4 className="text-base font-bold mb-1">Transaksi POS & Kasir Cepat</h4>
                  <p className="text-sm text-white/80 leading-relaxed font-light">
                    Mendukung kasir cepat barcode scanner, open bill, dan diskon grosir otomatis.
                  </p>
                </div>
              </div>

              {/* Feature Item 2 */}
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0 w-6 h-6 rounded-full bg-white/20 border border-white flex items-center justify-center mt-1">
                  <CheckCircle2 className="h-3.5 w-3.5 text-white stroke-[3]" />
                </div>
                <div>
                  <h4 className="text-base font-bold mb-1">Stok & Mutasi FIFO Otomatis</h4>
                  <p className="text-sm text-white/80 leading-relaxed font-light">
                    Kalkulasi nilai persediaan barang dagangan akurat dengan mutasi HPP digital.
                  </p>
                </div>
              </div>

              {/* Feature Item 3 */}
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0 w-6 h-6 rounded-full bg-white/20 border border-white flex items-center justify-center mt-1">
                  <CheckCircle2 className="h-3.5 w-3.5 text-white stroke-[3]" />
                </div>
                <div>
                  <h4 className="text-base font-bold mb-1">Laporan Keuangan Terpadu</h4>
                  <p className="text-sm text-white/80 leading-relaxed font-light">
                    Dapatkan rekapan laba rugi bersih, biaya pengeluaran, dan penagihan piutang tempo.
                  </p>
                </div>
              </div>
            </div>
          </div>


        </div>

        {/* SISI KANAN: Form Login Minimalis Putih */}
        <div className="lg:flex-[0.9] bg-[#FAFBFD] lg:bg-white flex items-center justify-center p-6 sm:p-12 overflow-y-auto w-full">
          <div className="w-full max-w-[420px] bg-white p-8 sm:p-0 rounded-2xl lg:rounded-none border border-slate-100 lg:border-none shadow-xl lg:shadow-none animate-slide-up">
            
            {/* Mobile Brand Logo Header */}
            <div className="flex lg:hidden justify-center mb-8">
              <Link href="https://poskasir.my.id" className="inline-flex items-center gap-2.5 text-xl font-extrabold tracking-tight text-[#0F172A] no-underline">
                <span className="w-9 h-9 bg-[#005BFF] border border-[#005BFF]/10 rounded-lg flex items-center justify-center shadow-md">
                  <Package className="h-4.5 w-4.5 text-white" />
                </span>
                POS Kasir
              </Link>
            </div>

            <div className="mb-8 text-center lg:text-left">
              <h1 className="text-2xl font-extrabold text-[#0F172A] tracking-tight mb-2 font-heading">
                Masuk ke Aplikasi
              </h1>
              <p className="text-sm text-slate-500 font-medium">
                Gunakan akun kasir / owner terdaftar Anda.
              </p>
            </div>

            {/* Error Message Alert */}
            {error && (
              <div className="flex items-center gap-2.5 rounded-xl border border-red-200 bg-red-50/50 p-4 mb-6 text-sm text-red-600 shadow-sm animate-pulse-soft">
                <AlertCircle className="h-4.5 w-4.5 shrink-0" />
                <span className="font-semibold">{error}</span>
              </div>
            )}

            {/* Login Form */}
            <form onSubmit={handleSubmit} className="space-y-5">
              <div className="flex flex-col gap-1.5">
                <label className="text-xs font-bold text-slate-700 uppercase tracking-wider">
                  Alamat Email
                </label>
                <div className="relative flex items-center">
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="email@toko.com"
                    required
                    autoFocus
                    className="w-full rounded-xl border border-slate-200 bg-white py-3 pl-11 pr-4 text-sm text-slate-900 placeholder:text-slate-400 outline-none transition-all focus:border-[#005BFF] focus:ring-4 focus:ring-[#005BFF]/8"
                  />
                  <span className="absolute left-3.5 text-slate-400">
                    <Mail className="h-4.5 w-4.5" />
                  </span>
                </div>
              </div>

              <div className="flex flex-col gap-1.5">
                <label className="text-xs font-bold text-slate-700 uppercase tracking-wider">
                  Password
                </label>
                <div className="relative flex items-center">
                  <input
                    type={showPassword ? 'text' : 'password'}
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="Masukkan password"
                    required
                    className="w-full rounded-xl border border-slate-200 bg-white py-3 pl-11 pr-11 text-sm text-slate-900 placeholder:text-slate-400 outline-none transition-all focus:border-[#005BFF] focus:ring-4 focus:ring-[#005BFF]/8"
                  />
                  <span className="absolute left-3.5 text-slate-400">
                    <Lock className="h-4.5 w-4.5" />
                  </span>
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3.5 text-slate-400 hover:text-slate-600 transition-colors cursor-pointer"
                  >
                    {showPassword ? <EyeOff className="h-4.5 w-4.5" /> : <Eye className="h-4.5 w-4.5" />}
                  </button>
                </div>
              </div>

              {/* Submit Button */}
              <button
                type="submit"
                disabled={loading || !email || !password}
                className="flex w-full items-center justify-center gap-2 rounded-xl bg-[#005BFF] py-3 text-sm font-bold text-white shadow-lg shadow-[#005BFF]/15 transition-all hover:bg-[#004BEE] hover:shadow-xl hover:shadow-[#005BFF]/25 active:translate-y-0 duration-200 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed mt-6"
              >
                {loading ? (
                  <>
                    <div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
                    <span>Masuk ke Dasbor...</span>
                  </>
                ) : (
                  <>
                    <span>Masuk & Buka Kasir</span>
                    <ChevronRight className="h-4 w-4" />
                  </>
                )}
              </button>
            </form>

            {/* Redirect / Register link */}
            <p className="text-center text-sm text-slate-500 mt-8">
              Belum mendaftarkan toko?{' '}
              <a href="https://poskasir.my.id/" className="color-[#005BFF] font-semibold text-[#005BFF] no-underline hover:underline">
                Daftar uji coba gratis
              </a>
            </p>
          </div>
        </div>

      </div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={
      <div className="flex h-[100dvh] w-full items-center justify-center bg-slate-50">
        <div className="flex flex-col items-center gap-3">
          <div className="h-10 w-10 animate-spin rounded-full border-3 border-blue-100 border-t-[#005BFF]" />
          <p className="text-sm font-semibold text-[#005BFF]">Memuat...</p>
        </div>
      </div>
    }>
      <LoginContent />
    </Suspense>
  );
}
