import { useState } from 'react'
import { Link, useNavigate, useLocation } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import { useToast } from '../context/ToastContext'

export default function Login() {
  const { login } = useAuth()
  const toast = useToast()
  const navigate = useNavigate()
  const location = useLocation()
  const [form, setForm] = useState({ email: '', password: '' })
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState('')

  const submit = async (e) => {
    e.preventDefault()
    setBusy(true)
    setError('')
    try {
      const user = await login(form)
      toast.success(`Welcome back, ${user.name}!`)
      navigate(location.state?.from || '/')
    } catch (err) {
      setError(err.response?.data?.message || 'Invalid credentials')
    } finally {
      setBusy(false)
    }
  }

  return (
    <AuthCard title="Welcome back" subtitle="Log in to continue">
      <form onSubmit={submit} className="space-y-4">
        {error && (
          <p className="rounded-lg bg-rose-50 px-3 py-2 text-sm text-rose-700 dark:bg-rose-900/30 dark:text-rose-300">
            {error}
          </p>
        )}
        <Field label="Email" type="email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} />
        <Field label="Password" type="password" value={form.password} onChange={(v) => setForm({ ...form, password: v })} />
        <button
          disabled={busy}
          className="w-full rounded-xl bg-[var(--brand)] py-2.5 font-semibold text-white transition hover:opacity-90 disabled:opacity-60"
        >
          {busy ? 'Logging in…' : 'Log in'}
        </button>
      </form>
      <p className="mt-4 text-center text-sm text-gray-500">
        No account?{' '}
        <Link to="/register" className="font-semibold text-[var(--brand)]">
          Register
        </Link>
      </p>
      {/* Dev-only helper — stripped from production builds. */}
      {import.meta.env.DEV && (
        <div className="mt-4 rounded-lg bg-gray-50 p-3 text-xs text-gray-500 dark:bg-gray-800/50">
          <b>Demo accounts</b> — admin@streamhub.test / password · user@streamhub.test / password
        </div>
      )}
    </AuthCard>
  )
}

export function AuthCard({ title, subtitle, children }) {
  return (
    <div className="mx-auto max-w-md py-10">
      <div className="rounded-2xl bg-white p-6 shadow-sm ring-1 ring-gray-100 dark:bg-gray-900 dark:ring-gray-800 sm:p-8">
        <h1 className="text-2xl font-extrabold">{title}</h1>
        <p className="mb-6 mt-1 text-sm text-gray-500">{subtitle}</p>
        {children}
      </div>
    </div>
  )
}

export function Field({ label, type = 'text', value, onChange }) {
  return (
    <label className="block">
      <span className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">{label}</span>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        required
        className="w-full rounded-xl border border-gray-200 bg-white px-3 py-2.5 outline-none transition focus:border-[var(--brand)] focus:ring-2 focus:ring-[var(--brand)]/30 dark:border-gray-700 dark:bg-gray-800"
      />
    </label>
  )
}
