import { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUserPlus, faTrash, faPlus } from '@fortawesome/pro-duotone-svg-icons';
import { Input } from '@/components/base/input/input';
import { Select } from '@/components/base/select/select';
import { Button } from '@/components/base/buttons/button';

// Multi-email invite form. Uses the platform's sendInvitations mutation which
// takes a list of emails; the invited members all get the same role (the
// platform doesn't support per-email roles in a single call). If the admin
// needs different roles, they invite in multiple batches, or edit roles
// afterwards via the team listing.
//
// Role selection is optional — leaving it blank invites members without a
// role, matching the platform's default. When a role is selected, the caller
// is expected to apply it via updateWorkspaceMemberRole after the invited
// member accepts (this form just reports the selected roleId back).

export type RoleOption = {
    id: string;
    label: string;
    supportingText?: string;
};

export type InviteMemberFormValues = {
    emails: string[];
    roleId: string;
};

const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

type InviteMemberFormProps = {
    value: InviteMemberFormValues;
    onChange: (value: InviteMemberFormValues) => void;
    roles: RoleOption[];
};

export const InviteMemberForm = ({ value, onChange, roles }: InviteMemberFormProps) => {
    const [draft, setDraft] = useState('');

    const addEmail = (rawValue?: string) => {
        const source = (rawValue ?? draft).trim();
        if (!source) return;
        const trimmed = source.replace(/,+$/, '').trim();
        if (!trimmed) return;
        if (!EMAIL_REGEX.test(trimmed)) return;
        if (value.emails.includes(trimmed)) {
            setDraft('');
            return;
        }
        onChange({ ...value, emails: [...value.emails, trimmed] });
        setDraft('');
    };

    const removeEmail = (email: string) => {
        onChange({ ...value, emails: value.emails.filter((e) => e !== email) });
    };

    // The Input component wraps react-aria TextField which doesn't expose
    // onKeyDown via its typed props — so we commit on comma via the onChange
    // handler instead. Users can also press the Add button or tab onto it.
    const handleChange = (next: string) => {
        if (next.endsWith(',')) {
            addEmail(next);
            return;
        }
        setDraft(next);
    };

    return (
        <div className="flex flex-col gap-4">
            <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-secondary">
                    Emails <span className="text-error-primary">*</span>
                </label>
                <div className="flex items-center gap-2">
                    <div className="flex-1">
                        <Input
                            placeholder="colleague@hospital.com"
                            type="email"
                            value={draft}
                            onChange={handleChange}
                        />
                    </div>
                    <Button
                        size="sm"
                        color="secondary"
                        iconLeading={({ className }: { className?: string }) => (
                            <FontAwesomeIcon icon={faPlus} className={className} />
                        )}
                        onClick={() => addEmail()}
                        isDisabled={!draft.trim() || !EMAIL_REGEX.test(draft.trim())}
                    >
                        Add
                    </Button>
                </div>
                <p className="text-xs text-tertiary">
                    Type a comma to add multiple emails, or click Add.
                </p>
            </div>

            {value.emails.length > 0 && (
                <div className="flex flex-col gap-2 rounded-lg border border-secondary bg-secondary p-3">
                    <p className="text-xs font-semibold uppercase tracking-wider text-quaternary">
                        {value.emails.length} invitee{value.emails.length === 1 ? '' : 's'}
                    </p>
                    <ul className="flex flex-col gap-1.5">
                        {value.emails.map((email) => (
                            <li
                                key={email}
                                className="flex items-center justify-between rounded-md bg-primary px-3 py-2 text-sm"
                            >
                                <span className="flex items-center gap-2 text-primary">
                                    <FontAwesomeIcon icon={faUserPlus} className="size-3.5 text-fg-brand-primary" />
                                    {email}
                                </span>
                                <button
                                    type="button"
                                    onClick={() => removeEmail(email)}
                                    className="flex size-6 items-center justify-center rounded-md text-fg-quaternary hover:bg-secondary_hover hover:text-fg-error-primary"
                                    title="Remove"
                                >
                                    <FontAwesomeIcon icon={faTrash} className="size-3" />
                                </button>
                            </li>
                        ))}
                    </ul>
                </div>
            )}

            <Select
                label="Role"
                placeholder={roles.length === 0 ? 'No roles available' : 'Assign a role'}
                isDisabled={roles.length === 0}
                items={roles}
                selectedKey={value.roleId || null}
                onSelectionChange={(key) => onChange({ ...value, roleId: (key as string) || '' })}
            >
                {(item) => <Select.Item id={item.id} label={item.label} supportingText={item.supportingText} />}
            </Select>
        </div>
    );
};
