'use client'

import { signIn } from 'next-auth/react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import AuthFormCloseButton from '@/components/auth/AuthFormCloseButton'
import { trackAnalyticsEvent } from '@/lib/analytics'

const inputClass =
  'w-full rounded-lg border border-gray-300 px-3 py-2 text-sm text-gray-900 shadow-sm focus:border-[color:var(--logo-color-dark)] focus:outline-none focus:ring-1 focus:ring-[color:var(--logo-color-dark)]'

function EyeIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinecap="round" strokeLinejoin="round" aria-hidden {...props}>
      <path d="M2 12s3.64-7 10-7 10 7 10 7-3.64 7-10 7-10-7-10-7Z" />
      <circle cx="12" cy="12" r="3.5" />
    </svg>
  )
}

function EyeOffIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinecap="round" strokeLinejoin="round" aria-hidden {...props}>
      <path d="M17.94 17.94A10.07 10.07 0 0 1 12 19c-6.36 0-10-7-10-7a21.94 21.94 0 0 1 5.17-6.53" />
      <path d="M9.9 5.24A9.67 9.67 0 0 1 12 5c6.36 0 10 7 10 7a21.32 21.32 0 0 1-2.16 3.19" />
      <path d="M14.12 14.12a3.5 3.5 0 1 1-4.24-4.24" />
      <line x1="2" x2="22" y1="2" y2="22" />
    </svg>
  )
}

export default function LoginForm({
  defaultCallbackUrl,
  initialEmail,
  variant = 'page',
  onAuthenticated,
  switchToRegister,
  registeredNotice,
  onEmailDraftChange,
}: {
  defaultCallbackUrl?: string
  initialEmail?: string
  variant?: 'page' | 'embedded'
  /** Po udanym logowaniu (np. w modalu) — zamknięcie modalu bez nawigacji zostaje w rodzicu */
  onAuthenticated?: () => void
  /** Wariant embedded: przejście do rejestracji w tym samym kontenerze */
  switchToRegister?: () => void
  /** Komunikat po utworzeniu konta (np. przejście z kroku rejestracji w modalu) */
  registeredNotice?: boolean
  /** Synchronizacja adresu przy przełączaniu kroków w modalu */
  onEmailDraftChange?: (email: string) => void
}) {
  const router = useRouter()
  const callbackUrl =
    defaultCallbackUrl && defaultCallbackUrl.startsWith('/') ? defaultCallbackUrl : '/profil'
  const embedded = variant === 'embedded'

  const [email, setEmail] = useState(initialEmail ?? '')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (typeof initialEmail === 'string') setEmail(initialEmail.trim())
  }, [initialEmail])

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError(null)
    setLoading(true)
    try {
      const res = await signIn('credentials', {
        email: email.trim(),
        password,
        redirect: false,
      })
      if (res?.error) {
        setError('Nieprawidłowy e-mail lub hasło.')
        setLoading(false)
        return
      }
      trackAnalyticsEvent('login', { method: 'email' })
      if (onAuthenticated) {
        onAuthenticated()
        return
      }
      router.push(callbackUrl.startsWith('/') ? callbackUrl : '/profil')
      router.refresh()
    } catch {
      setError('Wystąpił błąd. Spróbuj ponownie.')
      setLoading(false)
    }
  }

  return (
    <div
      className={
        embedded
          ? 'relative w-full'
          : 'relative mx-auto w-full max-w-md rounded-2xl border border-gray-200 bg-white p-8 pt-10 shadow-lg sm:pr-10'
      }
    >
      {!embedded ? <AuthFormCloseButton /> : null}
      {registeredNotice ? (
        <div className="mb-4 rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-center text-sm text-emerald-900">
          Konto zostało utworzone. Możesz się zalogować.
        </div>
      ) : null}
      {!embedded ? (
        <>
          <h1 className="pr-10 text-2xl font-bold text-gray-900 sm:pr-12">Logowanie</h1>
          <p className="mt-1 text-sm text-gray-600">Zaloguj się na swoje konto.</p>
        </>
      ) : null}

      <form onSubmit={onSubmit} className={`${embedded ? '' : 'mt-6'} space-y-4`}>
        {error ? (
          <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-800" role="alert">
            {error}
          </p>
        ) : null}

        <div>
          <label htmlFor="login-email" className="mb-1 block text-sm font-medium text-gray-700">
            E-mail
          </label>
          <input
            id="login-email"
            name="email"
            type="email"
            autoComplete="email"
            required
            value={email}
            onChange={(e) => {
              setEmail(e.target.value)
              onEmailDraftChange?.(e.target.value)
            }}
            className={inputClass}
          />
        </div>

        <div>
          <label htmlFor="login-password" className="mb-1 block text-sm font-medium text-gray-700">
            Hasło
          </label>
          <div className="flex w-full items-stretch rounded-lg border border-gray-300 bg-white shadow-sm focus-within:border-[color:var(--logo-color-dark)] focus-within:ring-1 focus-within:ring-[color:var(--logo-color-dark)]">
            <input
              id="login-password"
              name="password"
              type={showPassword ? 'text' : 'password'}
              autoComplete="current-password"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="min-w-0 flex-1 border-0 bg-transparent px-3 py-2 text-sm text-gray-900 outline-none focus:ring-0"
            />
            <button
              type="button"
              onClick={() => setShowPassword((v) => !v)}
              className="flex shrink-0 items-center justify-center border-l border-gray-200 px-3 text-gray-500 transition hover:bg-gray-50 hover:text-gray-800 focus-visible:z-10 focus-visible:outline focus-visible:ring-2 focus-visible:ring-[color:var(--logo-color-dark)] focus-visible:ring-offset-0"
              aria-label={showPassword ? 'Ukryj hasło' : 'Pokaż hasło'}
              aria-pressed={showPassword}
            >
              {showPassword ? <EyeOffIcon className="h-5 w-5" /> : <EyeIcon className="h-5 w-5" />}
            </button>
          </div>
        </div>

        <button
          type="submit"
          disabled={loading}
          className="w-full rounded-lg bg-[color:var(--logo-color-dark)] py-2.5 text-sm font-semibold text-white shadow transition hover:opacity-95 disabled:opacity-60"
        >
          {loading ? 'Logowanie…' : 'Zaloguj się'}
        </button>
      </form>

      <p className={`mt-6 text-center text-sm text-gray-600 ${embedded ? 'mt-5' : ''}`}>
        Nie masz konta?{' '}
        {embedded && switchToRegister ? (
          <button
            type="button"
            onClick={switchToRegister}
            className="font-medium text-[color:var(--logo-color-dark)] underline decoration-from-font underline-offset-2 hover:no-underline"
          >
            Zarejestruj się
          </button>
        ) : (
          <Link href="/rejestracja" className="font-medium text-[color:var(--logo-color-dark)] hover:underline">
            Zarejestruj się
          </Link>
        )}
      </p>
    </div>
  )
}
