"use client";

import { useState } from "react";
import { AdminButton } from "@/components/admin/design-system";

function isValidEmail(e: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);
}

export default function AddRecipientForm({ onAdd }: { onAdd: (email: string, name: string) => void }) {
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [error, setError] = useState("");

  function handleAdd() {
    if (!email.trim()) return;
    if (!isValidEmail(email.trim())) {
      setError("Enter a valid email address.");
      return;
    }
    setError("");
    onAdd(email.trim(), name.trim());
    setEmail("");
    setName("");
  }

  return (
    <div className="flex gap-2 items-start">
      <div className="flex-1">
        <input aria-label="Email Address"
          type="email" placeholder="Email address"
          value={email} onChange={e => { setEmail(e.target.value); setError(""); }}
          onKeyDown={e => e.key === "Enter" && handleAdd()}
          className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)]" />
      </div>
      <div className="w-36">
        <input aria-label="Name (optional)"
          type="text" placeholder="Name (optional)"
          value={name} onChange={e => setName(e.target.value)}
          onKeyDown={e => e.key === "Enter" && handleAdd()}
          className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)]" />
      </div>
      <AdminButton
        variant="primary"
        size="sm"
        onClick={handleAdd}
      >
        Add
      </AdminButton>
      {error && <p className="text-xs text-[var(--admin-danger)] mt-1">{error}</p>}
    </div>
  );
}
