// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)

import { useState } from 'react';
import { Mail } from 'lucide-react';
import { useTranslation } from '@/i18n/TranslationProvider';
import type { MemberRole } from '@/infrastructure/http/api/members/api';

interface InviteMemberFormProps {
  onSubmit: (email: string, role: MemberRole) => Promise<void>;
  /** Pre-rendered seat-cost disclosure shown when seats are a paid, configurable cap. */
  seatNotice?: string | null;
}

export function InviteMemberForm({ onSubmit, seatNotice }: InviteMemberFormProps) {
  const { t } = useTranslation();
  const [email, setEmail] = useState('');
  const [role, setRole] = useState<MemberRole>('operator');
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (!email.trim()) return;
    setSubmitting(true);
    try {
      await onSubmit(email.trim(), role);
      setEmail('');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section data-testid="invite-member-section" className="bg-white border border-gray-200 rounded-lg p-6">
      <h2 className="text-lg font-semibold mb-1">{t('members.invite.heading')}</h2>
      <p className="text-sm text-gray-500 mb-4">{t('members.invite.hint')}</p>
      {seatNotice && (
        <p className="text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded-md px-3 py-2 mb-4" data-testid="invite-seat-notice">
          {seatNotice}
        </p>
      )}
      <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-[1fr_220px_140px] gap-3">
        <input
          type="email"
          required
          value={email}
          onChange={(event) => setEmail(event.target.value)}
          placeholder={t('members.invite.emailPlaceholder')}
          data-testid="invite-email-input"
          className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
        />
        <select
          value={role}
          onChange={(event) => setRole(event.target.value as MemberRole)}
          data-testid="invite-role-select"
          className="border border-gray-300 rounded-md px-3 py-2 text-sm bg-white"
        >
          <option value="admin">{t('members.invite.roleAdmin')}</option>
          <option value="operator">{t('members.invite.roleOperator')}</option>
        </select>
        <button
          type="submit"
          disabled={submitting || !email.trim()}
          data-testid="invite-submit"
          className="bg-emerald-600 hover:bg-emerald-700 text-white font-medium rounded-md px-4 py-2 text-sm disabled:opacity-50 inline-flex items-center justify-center gap-2"
        >
          <Mail size={16} />
          {submitting ? t('members.invite.submitting') : t('members.invite.submit')}
        </button>
      </form>
    </section>
  );
}
