import React from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { UserPlus, Trash2, Copy, RefreshCcw } from 'lucide-react';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { Pressable } from '@tamagui/react-native-web-lite';
import { MobileShell, HeaderActionButton } from './components/MobileShell';
import { MobileCard, CTAButton, PillBadge, SkeletonCard } from './components/Primitives';
import { MobileField, MobileInput, MobileSelect } from './components/FormControls';
import { EventMember, getEventMembers, inviteEventMember, removeEventMember, trackOnboarding } from '../api';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import toast from 'react-hot-toast';
import { MobileSheet } from './components/Sheet';
import { adminPath } from '../constants';
import { useBackNavigation } from './hooks/useBackNavigation';

export default function MobileEventMembersPage() {
  const { slug: slugParam } = useParams<{ slug?: string }>();
  const slug = slugParam ?? null;
  const navigate = useNavigate();
  const { t } = useTranslation('management');

  const [members, setMembers] = React.useState<EventMember[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const [invite, setInvite] = React.useState({ name: '', email: '', role: 'member' as EventMember['role'] });
  const [saving, setSaving] = React.useState(false);
  const [inviteLink, setInviteLink] = React.useState<string | null>(null);
  const emailInputRef = React.useRef<HTMLInputElement | null>(null);
  const [search, setSearch] = React.useState('');
  const [confirmRemove, setConfirmRemove] = React.useState<EventMember | null>(null);
  const back = useBackNavigation(slug ? adminPath(`/mobile/events/${slug}`) : adminPath('/mobile/events'));

  const load = React.useCallback(async () => {
    if (!slug) return;
    setLoading(true);
    setError(null);
    try {
      const result = await getEventMembers(slug, 1);
      setMembers(result.data);
      if (result.data.length) {
        const pending = result.data.find((m) => m.status === 'pending' && m.permissions?.includes('invite_link'));
        if (pending?.email) {
          setInviteLink(`mailto:${pending.email}`);
        }
      }
    } catch (err) {
      if (!isAuthError(err)) {
        setError(getApiErrorMessage(err, t('events.errors.loadFailed', 'Mitglieder konnten nicht geladen werden.')));
      }
    } finally {
      setLoading(false);
    }
  }, [slug, t]);

  React.useEffect(() => {
    void load();
  }, [load]);

  async function handleInvite() {
    if (!slug || !invite.email.trim()) return;
    setSaving(true);
    setError(null);
    try {
      const member = await inviteEventMember(slug, {
        email: invite.email.trim(),
        name: invite.name.trim() || undefined,
        role: invite.role,
      });
      setMembers((prev) => [member, ...prev]);
      setInvite({ name: '', email: '', role: 'member' });
      void trackOnboarding('invite_created', { event_slug: slug });
      toast.success(t('events.members.inviteSuccess', 'Einladung gesendet'));
    } catch (err) {
      if (!isAuthError(err)) {
        setError(getApiErrorMessage(err, t('events.errors.saveFailed', 'Einladung fehlgeschlagen.')));
        toast.error(t('events.members.inviteFailed', 'Einladung fehlgeschlagen.'));
      }
    } finally {
      setSaving(false);
    }
  }

  async function handleRemove(member: EventMember) {
    if (!slug) return;
    try {
      await removeEventMember(slug, member.id);
      setMembers((prev) => prev.filter((m) => m.id !== member.id));
      toast.success(t('events.members.removeSuccess', 'Mitglied entfernt'));
    } catch (err) {
      if (!isAuthError(err)) {
        setError(getApiErrorMessage(err, t('events.errors.saveFailed', 'Mitglied konnte nicht entfernt werden.')));
        toast.error(t('events.members.removeFailed', 'Mitglied konnte nicht entfernt werden.'));
      }
    }
  }

  return (
    <MobileShell
      activeTab="home"
      title={t('events.members.title', 'Guest Management')}
      onBack={back}
      headerActions={
        <HeaderActionButton onPress={() => load()} ariaLabel={t('common.refresh', 'Refresh')}>
          <RefreshCcw size={18} color="#0f172a" />
        </HeaderActionButton>
      }
    >
      {error ? (
        <MobileCard>
          <Text fontWeight="700" color="#b91c1c">
            {error}
          </Text>
        </MobileCard>
      ) : null}

      <MobileCard space="$3">
        <Text fontSize="$md" fontWeight="800" color="#111827">
          {t('events.members.inviteTitle', 'Invite Member')}
        </Text>
        <YStack space="$2">
          <MobileField label={t('events.members.name', 'Name')}>
            <MobileInput
              type="text"
              value={invite.name}
              onChange={(e) => setInvite((prev) => ({ ...prev, name: e.target.value }))}
              placeholder="Alex Example"
            />
          </MobileField>
          <MobileField label={t('events.members.email', 'Email')}>
            <MobileInput
              type="email"
              value={invite.email}
              onChange={(e) => setInvite((prev) => ({ ...prev, email: e.target.value }))}
              placeholder="alex@example.com"
              ref={emailInputRef}
            />
          </MobileField>
          <MobileField label={t('events.members.role', 'Role')}>
            <MobileSelect
              value={invite.role}
              onChange={(e) => setInvite((prev) => ({ ...prev, role: e.target.value as EventMember['role'] }))}
            >
              <option value="member">{t('events.members.roleMember', 'Member')}</option>
              <option value="tenant_admin">{t('events.members.roleAdmin', 'Admin')}</option>
            </MobileSelect>
          </MobileField>
          <CTAButton label={saving ? t('common.saving', 'Saving...') : t('events.members.invite', 'Send Invite')} onPress={() => handleInvite()} />
          {saving ? (
            <Text fontSize="$xs" color="#4b5563">
              {t('common.processing', 'Processing...')}
            </Text>
          ) : null}
        </YStack>
      </MobileCard>

      <MobileInput
        type="search"
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        placeholder={t('events.members.search', 'Search members')}
        compact
      />

      <MobileCard space="$3">
        <Text fontSize="$md" fontWeight="800" color="#111827">
          {t('events.members.listTitle', 'Team & Guests')}
        </Text>
        {inviteLink ? (
          <Pressable
            onPress={async () => {
              try {
                await navigator.clipboard.writeText(inviteLink);
                toast.success(t('events.members.copyInvite', 'Einladungslink kopiert'));
              } catch {
                toast.error(t('events.members.copyInviteFailed', 'Kopieren nicht möglich'));
              }
            }}
          >
            <XStack alignItems="center" space="$2" marginBottom="$2">
              <Copy size={16} color="#007AFF" />
              <Text fontSize="$sm" color="#007AFF">
                {t('events.members.copyInviteLabel', 'Invite Link kopieren')}
              </Text>
            </XStack>
          </Pressable>
        ) : null}
        {loading ? (
          <YStack space="$2">
            {Array.from({ length: 4 }).map((_, idx) => (
              <SkeletonCard key={`m-${idx}`} height={70} />
            ))}
          </YStack>
        ) : members.length === 0 ? (
          <YStack space="$2">
            <Text fontSize="$sm" fontWeight="700" color="#111827">
              {t('events.members.emptyTitle', 'Invite your team')}
            </Text>
            <Text fontSize="$xs" color="#4b5563">
              {t('events.members.emptyBody', 'Send the first invite so helpers can access the event.')}
            </Text>
            <CTAButton
              label={t('events.members.emptyAction', 'Send first invite')}
              onPress={() => emailInputRef.current?.focus()}
              fullWidth={false}
            />
          </YStack>
        ) : (
          <YStack space="$2">
            {members
              .filter((member) => {
                if (!search.trim()) return true;
                const hay = `${member.name ?? ''} ${member.email ?? ''}`.toLowerCase();
                return hay.includes(search.toLowerCase());
              })
              .map((member) => (
                <MobileCard key={member.id} padding="$3" borderColor="#e5e7eb">
                  <XStack alignItems="center" justifyContent="space-between">
                    <YStack space="$1">
                      <Text fontSize="$sm" fontWeight="700" color="#111827">
                        {member.name || member.email || 'Gast'}
                      </Text>
                      <Text fontSize="$xs" color="#6b7280">
                        {member.email ?? ''}
                      </Text>
                      <XStack space="$1.5" alignItems="center">
                        <PillBadge tone={member.status === 'pending' ? 'warning' : 'muted'}>
                          {member.status ?? 'pending'}
                        </PillBadge>
                        <PillBadge tone={member.role === 'tenant_admin' ? 'success' : 'muted'}>
                          {member.role === 'tenant_admin'
                            ? t('events.members.admin', 'Admin')
                            : t('events.members.member', 'Member')}
                        </PillBadge>
                      </XStack>
                    </YStack>
                    <XStack space="$2">
                      <Pressable
                        onPress={async () => {
                          const link = inviteLink || (member.email ? `mailto:${member.email}` : null);
                          if (!link) {
                            toast.error(t('events.members.copyInviteFailed', 'Kopieren nicht möglich'));
                            return;
                          }
                          try {
                            await navigator.clipboard.writeText(link);
                            toast.success(t('events.members.copyInvite', 'Einladungslink kopiert'));
                          } catch {
                            toast.error(t('events.members.copyInviteFailed', 'Kopieren nicht möglich'));
                          }
                        }}
                      >
                        <Copy size={16} color="#6b7280" />
                      </Pressable>
                      <Pressable onPress={() => setConfirmRemove(member)}>
                        <Trash2 size={16} color="#ef4444" />
                      </Pressable>
                    </XStack>
                  </XStack>
                </MobileCard>
              ))}
          </YStack>
        )}
      </MobileCard>

      <MobileSheet
        open={Boolean(confirmRemove)}
        onClose={() => setConfirmRemove(null)}
        title={t('events.members.confirmRemove', 'Mitglied entfernen?')}
        footer={
          <CTAButton
            label={t('events.members.remove', 'Remove')}
            onPress={() => {
              if (confirmRemove) {
                void handleRemove(confirmRemove);
              }
              setConfirmRemove(null);
            }}
          />
        }
        bottomOffsetPx={120}
      >
        <Text fontSize={12.5} color="#4b5563">
          {t('events.members.removeHint', 'Dieses Mitglied verliert den Zugang zum Event.')}
        </Text>
        <Text fontSize={13} fontWeight="700" color="#111827">
          {confirmRemove?.name || confirmRemove?.email}
        </Text>
      </MobileSheet>
    </MobileShell>
  );
}
