'use client';

import { useState } from 'react';
import Link from 'next/link';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/navigation';
import { GoogleLogin } from '@react-oauth/google';
import { useAuthStore } from '@/store/authStore';
import { useTranslations } from 'next-intl';

const AppleSignin = dynamic(() => import('react-apple-signin-auth'), { ssr: false });

const googleClientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || '';
const appleClientId = process.env.NEXT_PUBLIC_APPLE_CLIENT_ID || '';
const appUrl =
  process.env.NEXT_PUBLIC_APP_URL ||
  (typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3002');

type Mode = 'signin' | 'signup';

export default function SignInPage() {
  const router = useRouter();
  const { login, register, loginWithGoogle, loginWithApple } = useAuthStore();
  const t = useTranslations('auth');
  const tc = useTranslations('common');

  const [mode, setMode] = useState<Mode>('signin');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  function switchMode(next: Mode) {
    setMode(next);
    setError('');
    setEmail(next === 'signin' ? 'demo@example.com' : '');
    setPassword(next === 'signin' ? 'demo123' : '');
    setConfirmPassword('');
  }

  async function withLoading(fn: () => Promise<void>) {
    setError('');
    setIsLoading(true);
    try {
      await fn();
      // If we were redirected here from the pricing page with a plan pre-selected,
      // go back there so the checkout can auto-open.
      const params = new URLSearchParams(window.location.search);
      const plan = params.get('plan');
      const billing = params.get('billing');
      if (plan && billing) {
        router.push(`/pricing?plan=${plan}&billing=${billing}`);
      } else {
        router.push('/');
      }
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { error?: string } } })?.response?.data?.error ||
        (err instanceof Error ? err.message : 'Something went wrong');
      setError(msg);
    } finally {
      setIsLoading(false);
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (mode === 'signup') {
      if (password !== confirmPassword) {
        setError(t('errors.passwordMismatch'));
        return;
      }
      if (password.length < 6) {
        setError(t('errors.passwordTooShort'));
        return;
      }
      await withLoading(() => register(email, password));
    } else {
      await withLoading(() => login(email, password));
    }
  }

  async function handleGoogleSuccess(credentialResponse: { credential?: string }) {
    if (!credentialResponse.credential) return;
    await withLoading(() => loginWithGoogle(credentialResponse.credential!));
  }

  async function handleAppleSuccess(response: {
    authorization: { id_token: string; code: string };
  }) {
    await withLoading(() => loginWithApple(response.authorization.id_token));
  }

  const inputClass =
    'w-full px-4 py-2.5 border border-gray-200 rounded-lg bg-gray-50 text-sm outline-none focus:border-brand-purple focus:ring-1 focus:ring-brand-purple focus:bg-white transition';

  const isSignUp = mode === 'signup';

  return (
    <div className="min-h-screen flex">
      {/* ── Left panel — brand ── */}
      <div className="hidden lg:flex lg:w-1/2 bg-[#4C1D95] flex-col justify-between p-12 relative overflow-hidden">
        <div className="absolute top-0 right-0 w-80 h-80 rounded-full bg-gradient-to-br from-purple-500 via-pink-500 to-orange-400 opacity-30 translate-x-24 -translate-y-24" />
        <div className="absolute bottom-0 left-0 w-64 h-64 rounded-full bg-gradient-to-tr from-blue-500 via-purple-500 to-pink-500 opacity-20 -translate-x-16 translate-y-16" />
        <div className="absolute bottom-32 right-8 w-40 h-40 rounded-full bg-gradient-to-br from-teal-400 to-blue-500 opacity-20" />

        <Link href="/" className="flex items-center gap-3 relative z-10">
          <img src="/cahootravel-logo.svg" alt="CahooTravel" className="h-10 w-auto brightness-0 invert" />
          {/* <span className="text-white text-lg font-semibold">CahooTravel</span> */}
        </Link>

        <div className="relative z-10">
          <h2 className="text-3xl font-bold text-white leading-snug mb-4">
            {t('brandPanel.headingPrefix')}{' '}
            <span className="bg-gradient-to-r from-yellow-300 via-pink-300 to-blue-300 bg-clip-text text-transparent">
              {t('brandPanel.headingSpan')}
            </span>
          </h2>
          <p className="text-purple-200 text-sm leading-relaxed mb-8">
            {t('brandPanel.subheading')}
          </p>
          <ul className="flex flex-col gap-3">
            {[
              ['🌍', t('brandPanel.features.countries')],
              ['💸', t('brandPanel.features.deals')],
              ['📱', t('brandPanel.features.platforms')],
              ['🔒', t('brandPanel.features.secure')],
            ].map(([icon, text]) => (
              <li key={text} className="flex items-center gap-3 text-sm text-purple-100">
                <span>{icon}</span>
                <span>{text}</span>
              </li>
            ))}
          </ul>
        </div>

        <p className="text-purple-400 text-xs relative z-10">
          {tc('copyright', { year: new Date().getFullYear() })}
        </p>
      </div>

      {/* ── Right panel — form ── */}
      <div className="flex-1 flex flex-col items-center justify-center px-8 py-12 bg-white">
        {/* Mobile logo */}
        <div className="lg:hidden mb-8">
          <Link href="/">
            <img src="/cahootravel-logo.svg" alt="CahooTravel" className="h-10 w-auto" />
          </Link>
        </div>

        <div className="w-full max-w-sm">
          {/* Mode toggle tabs */}
          <div className="flex rounded-lg border border-gray-200 p-1 mb-7 gap-1">
            <button
              onClick={() => switchMode('signin')}
              className={`flex-1 py-2 text-sm font-medium rounded-md transition-colors ${
                !isSignUp
                  ? 'bg-brand-purple text-white shadow-sm'
                  : 'text-gray-500 hover:text-gray-700'
              }`}
            >
              {t('tabSignIn')}
            </button>
            <button
              onClick={() => switchMode('signup')}
              className={`flex-1 py-2 text-sm font-medium rounded-md transition-colors ${
                isSignUp
                  ? 'bg-brand-purple text-white shadow-sm'
                  : 'text-gray-500 hover:text-gray-700'
              }`}
            >
              {t('tabCreateAccount')}
            </button>
          </div>

          <h1 className="text-2xl font-bold text-gray-900 mb-1">
            {isSignUp ? t('headingSignUp') : t('headingSignIn')}
          </h1>
          <p className="text-sm text-gray-500 mb-7">
            {isSignUp
              ? t('subheadingSignUp')
              : t('subheadingSignIn')}
          </p>

          {error && (
            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-5 text-sm">
              {error}
            </div>
          )}

          {/* ── Email / password form ── */}
          <form onSubmit={handleSubmit} className="flex flex-col gap-4">
            <div>
              <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5">
                {t('emailLabel')}
              </label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className={inputClass}
                autoComplete="email"
                placeholder={t('emailPlaceholder')}
                required
              />
            </div>

            <div>
              <div className="flex items-center justify-between mb-1.5">
                <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide">
                  {t('passwordLabel')}
                </label>
                {!isSignUp && (
                  <a href="#" className="text-xs text-brand-purple hover:underline">
                    {t('forgotPassword')}
                  </a>
                )}
              </div>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className={inputClass}
                autoComplete={isSignUp ? 'new-password' : 'current-password'}
                placeholder={isSignUp ? t('passwordPlaceholderNew') : ''}
                required
              />
            </div>

            {isSignUp && (
              <div>
                <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5">
                  {t('confirmPasswordLabel')}
                </label>
                <input
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  className={inputClass}
                  autoComplete="new-password"
                  placeholder={t('confirmPasswordPlaceholder')}
                  required
                />
              </div>
            )}

            <button
              type="submit"
              disabled={isLoading}
              className="w-full bg-brand-purple hover:bg-purple-700 text-white font-semibold py-2.5 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed mt-1"
            >
              {isLoading
                ? isSignUp ? t('submittingSignUp') : t('submittingSignIn')
                : isSignUp ? t('submitSignUp') : t('submitSignIn')}
            </button>
          </form>

          {/* Divider */}
          <div className="flex items-center my-5">
            <div className="flex-1 border-t border-gray-200" />
            <span className="px-3 text-xs text-gray-400 uppercase tracking-wide">{t('orDivider')}</span>
            <div className="flex-1 border-t border-gray-200" />
          </div>

          {/* ── Social sign-in ── */}
          <div className="flex flex-col gap-3">
            {googleClientId ? (
              <div className="overflow-hidden">
                <GoogleLogin
                  onSuccess={handleGoogleSuccess}
                  onError={() => setError(t('errors.googleFailed'))}
                  width="384"
                  text={isSignUp ? 'signup_with' : 'continue_with'}
                  shape="rectangular"
                  logo_alignment="left"
                />
              </div>
            ) : (
              <button
                disabled
                title="Set NEXT_PUBLIC_GOOGLE_CLIENT_ID to enable Google Sign-In"
                className="w-full flex items-center justify-center gap-2.5 border border-gray-300 rounded-lg py-2.5 text-sm text-gray-400 cursor-not-allowed opacity-50"
              >
                <GoogleIcon />
                {isSignUp ? t('signUpGoogle') : t('continueGoogle')}
              </button>
            )}

            {appleClientId ? (
              <AppleSignin
                uiType="dark"
                authOptions={{
                  clientId: appleClientId,
                  scope: 'email name',
                  redirectURI: `${appUrl}/signin`,
                  state: Math.random().toString(36).substring(2),
                  nonce: Math.random().toString(36).substring(2),
                  usePopup: true,
                }}
                onSuccess={handleAppleSuccess}
                onError={(err: unknown) => {
                  console.error('Apple Sign-In error:', err);
                  setError(t('errors.appleFailed'));
                }}
                render={(props: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
                  <button
                    {...props}
                    disabled={isLoading}
                    className="w-full flex items-center justify-center gap-2.5 bg-black hover:bg-gray-900 rounded-lg py-2.5 text-sm text-white transition-colors disabled:opacity-50"
                  >
                    <AppleIcon />
                    {isSignUp ? t('signUpApple') : t('continueApple')}
                  </button>
                )}
              />
            ) : (
              <button
                disabled
                title="Set NEXT_PUBLIC_APPLE_CLIENT_ID to enable Apple Sign-In"
                className="w-full flex items-center justify-center gap-2.5 bg-black opacity-40 cursor-not-allowed rounded-lg py-2.5 text-sm text-white"
              >
                <AppleIcon />
                {isSignUp ? t('signUpApple') : t('continueApple')}
              </button>
            )}
          </div>

          {/* Demo credentials — only on sign-in */}
          {!isSignUp && (
            <button
              type="button"
              onClick={() => { setEmail('demo@example.com'); setPassword('demo123'); }}
              className="w-full mt-6 p-3 bg-gray-50 rounded-lg border border-gray-100 text-left hover:bg-gray-100 transition-colors"
            >
              <p className="text-xs text-gray-400 font-medium mb-0.5">{t('demoAccessLabel')}</p>
              <p className="text-xs text-gray-500 font-mono">{t('demoCredentials')}</p>
            </button>
          )}

          <p className="mt-6 text-center text-sm text-gray-500">
            {isSignUp ? (
              <>
                {t('alreadyHaveAccount')}{' '}
                <button onClick={() => switchMode('signin')} className="text-brand-purple font-medium hover:underline">
                  {t('signInLink')}
                </button>
              </>
            ) : (
              <>
                {t('noAccount')}{' '}
                <button onClick={() => switchMode('signup')} className="text-brand-purple font-medium hover:underline">
                  {t('createFreeLink')}
                </button>
              </>
            )}
          </p>
        </div>
      </div>
    </div>
  );
}

function GoogleIcon() {
  return (
    <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" aria-hidden="true">
      <path 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" fill="#4285F4" />
      <path 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" fill="#34A853" />
      <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05" />
      <path 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.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" />
    </svg>
  );
}

function AppleIcon() {
  return (
    <svg viewBox="0 0 24 24" className="w-4 h-4 fill-white" aria-hidden="true">
      <path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.8-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z" />
    </svg>
  );
}
