import { useRef, useState } from 'react'
import { Head, useForm } from '@inertiajs/react'
import { Eye, EyeOff, Moon, Sun } from '@/Components/Icons'
import useTheme from '@/Hooks/useTheme'
import { cn } from '@/lib/utils'
import { ToastProvider, useToast } from '@/Components/Toast';

// Standalone auth page (no AppLayout) — centered single sign-in card. Submit performs the
// existing username+password login. Fully theme-aware via design tokens (flip on `data-theme`).
// NOTE: JANGAN diubah jadi layout split kiri/kanan — user sudah mengunci tampilan ini.
//
// ⚠️ This page mounts its OWN <ToastProvider> (see the default export at the bottom). Everywhere
// else in the app the provider comes from AppLayout, but an auth page has no layout — and
// `useToast()` outside a provider returns a no-op `show`, so toasts here failed SILENTLY.

const inputClass =
    'h-11 w-full rounded-lg border border-input bg-card px-3.5 text-sm text-foreground outline-none ' +
    'transition-colors placeholder:text-muted-foreground/60 focus:border-primary focus:ring-2 focus:ring-primary/25'
const labelClass = 'mb-1.5 block text-[13px] font-semibold text-foreground'

function ThemeToggle({ onClick }) {
    return (
        <button
            type="button"
            onClick={onClick}
            aria-label="Toggle dark mode"
            className="grid size-10 place-items-center rounded-full border border-border bg-card text-muted-foreground transition-colors hover:border-primary hover:text-primary"
        >
            <span className="hidden dark:block"><Sun size={18} /></span>
            <span className="dark:hidden"><Moon size={18} /></span>
        </button>
    )
}


// The toast-consuming half. It MUST be a child of the provider — a component cannot call
// useToast() and render <ToastProvider> at the same time; the hook would run above its own
// context and read null.
function SignInPage() {
    const { show: showToast } = useToast();
    const { toggle: toggleTheme } = useTheme()
    const [showPassword, setShowPassword] = useState(false)
    const usernameRef = useRef(null)
    const passwordRef = useRef(null)
    const form = useForm({ username: '', password: '' })

    // An empty field never reaches the server: the 422 it would come back with tells the user
    // nothing they don't already know, and the round trip only delays the message. Username is
    // trimmed (spaces there are always a typo); the password is NOT — a space can be part of it.
    const missingUsername = form.data.username.trim() === ''
    const missingPassword = form.data.password === ''

    const missingMessage = () => {
        if (missingUsername && missingPassword) return 'Username and password are required.'
        if (missingUsername) return 'Username is required.'
        if (missingPassword) return 'Password is required.'
        return null
    }

    const submit = (e) => {
        e.preventDefault()

        const missing = missingMessage()
        if (missing) {
            showToast(missing, 'error')
            ;(missingUsername ? usernameRef : passwordRef).current?.focus()
            return
        }

        // The toast is the ONLY channel on this page — there is no inline label under the field
        // any more — so it has to carry the server's exact reason (wrong credentials vs
        // rate-limited). NOT the generic "check the form": on a bad password the form is filled
        // in correctly, the credentials are simply wrong.
        form.post(route('login.store'), {
            onError: (errors) =>
                showToast(
                    errors.username || errors.password || 'Sign in failed — check your username and password.',
                    'error',
                ),
            onFinish: () => form.reset('password'),
        })
    }

    // Controller returns both the credential error and the lockout message under `username`.
    // Kept only to flag the fields for assistive tech — nothing is rendered from it.
    const error = form.errors.username || form.errors.password

    return (
        <>
            <Head title="Sign in" />

            <div className="relative flex min-h-screen flex-col overflow-hidden bg-background text-foreground">
                <div aria-hidden="true" className="pointer-events-none absolute -top-40 left-1/2 size-[32rem] -translate-x-1/2 rounded-full bg-primary/10 blur-[130px]" />

                <header className="relative z-10 flex items-center justify-end px-6 py-5 sm:px-8">
                    <ThemeToggle onClick={toggleTheme} />
                </header>

                <main className="relative z-10 flex flex-1 items-center justify-center px-4 py-10">
                    <div className="w-full max-w-md rounded-2xl border border-border bg-card p-8 shadow-sm sm:p-9">
                        <h1 className="m-0 text-2xl font-bold tracking-tight text-card-foreground">Sign in</h1>
                        <p className="m-0 mt-1.5 text-sm text-muted-foreground">Enter your credentials to access your account.</p>

                        <form onSubmit={submit} className="mt-8 space-y-4" noValidate>
                            <div>
                                <label htmlFor="username" className={labelClass}>Username</label>
                                <input
                                    id="username"
                                    type="text"
                                    autoComplete="username"
                                    autoFocus
                                    ref={usernameRef}
                                    value={form.data.username}
                                    onChange={(e) => form.setData('username', e.target.value)}
                                    placeholder="Insert username"
                                    aria-invalid={error ? true : undefined}
                                    className={inputClass}
                                />
                            </div>

                            <div>
                                <label htmlFor="password" className={labelClass}>Password</label>
                                <div className="relative">
                                    <input
                                        id="password"
                                        type={showPassword ? 'text' : 'password'}
                                        autoComplete="current-password"
                                        ref={passwordRef}
                                        value={form.data.password}
                                        onChange={(e) => form.setData('password', e.target.value)}
                                        placeholder="Insert password"
                                        aria-invalid={error ? true : undefined}
                                        className={cn(inputClass, 'pr-11')}
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPassword((v) => !v)}
                                        aria-label={showPassword ? 'Hide password' : 'Show password'}
                                        aria-pressed={showPassword}
                                        className="absolute inset-y-0 right-0 grid w-11 place-items-center text-muted-foreground transition-colors hover:text-foreground"
                                    >
                                        {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                                    </button>
                                </div>
                            </div>

                            <button
                                type="submit"
                                disabled={form.processing}
                                className="mt-2 grid h-11 w-full place-items-center rounded-lg bg-linear-to-br from-violet-500 to-primary text-sm font-bold text-white shadow-sm transition-[filter] hover:brightness-105 active:brightness-95 disabled:cursor-not-allowed disabled:opacity-60"
                            >
                                {form.processing ? 'Signing in…' : 'Sign in'}
                            </button>
                        </form>
                    </div>
                </main>

                <footer className="relative z-10 px-6 py-6 text-center text-xs text-muted-foreground">
                    Internal use only
                </footer>
            </div>
        </>
    )
}

export default function Login() {
    return (
        <ToastProvider>
            <SignInPage />
        </ToastProvider>
    )
}
