import React from 'react';
import { themedColor } from '../../theme';
import { ActivityIndicator, Pressable, Text, TextInput, View } from 'react-native';
import { Building2, Info, UserPlus } from 'lucide-react-native';

import { CollaboratorRow } from './CollaboratorRow';
import { editorShellStyles } from '../editor/editorShellStyles';
import { sharingPanelStyles as localStyles } from './sharingPanelStyles';
import { formatEmailList } from './sharingPanelUtils';
import { styles as sharedStyles } from '../../styles';
import { useSharingPanel } from './useSharingPanel';
import { useSuperagentCollaborators } from '../../runtime/runtimeContext';
import type { SuperagentAgent } from '../../types';

type SharingPanelProps = {
  agent: SuperagentAgent;
  // Closes the settings drawer — used before navigating out to workspace members.
  onClose: () => void;
};

/**
 * Sharing & access settings page (invite collaborators + who has access), rendered
 * inside the shared `EditorDrawer` shell — which provides the modal chrome, X-header,
 * "Sharing & access" title, and scroll container. Invite state/actions live in
 * `useSharingPanel`; this component is pure UI.
 */
export function SharingPanel({ agent, onClose }: SharingPanelProps) {
  const { collaborators = [], isLoadingCollaborators: isLoading } = useSuperagentCollaborators();
  const {
    emailText,
    setEmailText,
    error,
    success,
    guestInvitePrompt,
    isInviting,
    hasInput,
    invite,
    inviteGuests,
    openWorkspaceMembers,
  } = useSharingPanel({ agent, onClose });
  return (
    <View style={editorShellStyles.settingsStack}>
      <View style={localStyles.inviteCard}>
        <Text style={[editorShellStyles.panelTitle, localStyles.sectionTitleSpacing]}>Invite collaborators</Text>
        <Text style={localStyles.subtitle}>Give people access to chat with this agent</Text>
        <View style={localStyles.inviteRow}>
          <TextInput
            autoCapitalize="none"
            autoCorrect={false}
            editable={!isInviting}
            keyboardType="email-address"
            onChangeText={setEmailText}
            placeholder="Enter emails"
            placeholderTextColor={themedColor('#71717A')}
            style={localStyles.input}
            value={emailText}
          />
          <Pressable
            accessibilityLabel="Invite collaborators"
            accessibilityRole="button"
            disabled={isInviting}
            onPress={invite}
            style={({ pressed }) => [
              localStyles.inviteButton,
              hasInput && localStyles.inviteButtonActive,
              isInviting && localStyles.disabledButton,
              pressed && sharedStyles.pressed,
            ]}
          >
            {isInviting ? (
              <ActivityIndicator color={themedColor(hasInput ? '#111111' : '#F4F4F5')} size="small" />
            ) : (
              <Text style={[localStyles.inviteButtonText, hasInput && localStyles.inviteButtonTextActive]}>Invite</Text>
            )}
          </Pressable>
        </View>
        {error ? <Text style={localStyles.errorText}>{error}</Text> : null}
        {success ? <Text style={localStyles.successText}>{success}</Text> : null}
      </View>
      {guestInvitePrompt ? (
        <View style={localStyles.guestCard}>
          <Text style={localStyles.guestTitle}>Invite outside workspace?</Text>
          <Text style={localStyles.guestBody}>
            {formatEmailList(guestInvitePrompt.emails)} {guestInvitePrompt.emails.length === 1 ? 'is' : 'are'} not in this workspace.
            Add {guestInvitePrompt.emails.length === 1 ? 'them' : 'these people'} as guests to this Superagent, or manage workspace members first.
          </Text>
          {guestInvitePrompt.pendingInvitationEmails.length > 0 ? (
            <Text style={localStyles.guestHint}>
              Pending workspace invite: {formatEmailList(guestInvitePrompt.pendingInvitationEmails)}
            </Text>
          ) : null}
          <View style={localStyles.guestActions}>
            <Pressable
              accessibilityLabel="Add invitees as guests"
              accessibilityRole="button"
              disabled={isInviting}
              onPress={inviteGuests}
              style={({ pressed }) => [
                localStyles.guestPrimaryButton,
                isInviting && localStyles.disabledButton,
                pressed && sharedStyles.pressed,
              ]}
            >
              {isInviting ? <ActivityIndicator color={themedColor('#111111')} size="small" /> : <UserPlus color={themedColor('#111111')} size={16} strokeWidth={2.6} />}
              <Text style={localStyles.guestPrimaryButtonText}>Add as guest</Text>
            </Pressable>
            <Pressable
              accessibilityLabel="Open workspace members"
              accessibilityRole="button"
              onPress={openWorkspaceMembers}
              style={({ pressed }) => [
                localStyles.guestSecondaryButton,
                pressed && sharedStyles.pressed,
              ]}
            >
              <Building2 color={themedColor('#F4F4F5')} size={16} strokeWidth={2.3} />
              <Text style={localStyles.guestSecondaryButtonText}>Add to workspace</Text>
            </Pressable>
          </View>
        </View>
      ) : null}
      <View style={editorShellStyles.panel}>
        <View style={editorShellStyles.panelHeader}>
          <Text style={editorShellStyles.panelTitle}>People with access</Text>
          {isLoading ? (
            <ActivityIndicator color={themedColor('#F4F4F5')} size="small" />
          ) : (
            <Text style={editorShellStyles.countBadge}>{collaborators.length}</Text>
          )}
        </View>
        <View style={localStyles.membersList}>
          {collaborators.map((collaborator) => (
            <CollaboratorRow collaborator={collaborator} key={`${collaborator.id}-${collaborator.email}`} />
          ))}
          {!isLoading && collaborators.length === 0 ? (
            <Text style={localStyles.emptyText}>No collaborators loaded yet.</Text>
          ) : null}
        </View>
      </View>
      <View style={localStyles.creditNote}>
        <Info color={themedColor('#8E8E93')} size={14} strokeWidth={2.2} />
        <Text style={localStyles.creditNoteText}>All collaborators consume credits from the workspace.</Text>
      </View>
    </View>
  );
}
