import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Field, FieldDescription, FieldGroup, FieldLabel } from '@/components/ui/field';

// Google 'G' logo — inline SVG to avoid importing a second icon library.
function GoogleIcon({ className }: { className?: string }) {
  return (
    <svg className={className} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" 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>
  );
}

// ---------------------------------------------------------------------------
// Sign-in form (login-03 layout)
// ---------------------------------------------------------------------------

function SignInForm({
  className,
  onSwitchMode,
  ...props
}: React.ComponentPropsWithoutRef<'div'> & { onSwitchMode: () => void }) {
  const utils = trpc.useUtils();
  const { t } = useTranslation();
  const loginMutation = trpc.auth.login.useMutation();
  const oauthMutation = trpc.auth.loginWithOAuth.useMutation();
  const { notifyError } = useNotify();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');

  const isBusy = loginMutation.isPending || oauthMutation.isPending;

  function handleSubmit(e: React.SyntheticEvent) {
    e.preventDefault();
    if (!email || !password) return;
    setError('');
    loginMutation.mutate({ email, password }, {
      onSuccess: (res) => {
        if (!res.success) setError(res.error ?? 'Authentication failed');
        else void utils.auth.status.invalidate();
      },
      onError: (err) => {
        setError(err.message);
        notifyError('toast.auth.loginError', err);
      },
    });
  }

  function handleGoogleLogin() {
    setError('');
    oauthMutation.mutate({ provider: 'google' }, {
      onSuccess: (res) => {
        if (!res.success) setError(res.error ?? 'Google sign-in failed');
        else void utils.auth.status.invalidate();
      },
      onError: (err) => {
        setError(err.message);
        notifyError('toast.auth.oauthError', err);
      },
    });
  }

  return (
    <div className={cn('flex flex-col gap-6', className)} {...props}>
      <Card>
        <CardHeader className="text-center">
          <CardTitle className="text-xl">{t('auth.welcomeBack')}</CardTitle>
          <CardDescription>{t('auth.signInDescription')}</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid gap-6">
            {/* Email + password form */}
            <form onSubmit={handleSubmit}>
              <div className="grid gap-4">
                <div className="grid gap-2">
                  <Label htmlFor="email">{t('auth.email')}</Label>
                  <Input
                    id="email"
                    type="email"
                    placeholder="you@example.com"
                    value={email}
                    onChange={(e) => { setEmail(e.target.value); setError(''); }}
                    disabled={isBusy}
                    autoFocus
                    required
                  />
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="password">{t('auth.password')}</Label>
                  <Input
                    id="password"
                    type="password"
                    value={password}
                    onChange={(e) => { setPassword(e.target.value); setError(''); }}
                    disabled={isBusy}
                    required
                  />
                </div>
                {error && <p className="text-sm text-destructive -mt-1">{error}</p>}
                <Button type="submit" className="w-full" disabled={isBusy || !email || !password}>
                  {loginMutation.isPending ? (
                    <><Loader2 className="mr-2 size-4 animate-spin" /> {t('auth.signingIn')}</>
                  ) : t('auth.signIn')}
                </Button>
              </div>
            </form>

            {/* Divider */}
            <div className="relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t after:border-border">
              <span className="relative z-10 bg-card px-2 text-muted-foreground">
                {t('auth.or')}
              </span>
            </div>

            {/* Google OAuth button */}
            <Button
              type="button"
              variant="outline"
              className="w-full gap-2"
              onClick={handleGoogleLogin}
              disabled={isBusy}
            >
              {oauthMutation.isPending ? (
                <><Loader2 className="size-4 animate-spin" /> {t('auth.waitingForBrowser')}</>
              ) : (
                <><GoogleIcon className="size-4" /> {t('auth.signInWithGoogle')}</>
              )}
            </Button>

            <div className="text-center text-sm">
              {t('auth.noAccount')}{' '}
              <button type="button" className="underline underline-offset-4 hover:text-primary" onClick={onSwitchMode} disabled={isBusy}>
                {t('auth.signUp')}
              </button>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Sign-up form (signup-03 layout)
// ---------------------------------------------------------------------------

function SignUpForm({
  className,
  onSwitchMode,
  ...props
}: React.ComponentPropsWithoutRef<'div'> & { onSwitchMode: () => void }) {
  const utils = trpc.useUtils();
  const { t } = useTranslation();
  const registerMutation = trpc.auth.register.useMutation();
  const { notifyError } = useNotify();

  const [name, setName] = useState('');
  const [surname, setSurname] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');

  function handleSubmit(e: React.SyntheticEvent) {
    e.preventDefault();
    if (!email || !password) return;
    setError('');
    registerMutation.mutate({
      email,
      password,
      ...(name && { name }),
      ...(surname && { surname }),
    }, {
      onSuccess: (res) => {
        if (!res.success) setError(res.error ?? 'Registration failed');
        else void utils.auth.status.invalidate();
      },
      onError: (err) => {
        setError(err.message);
        notifyError('toast.auth.registerError', err);
      },
    });
  }

  return (
    <div className={cn('flex flex-col gap-6', className)} {...props}>
      <Card>
        <CardHeader className="text-center">
          <CardTitle className="text-xl">{t('auth.createAccount')}</CardTitle>
          <CardDescription>{t('auth.createAccountDescription')}</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit}>
            <FieldGroup>
              <div className="grid grid-cols-2 gap-3">
                <Field>
                  <FieldLabel htmlFor="reg-name">{t('auth.name')}</FieldLabel>
                  <Input
                    id="reg-name"
                    type="text"
                    placeholder="John"
                    value={name}
                    onChange={(e) => { setName(e.target.value); setError(''); }}
                    disabled={registerMutation.isPending}
                    autoFocus
                  />
                </Field>
                <Field>
                  <FieldLabel htmlFor="reg-surname">{t('auth.surname')}</FieldLabel>
                  <Input
                    id="reg-surname"
                    type="text"
                    placeholder="Doe"
                    value={surname}
                    onChange={(e) => { setSurname(e.target.value); setError(''); }}
                    disabled={registerMutation.isPending}
                  />
                </Field>
              </div>
              <Field>
                <FieldLabel htmlFor="reg-email">{t('auth.email')}</FieldLabel>
                <Input
                  id="reg-email"
                  type="email"
                  placeholder="you@example.com"
                  value={email}
                  onChange={(e) => { setEmail(e.target.value); setError(''); }}
                  disabled={registerMutation.isPending}
                  autoFocus
                  required
                />
              </Field>
              <Field>
                <Field>
                  <FieldLabel htmlFor="reg-password">{t('auth.password')}</FieldLabel>
                  <Input
                    id="reg-password"
                    type="password"
                    value={password}
                    onChange={(e) => { setPassword(e.target.value); setError(''); }}
                    disabled={registerMutation.isPending}
                    required
                  />
                </Field>
                <FieldDescription>Must be at least 8 characters long.</FieldDescription>
              </Field>
              {error && <p className="text-sm text-destructive">{error}</p>}
              <Field>
                <Button type="submit" className="w-full" disabled={registerMutation.isPending || !email || !password}>
                  {t('auth.createAccountButton')}
                </Button>
                <FieldDescription className="text-center">
                  {t('auth.haveAccount')}{' '}
                  <button type="button" className="underline underline-offset-4 hover:text-primary" onClick={onSwitchMode}>
                    {t('auth.signInLink')}
                  </button>
                </FieldDescription>
              </Field>
            </FieldGroup>
          </form>
        </CardContent>
      </Card>
      <FieldDescription className="px-6 text-center">
        By creating an account, you agree to our terms of service.
      </FieldDescription>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Shell — logo + mode switcher
// ---------------------------------------------------------------------------

export function LoginForm() {
  const [mode, setMode] = useState<'login' | 'register'>('login');

  return (
    <div className="flex w-full h-full flex-col items-center justify-center gap-6 bg-muted p-6 md:p-10">
      <div className="flex w-full max-w-sm flex-col gap-6">
        <div className="flex items-center self-center">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 180 70" fill="none" width="120" height="47">
            <style>{`
              .compass-needle-login {
                animation: compass-settle-login 5s ease-in-out infinite;
                transform-origin: 32px 32px;
              }
              @keyframes compass-settle-login {
                0%   { transform: rotate(0deg);  }
                20%  { transform: rotate(4deg);  }
                50%  { transform: rotate(-3deg); }
                80%  { transform: rotate(2deg);  }
                100% { transform: rotate(0deg);  }
              }
            `}</style>
            <g transform="translate(2,2)">
              <g className="compass-needle-login">
                <path d="M32,4 L48,32 L16,32 Z" fill="#fbc881"/>
                <path d="M16,32 L48,32 L32,60 Z" fill="currentColor"/>
                <line x1="16" y1="32" x2="48" y2="32" stroke="currentColor" strokeWidth="0.5" opacity="0.12"/>
                <circle cx="32" cy="32" r="2.5" fill="currentColor" opacity="0.18"/>
              </g>
            </g>
            <text x="65" y="42" fontFamily="Geist, system-ui, -apple-system, sans-serif" fontSize="30" letterSpacing="-0.5">
              <tspan fontWeight="400" fill="currentColor">adiuv</tspan><tspan fontWeight="700" fill="#fbc881">AI</tspan>
            </text>
          </svg>
        </div>
        {mode === 'login' ? (
          <SignInForm onSwitchMode={() => setMode('register')} />
        ) : (
          <SignUpForm onSwitchMode={() => setMode('login')} />
        )}
      </div>
    </div>
  );
}
