'use client';

import Link from 'next/link';
import { useState } from 'react';
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 LoginPage() {
  const [email, setEmail] = useState('');
  const [state, setState] = useState<'idle' | 'sending' | 'sent' | 'error'>('idle');
  const [error, setError] = useState<string | null>(null);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setState('sending');
    setError(null);
    try {
      await apiFetch('/v1/auth/magic-link', {
        method: 'POST',
        body: JSON.stringify({ email }),
      });
      setState('sent');
    } catch (err) {
      setState('error');
      setError((err as Error).message);
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center px-6">
      <div className="w-full max-w-sm">
        <Logo className="mb-10" />
        <h1 className="text-[20px] font-semibold tracking-tight">Sign in to your workspace</h1>
        <p className="mt-1 text-[13px] text-[--color-fg-muted]">
          We&apos;ll email you a magic link. No password.
        </p>

        {state !== 'sent' ? (
          <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="you@company.com"
              />
            </div>
            <Button
              type="submit"
              variant="primary"
              size="lg"
              className="w-full"
              disabled={state === 'sending'}
            >
              {state === 'sending' ? 'Sending…' : 'Send magic link'}
            </Button>
            {error && <p className="text-[12px] text-[--color-danger]">{error}</p>}
          </form>
        ) : (
          <div className="panel mt-7 p-4">
            <p className="text-[13px]">
              Magic link sent to <span className="mono">{email}</span>.
            </p>
            <p className="mt-1.5 text-[12px] text-[--color-fg-muted]">
              In dev mode the link is printed to the API console output. Check the terminal.
            </p>
          </div>
        )}

        <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>
  );
}
