import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Eye, EyeOff, Loader2, AlertCircle, Server, User as UserIcon, Lock, ArrowRight } from '../lib/icons'
import { jellyfinClient, getLastServerUrl } from '../api/jellyfin'
import type { AuthState } from '../api/types'

interface Props {
  onLogin: (auth: AuthState) => void
}

export default function LoginPage({ onLogin }: Props) {
  const [serverUrl, setServerUrl] = useState(() => getLastServerUrl())
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError('')

    if (!serverUrl.trim()) {
      setError('Please enter a server URL')
      return
    }

    setLoading(true)
    try {
      jellyfinClient.connect(serverUrl.trim())
      const auth = await jellyfinClient.login(username.trim(), password)
      onLogin(auth)
    } catch (err: any) {
      setError(
        err?.response?.data?.message ||
          err?.message ||
          'Connection failed. Check your server URL and credentials.'
      )
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="absolute inset-0 flex items-center justify-center bg-void overflow-hidden">
      {/* Cinematic ambient backdrop */}
      <div className="absolute inset-0 -z-10">
        <div className="absolute top-[-30%] left-[-20%] w-[80%] h-[80%] rounded-full bg-accent/10 blur-[120px]" />
        <div className="absolute bottom-[-30%] right-[-20%] w-[70%] h-[70%] rounded-full bg-cool/8 blur-[120px]" />
        <div className="absolute inset-0 noise" />
      </div>

      <motion.div
        initial={{ opacity: 0, y: 16 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.6, ease: [0.16, 1, 0.3, 1] }}
        className="w-full max-w-[400px] mx-6 relative"
      >
        {/* Brand */}
        <div className="flex flex-col items-center mb-9">
          <motion.div
            initial={{ scale: 0.85, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            transition={{ duration: 0.5, ease: [0.34, 1.56, 0.64, 1], delay: 0.1 }}
            className="relative w-14 h-14 mb-4"
          >
            <div className="absolute inset-0 rounded-2xl bg-accent-glow blur-xl" />
            <div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-accent to-accent-press shadow-lg" />
            <div className="relative w-full h-full rounded-2xl grid place-items-center text-void font-bold text-2xl font-display">
              j
            </div>
          </motion.div>
          <motion.h1
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.25 }}
            className="font-display text-2xl font-semibold text-text-1 tracking-tight"
          >
            Welcome back
          </motion.h1>
          <motion.p
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.32 }}
            className="text-[13px] text-text-3 mt-1"
          >
            Connect to your server to begin
          </motion.p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-3">
          <Field
            label="Server URL"
            icon={Server}
            type="url"
            value={serverUrl}
            onChange={setServerUrl}
            placeholder="https://jellyfin.example.com"
            autoFocus={!serverUrl}
            delay={0.4}
          />

          <Field
            label="Username"
            icon={UserIcon}
            type="text"
            value={username}
            onChange={setUsername}
            placeholder="Your username"
            autoComplete="username"
            autoFocus={!!serverUrl}
            delay={0.45}
          />

          <Field
            label="Password"
            icon={Lock}
            type={showPassword ? 'text' : 'password'}
            value={password}
            onChange={setPassword}
            placeholder="Your password"
            autoComplete="current-password"
            delay={0.5}
            trailing={
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="text-text-4 hover:text-text-2 transition-colors p-1 rounded-md focus-ring"
                aria-label={showPassword ? 'Hide password' : 'Show password'}
              >
                {showPassword ? <EyeOff size={15} /> : <Eye size={15} />}
              </button>
            }
          />

          <AnimatePresence>
            {error && (
              <motion.div
                initial={{ opacity: 0, y: -4, height: 0 }}
                animate={{ opacity: 1, y: 0, height: 'auto' }}
                exit={{ opacity: 0, y: -4, height: 0 }}
                transition={{ duration: 0.22, ease: [0.16, 1, 0.3, 1] }}
                className="overflow-hidden"
              >
                <div className="flex items-start gap-2 p-3 rounded-lg bg-error/8 border border-error/20">
                  <AlertCircle size={14} className="text-error/90 shrink-0 mt-px" />
                  <p className="text-[12.5px] text-error/95 leading-relaxed">{error}</p>
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          <motion.button
            type="submit"
            disabled={loading}
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, delay: 0.55 }}
            whileTap={{ scale: 0.98 }}
            className="group relative w-full h-11 mt-2 bg-accent hover:bg-accent-hover text-void text-[14px] font-semibold rounded-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 shadow-lg shadow-accent/20 hover:shadow-accent/40 focus-ring"
          >
            {loading ? (
              <>
                <Loader2 size={15} className="animate-[spin-soft_0.8s_linear_infinite]" />
                Connecting...
              </>
            ) : (
              <>
                Sign in
                <ArrowRight
                  size={15}
                  className="transition-transform duration-200 group-hover:translate-x-0.5"
                />
              </>
            )}
          </motion.button>
        </form>

        <motion.p
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.7 }}
          className="text-center text-[11px] text-text-4 mt-6"
        >
          Your server connection stays on this device.
        </motion.p>
      </motion.div>
    </div>
  )
}

function Field({
  label,
  icon: Icon,
  type,
  value,
  onChange,
  placeholder,
  autoFocus,
  autoComplete,
  delay = 0,
  trailing,
}: {
  label: string
  icon: typeof Server
  type: string
  value: string
  onChange: (v: string) => void
  placeholder?: string
  autoFocus?: boolean
  autoComplete?: string
  delay?: number
  trailing?: React.ReactNode
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5, delay, ease: [0.16, 1, 0.3, 1] }}
    >
      <label className="block text-[11px] font-medium text-text-3 mb-1.5 uppercase tracking-wider">
        {label}
      </label>
      <div className="relative group">
        <Icon
          size={14}
          className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-4 group-focus-within:text-accent transition-colors duration-200"
        />
        <input
          type={type}
          value={value}
          onChange={e => onChange(e.target.value)}
          placeholder={placeholder}
          autoFocus={autoFocus}
          autoComplete={autoComplete}
          className={`w-full h-11 pl-10 ${trailing ? 'pr-10' : 'pr-3'} bg-elevated/60 hover:bg-elevated rounded-lg text-[13.5px] text-text-1 placeholder:text-text-4 border border-border focus:outline-none focus:border-accent/50 focus:ring-2 focus:ring-accent/20 focus:bg-elevated transition-all duration-200`}
        />
        {trailing && (
          <div className="absolute right-2 top-1/2 -translate-y-1/2">{trailing}</div>
        )}
      </div>
    </motion.div>
  )
}
