'use client';

import { useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { signIn } from 'next-auth/react';
import { Database } from 'lucide-react';

export default function SignInClient() {
  const [authError, setAuthError] = useState('');
  const searchParams = useSearchParams();
  const error = searchParams.get('error');
  const reason = searchParams.get('reason');
  const callbackUrlParam = searchParams.get('callbackUrl') ?? '/';
  const callbackUrl = callbackUrlParam.startsWith('/') ? callbackUrlParam : '/';

  const noticeFromQuery =
    error === 'SessionRequired'
      ? 'Please sign in to continue.'
      : '';

  const errorFromQuery =
    error === 'NotAllowed' || error === 'AccessDenied'
      ? reason === 'missing_hosted_domain'
        ? 'This Google account does not appear to be a company-managed Workspace account. Please switch to your company Google account, or contact the administrator for help.'
        : 'Access is currently limited to approved company Google accounts. Please switch accounts or contact the administrator to request access.'
      : error === 'NotConfigured'
        ? 'Access control is not configured yet. If you are an administrator, set ALLOWED_GOOGLE_DOMAIN or ALLOWED_GOOGLE_EMAILS in the environment.'
        : error && error !== 'SessionRequired'
          ? `Sign-in failed (${error}). Please try again or contact the administrator.`
          : '';

  const handleSignIn = async () => {
    setAuthError('');

    try {
      await signIn('google', { callbackUrl });
    } catch (error) {
      console.error('Google sign-in failed', error);
      setAuthError('Google sign-in failed. Please try again.');
    }
  };

  return (
    <main className="min-h-screen bg-cream-200 text-warm-800 flex items-center justify-center px-6 relative overflow-hidden">
      {/* Subtle background pattern */}
      <div className="absolute inset-0 bg-gradient-to-br from-cream-100 via-cream-200 to-cream-300 opacity-50" />
      <div
        className="absolute inset-0 opacity-[0.02]"
        style={{
          backgroundImage: `radial-gradient(circle at 1px 1px, rgb(55 48 40) 1px, transparent 0)`,
          backgroundSize: '24px 24px',
        }}
      />

      {/* Content */}
      <div className="relative max-w-md w-full">
        {/* Card */}
        <div className="bg-white border border-cream-300 rounded-3xl shadow-warm-xl p-10 text-center animate-slide-up">
          {/* Logo */}
          <div className="mx-auto mb-6 w-14 h-14 rounded-2xl bg-gradient-to-br from-accent to-accent-600 flex items-center justify-center text-white shadow-lg shadow-accent/30">
            <Database className="w-6 h-6" />
          </div>

          {/* Title - using serif font */}
          <h1 className="heading-serif text-3xl text-warm-800 mb-3">FinOps Insight</h1>

          {/* Description */}
          <p className="text-sm text-warm-500 mb-8 leading-relaxed">
            Sign in with your company Google account to access the FinOps data agent.
          </p>

          {/* Sign In Button */}
          <button
            type="button"
            onClick={handleSignIn}
            className="w-full py-3.5 px-4 rounded-xl bg-warm-800 text-cream-100 font-semibold text-sm shadow-warm-lg hover:bg-warm-900 hover:shadow-warm-xl active:scale-[0.98] transition-all duration-200"
          >
            Sign in with Google
          </button>

          {/* Notice */}
          {noticeFromQuery && !authError && !errorFromQuery && (
            <div className="mt-5 rounded-xl border border-cream-300 bg-cream-50 px-4 py-3 text-left text-xs text-warm-600">
              {noticeFromQuery}
            </div>
          )}

          {/* Error message */}
          {(errorFromQuery || authError) && (
            <div className="mt-5 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-left text-xs text-red-700">
              {errorFromQuery || authError}
            </div>
          )}
        </div>

        {/* Footer text */}
        <p className="text-center mt-6 text-xs text-warm-400">Powered by BigQuery & Gemini</p>
      </div>
    </main>
  );
}
