'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Eye, EyeOff } from 'lucide-react'
import { saveUser } from '@/libs/auth'
import { getApiError } from '@/libs/api'
import { authService } from '@/services/auth.service'
import { DemoUser } from '@/types'
import DemoCard from './DemoCard'
import { showError, showSuccess } from '../ui/Toast'
import { useAuth } from '@/hooks/useAuth'
import Loading from '@/components/ui/Loader/Loading'

const DEMO_USERS: DemoUser[] = [
  { role: 'ADVISORY ADMIN', badgeColor: 'text-green-600 bg-green-50 border-green-200', name: 'Rahul Mehta', description: 'Full platform access across all clients', email: 'rahul@samasthafinance.com', password: 'advisory_admin' },
  { role: 'ADVISORY TEAM', badgeColor: 'text-blue-600 bg-blue-50 border-blue-200', name: 'Priya Nair', description: 'View access — Aarna & Meridian clients', email: 'priya@samasthafinance.com', password: 'advisory_team' },
  { role: 'CLIENT ADMIN', badgeColor: 'text-purple-600 bg-purple-50 border-purple-200', name: 'Vikram Sethi', description: 'Aarna Industries — CFO with upload rights', email: 'vikram@aarna.com', password: 'client_admin' },
  { role: 'CLIENT TEAM', badgeColor: 'text-orange-600 bg-orange-50 border-orange-200', name: 'Sunita Rao', description: 'Aarna Industries — Financials upload only', email: 'sunita@aarna.com', password: 'client_team' },
]

export default function LoginForm() {
  const router = useRouter()
  const { user, ready, setUser } = useAuth()

  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [rememberMe, setRememberMe] = useState(false)
  const [showPassword, setShowPassword] = useState(false)
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (ready && user) {
      router.replace('/clients')
    }
  }, [user, ready, router])

  function handleDemoSelect(user: DemoUser) {
    setEmail(user.email)
    setPassword(user.password)
    setError('')
  }

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

    try {
      const { data } = await authService.login(email, password, rememberMe)
      saveUser(data.user, rememberMe)
      setUser(data.user)
      showSuccess(data.message || "Logged in successfully!")
      setTimeout(() => router.push('/clients'), 1000)
    } catch (err) {
      setError(getApiError(err))
      showError(getApiError(err))
    } finally {
      setLoading(false)
    }
  }

  if (!ready || user) {
    return <Loading name="session" />
  }

  return (
    <div className="flex items-center justify-center min-h-screen py-10 px-6 bg-[#f1f5f9]">
      <div className="w-full max-w-[420px] bg-white rounded-2xl shadow-md border border-gray-100 px-8 py-8">
        <h1 className="text-2xl font-bold text-gray-900 mb-1">Sign in to your workspace</h1>
        <p className="text-sm text-gray-500 mb-7">Enter your credentials to access the platform.</p>

        <form onSubmit={handleSubmit} noValidate className="space-y-4">
          <div>
            <label htmlFor="email" className="block text-[11px] font-semibold text-gray-500 uppercase tracking-widest mb-1.5">Work Email</label>
            <input id="email" type="email" autoComplete="email" placeholder="you@organisation.com" value={email}
              onChange={e => { setEmail(e.target.value); setError('') }}
              className="w-full px-3.5 py-2.5 text-sm border border-gray-200 rounded-lg bg-white placeholder:text-muted-foreground text-gray-900 focus:outline-none focus:ring-2 focus:ring-slate-800 focus:border-transparent transition-all duration-150" />
          </div>

          <div>
            <label htmlFor="password" className="block text-[11px] font-semibold text-gray-500 uppercase tracking-widest mb-1.5">Password</label>
            <div className="relative">
              <input id="password" type={showPassword ? 'text' : 'password'} autoComplete="current-password"
                placeholder="••••••••" value={password}
                onChange={e => { setPassword(e.target.value); setError('') }}
                className="w-full px-3.5 py-2.5 pr-10 text-sm border border-gray-200 rounded-lg bg-white placeholder:text-muted-foreground text-gray-900 focus:outline-none focus:ring-2 focus:ring-slate-800 focus:border-transparent transition-all duration-150" />
              <button type="button" onClick={() => setShowPassword(v => !v)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                aria-label={showPassword ? 'Hide password' : 'Show password'}>
                {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              </button>
            </div>
          </div>

          {error && <p className="text-xs text-red-600 bg-red-50 border border-red-100 rounded-lg px-3 py-2">{error}</p>}

          <div className="flex items-center justify-between pt-1">
            <label className="flex items-center gap-2 cursor-pointer select-none">
              <input type="checkbox" checked={rememberMe} onChange={e => setRememberMe(e.target.checked)}
                className="w-4 h-4 rounded border-gray-300 text-slate-800 accent-slate-800 cursor-pointer" />
              <span className="text-sm text-gray-600">Remember me</span>
            </label>
            <a href="#" className="text-sm text-slate-700 font-medium hover:underline">Forgot password?</a>
          </div>

          <button type="submit" disabled={loading}
            className="w-full py-3 rounded-lg text-sm font-semibold text-white transition-all duration-150 hover:opacity-90 disabled:opacity-60 disabled:cursor-not-allowed mt-1 bg-[#0f1c2e]">
            {loading ? 'Signing in…' : 'Sign in'}
          </button>
        </form>

        <div className="mt-8">
          <p className="text-[11px] font-semibold text-gray-400 uppercase tracking-widest mb-3">Demo as…</p>
          <div className="grid grid-cols-2 gap-2">
            {DEMO_USERS.map(user => <DemoCard key={user.role} user={user} onClick={handleDemoSelect} />)}
          </div>
          <p className="mt-3 text-[11px] text-gray-400 leading-snug">Clicking a card pre-fills the credentials — then press Sign in.</p>
        </div>

        <p className="mt-6 text-[11px] text-gray-400">
          Access is restricted to authorised personnel.{' '}
          <a href="mailto:support@samasthafinance.com" className="text-slate-700 hover:underline font-medium">Contact support</a>{' '}
          if you need access.
        </p>
      </div>
    </div>
  )
}
