'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Suspense } from 'react';
import { Mail, Lock, Eye, EyeOff, ArrowRight, Shield, Zap, TrendingUp, CheckCircle2, Crown } from 'lucide-react';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { authService } from '@/services/auth.service';
import { useAuthStore } from '@/store/auth.store';
import { getErrorMessage } from '@/lib/errors';
import { getLandingPath } from '@/lib/utils';
import type { AuthUser } from '@/store/auth.store';
import { useSystemConfig } from '@/hooks/useSystemConfig';
import TermsPopup from '@/components/popups/TermsPopup';
import ReferralPopup from '@/components/popups/ReferralPopup';

export default function LoginPageContent() {
  return (
    <Suspense fallback={<div className="min-h-screen" />}>
      <LoginInner />
    </Suspense>
  );
}



function LoginInner() {
  const router = useRouter();
  const sysConfig = useSystemConfig();
  const searchParams = useSearchParams();
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);

  const [requires2FA, setRequires2FA] = useState(false);
  const [twoFACode, setTwoFACode] = useState('');
  const [pendingLoginId, setPendingLoginId] = useState<string | null>(null);

  const [requiresTermsAcceptance, setRequiresTermsAcceptance] = useState(false);
  const [pendingTermsUser, setPendingTermsUser] = useState<AuthUser | null>(null);
  const [pendingTermsTokens, setPendingTermsTokens] = useState<{ accessToken: string; refreshToken?: string; sessionId?: string } | null>(null);

  const [showReferralPopup, setShowReferralPopup] = useState(false);
  const handleReferralClose = () => {
    setShowReferralPopup(false);
    const path = getLandingPath('USER');
    if (typeof window !== 'undefined') {
      window.location.assign(path);
    } else {
      router.replace(path);
    }
  };

  const setAuth = useAuthStore((s) => s.setAuth);

  useEffect(() => {
    const session = searchParams.get('session');
    if (session === 'expired') {
      setNotice('Your session has expired. Please sign in again.');
    } else if (session === 'unauthorized') {
      setNotice('Please sign in to continue.');
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const redirectByRole = (role: AuthUser['role']) => {
    const path = getLandingPath(role);
    if (typeof window !== 'undefined') {
      window.location.assign(path);
    } else {
      router.replace(path);
    }
  };

  const handlePrimarySubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setNotice(null);
    setLoading(true);
    try {
      const { data } = await authService.login({
        email,
        password,
        deviceName: navigator.userAgent ?? '',
        browser: typeof navigator !== 'undefined' ? navigator.userAgent : undefined,
      });

      const res = data?.data ?? {};

      if (data?.requiresEmailVerification || res.requiresEmailVerification) {
        setLoading(false);
        if (res?.requiresVerificationPage) {
          router.push('/verification');
        } else {
          setNotice(res.message ?? 'Email verification required. Please check your inbox.');
        }
        return;
      }

      if (data?.requiresTermsAcceptance || res.requiresTermsAcceptance) {
        setLoading(false);
        setPendingTermsUser(res.user as AuthUser);
        setPendingTermsTokens({
          accessToken: res.tokens?.accessToken,
          refreshToken: res.tokens?.refreshToken,
          sessionId: res.sessionId,
        });
        setRequiresTermsAcceptance(true);
        return;
      }

      if (data?.requiresTwoFA || res.requiresTwoFA) {
        setPendingLoginId(res.userId ?? null);
        setRequires2FA(true);
        setLoading(false);
        return;
      }

      const user = res.user as AuthUser;
      const tokens = res.tokens ?? {};
      const accessToken = tokens.accessToken;
      const refreshToken = tokens.refreshToken;

      if (!accessToken || !user?.role) {
        setError('Unable to complete sign in. Please try again.');
        setLoading(false);
        return;
      }

      if (res.requiresEmailVerification) {
        setNotice('Signed in. Please complete email verification to unlock all features.');
      }

      setAuth(accessToken, user.role, user, refreshToken, res.sessionId);
      setTimeout(() => redirectByRole(user.role), 100);
    } catch (err) {
      setError(getErrorMessage(err));
      setLoading(false);
    }
  };

  const handleTermsAccept = async () => {
    if (!pendingTermsUser || !pendingTermsTokens?.accessToken) {
      setError('Unable to complete sign in. Please try again.');
      setRequiresTermsAcceptance(false);
      return;
    }

    setError(null);
    setLoading(true);
    try {
      // Persist terms acceptance FIRST so the user is not redirected
      // (and possibly logged in) while the flag is still false in the DB.
      await authService.acceptTerms(pendingTermsTokens.accessToken);

      setAuth(
        pendingTermsTokens.accessToken,
        pendingTermsUser.role,
        { ...pendingTermsUser, hasAcceptedTerms: true },
        pendingTermsTokens.refreshToken,
        pendingTermsTokens.sessionId,
      );
      setTimeout(() => redirectByRole(pendingTermsUser.role), 100);
    } catch (err) {
      // Show the user the real error and close the popup so they can see
      // the message and retry. Previously the popup stayed open, masking
      // the error and leaving the user stuck on the login page.

      setError(getErrorMessage(err));
      setRequiresTermsAcceptance(false);
    } finally {
      setLoading(false);
    }
  };

  const handle2FASubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const { data } = await authService.verify2FALogin({
        code: twoFACode,
        userId: pendingLoginId ?? '',
      });

      const res = data?.data ?? {};

      if (data?.requiresTermsAcceptance || res.requiresTermsAcceptance) {
        setLoading(false);
        setPendingTermsUser(res.user as AuthUser);
        setPendingTermsTokens({
          accessToken: res.tokens?.accessToken,
          refreshToken: res.tokens?.refreshToken,
          sessionId: res.sessionId,
        });
        setRequiresTermsAcceptance(true);
        setRequires2FA(false);
        return;
      }

      const user = res.user as AuthUser;
      const tokens = res.tokens ?? {};
      const accessToken = tokens.accessToken;
      const refreshToken = tokens.refreshToken;

      if (!accessToken || !user?.role) {
        setError('Unable to complete sign in. Please try again.');
        setLoading(false);
        return;
      }

      if (res.requiresEmailVerification) {
        setNotice('Signed in. Please complete email verification to unlock all features.');
      }

      setAuth(accessToken, user.role, user, refreshToken, res.sessionId);
      redirectByRole(user.role);
    } catch (err) {
      setError(getErrorMessage(err));
      setLoading(false);
    }
  };

  return (
    <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-surface-sunken px-4 py-10">
      <div className="pointer-events-none absolute inset-0">
        <div className="absolute -left-40 -top-40 h-96 w-96 rounded-full bg-primary-500/20 blur-3xl" />
        <div className="absolute -bottom-40 -right-40 h-96 w-96 rounded-full bg-indigo-500/20 blur-3xl" />
        <div className="absolute inset-0 bg-grid opacity-40" />
      </div>

      <div className="relative grid w-full max-w-5xl grid-cols-1 gap-8 lg:grid-cols-2 lg:items-center">
        {/* Brand / marketing column */}
        <div className="hidden lg:block">
          <div className="mb-6 flex items-center gap-2">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-primary-500 to-indigo-600 text-white">
              <Shield className="h-5 w-5" />
            </div>
            <span className="text-xl font-bold text-ink">{sysConfig.projectName}</span>
          </div>
          <h1 className="text-4xl font-bold leading-tight tracking-tight text-ink">
            The modern way to manage your digital assets
          </h1>
          <p className="mt-4 text-lg text-ink-muted">
            Trade, invest, and grow your portfolio with a secure, enterprise-grade fintech platform.
          </p>
          <div className="mt-8 space-y-4">
            <FeatureItem icon={TrendingUp} title="Real-time portfolio tracking" desc="Instant updates on all your assets" />
            <FeatureItem icon={Zap} title="Lightning-fast trading" desc="Execute orders in milliseconds" />
            <FeatureItem icon={Shield} title="Bank-grade security" desc="Advanced encryption & 2FA protection" />
          </div>
          <div className="mt-8 flex items-center gap-4 text-sm text-ink-faint">
            <span className="flex items-center gap-1.5"><CheckCircle2 className="h-4 w-4 text-emerald-500" /> SOC 2 Ready</span>
            <span className="flex items-center gap-1.5"><CheckCircle2 className="h-4 w-4 text-emerald-500" /> 256-bit SSL</span>
            <span className="flex items-center gap-1.5"><CheckCircle2 className="h-4 w-4 text-emerald-500" /> 2FA Supported</span>
          </div>
        </div>

        {/* Auth card */}
        <div className="mx-auto w-full max-w-md">
          {!requiresTermsAcceptance && (
            <Card className="card-hover">
              <CardHeader>
                <CardTitle className="text-2xl">{requires2FA ? 'Two-Factor Authentication' : 'Welcome back'}</CardTitle>
                <CardDescription className="mt-2">
                  {requires2FA
                    ? 'Enter the verification code from your authenticator app to continue.'
                    : 'Sign in to your account to continue'}
                </CardDescription>
              </CardHeader>

              {notice && !requires2FA && (
                <div className="mx-5 mb-2 flex items-start gap-2 rounded-xl border border-primary-500/30 bg-primary-500/10 p-3 text-sm text-primary-700 dark:text-primary-300">
                  <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0" />
                  <span>{notice}</span>
                </div>
              )}

              {error && (
                <div className="mx-5 mb-2 flex items-start gap-2 rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-600 dark:text-red-300">
                  <span>{error}</span>
                </div>
              )}

              {requires2FA ? (
                <form onSubmit={handle2FASubmit}>
                  <CardContent className="space-y-4">
                    <div>
                      <label htmlFor="2fa" className="mb-1.5 block text-sm font-medium text-ink">Verification Code</label>
                      <Input
                        id="2fa"
                        value={twoFACode}
                        onChange={(e) => setTwoFACode(e.target.value)}
                        placeholder="6-digit code"
                        required
                        inputMode="numeric"
                        autoComplete="one-time-code"
                      />
                    </div>
                    <Button type="submit" className="w-full" loading={loading}>
                      {loading ? 'Verifying...' : 'Verify & Continue'}
                      {!loading && <ArrowRight className="h-4 w-4" />}
                    </Button>
                    <button
                      type="button"
                      onClick={() => {
                        setRequires2FA(false);
                        setTwoFACode('');
                        setPendingLoginId(null);
                      }}
                      className="w-full text-center text-sm font-medium text-primary-600 hover:underline"
                    >
                      Back to sign in
                    </button>
                  </CardContent>
                </form>
              ) : (
                <form onSubmit={handlePrimarySubmit}>
                  <CardContent className="space-y-4">
                    <div>
                      <label htmlFor="email" className="mb-1.5 block text-sm font-medium text-ink">Email</label>
                      <Input
                        id="email"
                        type="email"
                        placeholder="you@example.com"
                        icon={<Mail className="h-4 w-4" />}
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        required
                        autoComplete="email"
                      />
                    </div>
                    <div>
                      <div className="mb-1.5 flex items-center justify-between">
                        <label htmlFor="password" className="text-sm font-medium text-ink">Password</label>
                        <Link href="/forgot-password" className="text-xs font-medium text-primary-600 hover:underline">Forgot password?</Link>
                      </div>
                      <div className="relative">
                        <Input
                          id="password"
                          type={showPassword ? 'text' : 'password'}
                          placeholder="••••••••"
                          icon={<Lock className="h-4 w-4" />}
                          value={password}
                          onChange={(e) => setPassword(e.target.value)}
                          required
                          autoComplete="current-password"
                          className="pr-10"
                        />
                        <button
                          type="button"
                          onClick={() => setShowPassword((v) => !v)}
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-faint hover:text-ink"
                          aria-label={showPassword ? 'Hide password' : 'Show password'}
                        >
                          {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                        </button>
                      </div>
                    </div>
                    <label className="flex items-center gap-2 text-sm text-ink-muted">
                      <input
                        type="checkbox"
                        checked={rememberMe}
                        onChange={(e) => setRememberMe(e.target.checked)}
                        className="h-4 w-4 rounded border-line text-primary-600 focus:ring-primary-500"
                      />
                      Remember me
                    </label>
                    <Button type="submit" className="w-full" loading={loading}>
                      {loading ? 'Signing in...' : 'Sign In'}
                      {!loading && <ArrowRight className="h-4 w-4" />}
                    </Button>
                  </CardContent>
                </form>
              )}

              {!requires2FA && (
                <CardFooter className="flex-col gap-4">
                  <p className="text-center text-sm text-ink-muted">
                    Don&apos;t have an account?{' '}
                    <Link href="/register" className="font-semibold text-primary-600 hover:underline">Sign up</Link>
                  </p>
                  <p className="text-center text-sm text-ink-muted">
                    <Link href="/forgot-password" className="text-primary-600 hover:underline">Need help signing in?</Link>
                  </p>
                  <p className="text-center text-sm text-ink-muted">
                    <Link href="/superadmin-login" className="font-semibold text-amber-600 hover:underline flex items-center justify-center gap-1">
                      <Crown className="h-3.5 w-3.5" /> Super Admin Sign In
                    </Link>
                  </p>
                </CardFooter>
              )}
            </Card>
          )}
        </div>
      </div>

      <TermsPopup open={requiresTermsAcceptance} onAccept={handleTermsAccept} />
      <ReferralPopup open={showReferralPopup} onClose={handleReferralClose} onAccept={handleReferralClose} />
    </div>
  );
}

function FeatureItem({ icon: Icon, title, desc }: { icon: typeof Shield; title: string; desc: string }) {
  return (
    <div className="flex items-start gap-3">
      <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-primary-100 text-primary-600 dark:bg-primary-500/15 dark:text-primary-300">
        <Icon className="h-5 w-5" />
      </div>
      <div>
        <p className="font-semibold text-ink">{title}</p>
        <p className="text-sm text-ink-muted">{desc}</p>
      </div>
    </div>
  );
}
