'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { Logo } from '@/components/logo';
import { Button } from '@/components/ui/button';
import { Input, Label } from '@/components/input';
import { apiFetch } from '@/lib/api';

export default function AdminLogin() {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [state, setState] = useState<'idle' | 'submitting' | 'error'>('idle');
  const [error, setError] = useState<string | null>(null);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setState('submitting');
    setError(null);
    try {
      await apiFetch('/v1/auth/admin/login', {
        method: 'POST',
        body: JSON.stringify({ email, password }),
      });
      router.replace('/admin');
    } catch (err) {
      const detail = (err as { detail?: { error?: string } }).detail;
      const code = detail?.error;
      setError(
        code === 'not_admin'
          ? 'That account exists but is not an admin.'
          : code === 'invalid_credentials'
            ? 'Wrong email or password.'
            : (err as Error).message,
      );
      setState('error');
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center px-6">
      <div className="w-full max-w-sm">
        <Logo className="mb-10" />
        <div className="flex items-baseline gap-2">
          <h1 className="text-[20px] font-semibold tracking-tight">Admin sign in</h1>
          <span className="mono rounded-full border border-[--color-border] bg-[--color-bg-elevated] px-2 py-0.5 text-[10.5px] tracking-wider text-[--color-fg-subtle]">
            restricted
          </span>
        </div>
        <p className="mt-1 text-[13px] text-[--color-fg-muted]">
          Email + password. Non-admin accounts use the magic link at{' '}
          <Link href="/login" className="underline transition-colors hover:text-[--color-fg]">
            /login
          </Link>
          .
        </p>

        <form onSubmit={submit} className="mt-7 space-y-3">
          <div className="space-y-1.5">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              required
              autoComplete="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="admin@yourcompany.com"
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="password">Password</Label>
            <Input
              id="password"
              type="password"
              required
              autoComplete="current-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
            />
          </div>
          <Button
            type="submit"
            variant="primary"
            size="lg"
            className="w-full"
            disabled={state === 'submitting'}
          >
            {state === 'submitting' ? 'Signing in…' : 'Sign in'}
          </Button>
          {error && <p className="text-[12px] text-[--color-danger]">{error}</p>}
        </form>

        <div className="mt-8 text-[12px] text-[--color-fg-subtle]">
          <Link href="/" className="transition-colors hover:text-[--color-fg]">
            ← Back to home
          </Link>
        </div>
      </div>
    </div>
  );
}
