'use client'
import React, { useState } from 'react'
import { useRouter } from 'next/navigation'
import { pb } from '@/lib/pocketbase'
import { syncAuthCookies } from '@/lib/auth'
import { Button } from '@/components/ui/Button'
import type { PBUser } from '@/types'

export default function AuthPage() {
  const router = useRouter()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (!email || !password) return

    setLoading(true)
    setError(null)

    try {
      await pb.collection('users').authWithPassword(email, password)
      syncAuthCookies()

      const user = pb.authStore.model as PBUser | null
      if (user?.role === 'admin') {
        router.push('/admin')
      } else {
        router.push('/app')
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Login failed. Check your credentials.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <main
      style={{
        minHeight: '100dvh',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 'var(--s-5)',
        background: 'var(--bg)',
      }}
    >
      <div
        style={{
          width: '100%',
          maxWidth: '400px',
          display: 'flex',
          flexDirection: 'column',
          gap: 'var(--s-6)',
        }}
      >
        {/* Logo / brand */}
        <div style={{ textAlign: 'center' }}>
          <div
            style={{
              width: '64px',
              height: '64px',
              borderRadius: '50%',
              background: 'var(--bg-dark)',
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: 'var(--paper)',
              fontSize: 'var(--t-h3)',
              fontWeight: 700,
              marginBottom: 'var(--s-4)',
            }}
          >
            L
          </div>
          <h1
            style={{
              margin: '0 0 var(--s-2)',
              fontSize: 'var(--t-h3)',
              fontWeight: 700,
              color: 'var(--fg)',
            }}
          >
            Learning Platform
          </h1>
          <p style={{ margin: 0, fontSize: 'var(--t-body)', color: 'var(--fg-muted)' }}>
            Sign in to continue
          </p>
        </div>

        {/* Form */}
        <form
          onSubmit={(e) => void handleSubmit(e)}
          style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-4)' }}
        >
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-2)' }}>
            <label
              htmlFor="email"
              style={{
                fontSize: 'var(--t-small)',
                fontWeight: 600,
                color: 'var(--fg)',
              }}
            >
              Email
            </label>
            <input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              autoComplete="email"
              placeholder="you@company.com"
              style={{
                width: '100%',
                borderRadius: 'var(--r-sm)',
                border: '1.5px solid var(--cream)',
                padding: 'var(--s-3) var(--s-4)',
                fontSize: 'var(--t-body)',
                fontFamily: 'var(--font-sans)',
                color: 'var(--fg)',
                background: 'var(--bg)',
                outline: 'none',
                minHeight: '44px',
                boxSizing: 'border-box',
              }}
            />
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-2)' }}>
            <label
              htmlFor="password"
              style={{
                fontSize: 'var(--t-small)',
                fontWeight: 600,
                color: 'var(--fg)',
              }}
            >
              Password
            </label>
            <input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              autoComplete="current-password"
              placeholder="••••••••"
              style={{
                width: '100%',
                borderRadius: 'var(--r-sm)',
                border: '1.5px solid var(--cream)',
                padding: 'var(--s-3) var(--s-4)',
                fontSize: 'var(--t-body)',
                fontFamily: 'var(--font-sans)',
                color: 'var(--fg)',
                background: 'var(--bg)',
                outline: 'none',
                minHeight: '44px',
                boxSizing: 'border-box',
              }}
            />
          </div>

          {error && (
            <div
              style={{
                background: '#f8d7da',
                color: '#c0392b',
                borderRadius: 'var(--r-sm)',
                padding: 'var(--s-3) var(--s-4)',
                fontSize: 'var(--t-small)',
              }}
            >
              {error}
            </div>
          )}

          <Button type="submit" variant="primary" size="lg" loading={loading} style={{ width: '100%' }}>
            Sign in
          </Button>
        </form>
      </div>
    </main>
  )
}
