import Link from 'next/link';
import { loginCustomer } from '../actions';

const ERROR_MESSAGES: Record<string, string> = {
  invalid: 'Incorrect email or password.',
  rate_limited: 'Too many attempts — please wait a few minutes and try again.',
};

export default function LoginPage({ searchParams }: { searchParams: { error?: string; next?: string } }) {
  const error = searchParams.error ? (ERROR_MESSAGES[searchParams.error] ?? 'Something went wrong.') : null;
  const next = searchParams.next ?? '/account';

  return (
    <div className="mx-auto max-w-md px-6 py-16">
      <h1 className="font-display text-3xl">Log in</h1>
      <p className="mt-2 text-sm text-muted">
        New here?{' '}
        <Link href={`/account/register?next=${encodeURIComponent(next)}`} className="text-clay hover:text-clay-dark">
          Create an account
        </Link>
      </p>

      {error && (
        <p className="mt-6 border border-splash-pink/40 bg-splash-pink/10 px-4 py-3 text-sm text-splash-pink">
          {error}
        </p>
      )}

      <form action={loginCustomer} className="mt-8 space-y-6">
        <input type="hidden" name="next" value={next} />
        <div>
          <label htmlFor="email" className="tag-label mb-2 block">
            Email
          </label>
          <input id="email" name="email" type="email" required className="w-full border border-line bg-paper px-3 py-2 text-sm text-ink" />
        </div>
        <div>
          <label htmlFor="password" className="tag-label mb-2 block">
            Password
          </label>
          <input
            id="password"
            name="password"
            type="password"
            required
            className="w-full border border-line bg-paper px-3 py-2 text-sm text-ink"
          />
        </div>
        <button type="submit" className="bg-clay px-6 py-3 text-sm font-medium text-paper hover:bg-clay-dark">
          Log in
        </button>
      </form>

      <p className="mt-6 text-sm">
        <Link href="/account/forgot-password" className="text-clay hover:text-clay-dark">
          Forgot your password?
        </Link>
      </p>

      <div className="mt-12 border-t border-line pt-6">
        <p className="text-sm text-muted">Shop owner? </p>
        <Link href="/admin/login" className="text-clay hover:text-clay-dark">
          Admin login
        </Link>
      </div>
    </div>
  );
}
