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

import { useState } from 'react';
import { Trash2, ArrowRightLeft } from 'lucide-react';
import { useTranslation } from '@/i18n/TranslationProvider';
import type { CompanyMemberResponse } from '@archer/api-interface';
import type { MemberRole } from '@/infrastructure/http/api/members/api';
import { RoleBadge } from './RoleBadge';

interface ActiveMembersListProps {
  members: CompanyMemberResponse[];
  loading: boolean;
  onChangeRole: (member: CompanyMemberResponse, role: MemberRole) => Promise<void>;
  onRemove: (member: CompanyMemberResponse) => Promise<void>;
  onTransfer: (member: CompanyMemberResponse, toEmail: string) => Promise<void>;
}

export function ActiveMembersList({ members, loading, onChangeRole, onRemove, onTransfer }: ActiveMembersListProps) {
  const { t } = useTranslation();
  const [transferFor, setTransferFor] = useState<string | null>(null);
  const [transferEmail, setTransferEmail] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const closeTransfer = () => {
    setTransferFor(null);
    setTransferEmail('');
  };

  const submitTransfer = async (member: CompanyMemberResponse) => {
    if (!transferEmail.trim()) return;
    setSubmitting(true);
    try {
      await onTransfer(member, transferEmail.trim());
      closeTransfer();
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section data-testid="active-members-section" className="bg-white border border-gray-200 rounded-lg p-6">
      <h2 className="text-lg font-semibold mb-4">{t('members.active.heading')}</h2>
      {loading ? (
        <div className="text-sm text-gray-500">{t('members.active.loading')}</div>
      ) : members.length === 0 ? (
        <div className="text-sm text-gray-500">{t('members.active.empty')}</div>
      ) : (
        <ul className="divide-y divide-gray-100" data-testid="members-list">
          {members.map((member) => (
            <li key={member.id} className="py-3" data-testid={`member-row-${member.id}`}>
              <div className="flex items-center gap-4">
                <div className="flex-1 min-w-0">
                  <div className="font-medium text-gray-900 truncate">
                    {`${member.profile.firstName} ${member.profile.lastName}`.trim() || member.profile.email}
                  </div>
                  <div className="text-xs text-gray-500 truncate">{member.profile.email}</div>
                </div>
                <RoleBadge role={member.role} />
                <select
                  value={member.role}
                  onChange={(event) => onChangeRole(member, event.target.value as MemberRole)}
                  data-testid={`member-role-select-${member.id}`}
                  className="border border-gray-300 rounded-md px-2 py-1 text-sm bg-white"
                >
                  <option value="admin">admin</option>
                  <option value="operator">operator</option>
                </select>
                <button
                  type="button"
                  onClick={() => (transferFor === member.id ? closeTransfer() : setTransferFor(member.id))}
                  data-testid={`member-transfer-${member.id}`}
                  className="text-gray-500 hover:text-primary-600 p-1"
                  aria-label={t('members.active.transferAria')}
                  title={t('members.active.transfer')}
                >
                  <ArrowRightLeft size={16} />
                </button>
                <button
                  type="button"
                  onClick={() => onRemove(member)}
                  data-testid={`member-remove-${member.id}`}
                  className="text-red-600 hover:text-red-700 p-1"
                  aria-label={t('members.active.removeAria')}
                >
                  <Trash2 size={16} />
                </button>
              </div>
              {transferFor === member.id && (
                <div className="mt-3 flex flex-col sm:flex-row gap-2" data-testid={`member-transfer-form-${member.id}`}>
                  <input
                    type="email"
                    value={transferEmail}
                    onChange={(event) => setTransferEmail(event.target.value)}
                    placeholder={t('members.active.transferEmailPlaceholder')}
                    data-testid={`member-transfer-email-${member.id}`}
                    className="flex-1 border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
                  />
                  <button
                    type="button"
                    disabled={submitting || !transferEmail.trim()}
                    onClick={() => submitTransfer(member)}
                    data-testid={`member-transfer-confirm-${member.id}`}
                    className="bg-primary-600 hover:bg-primary-700 text-white font-medium rounded-md px-4 py-2 text-sm disabled:opacity-50"
                  >
                    {t('members.active.transferConfirm')}
                  </button>
                  <button
                    type="button"
                    onClick={closeTransfer}
                    data-testid={`member-transfer-cancel-${member.id}`}
                    className="border border-gray-300 text-gray-700 rounded-md px-4 py-2 text-sm hover:bg-gray-50"
                  >
                    {t('members.active.transferCancel')}
                  </button>
                </div>
              )}
            </li>
          ))}
        </ul>
      )}
    </section>
  );
}
