import React from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { RefreshCcw, Plus, Pencil, Trash2, ChevronDown, ChevronRight } from 'lucide-react';
import { YStack, XStack } from '@tamagui/stacks';
import { YGroup } from '@tamagui/group';
import { SizableText as Text } from '@tamagui/text';
import { ListItem } from '@tamagui/list-item';
import { Pressable } from '@tamagui/react-native-web-lite';
import { Button } from '@tamagui/button';
import { AlertDialog } from '@tamagui/alert-dialog';
import { MobileShell, HeaderActionButton } from './components/MobileShell';
import { MobileCard, CTAButton, SkeletonCard, PillBadge, FloatingActionButton } from './components/Primitives';
import { MobileField, MobileInput, MobileSelect, MobileTextArea } from './components/FormControls';
import {
  getEvent,
  getEvents,
  getEventTasks,
  updateTask,
  TenantTask,
  TenantEvent,
  assignTasksToEvent,
  getTasks,
  getTaskCollections,
  importTaskCollection,
  createTask,
  TenantTaskCollection,
  getEmotions,
  TenantEmotion,
  detachTasksFromEvent,
  createEmotion,
  updateEmotion as updateEmotionApi,
  deleteEmotion as deleteEmotionApi,
} from '../api';
import { adminPath } from '../constants';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import toast from 'react-hot-toast';
import { MobileSheet } from './components/Sheet';
import { Tag } from './components/Tag';
import { useEventContext } from '../context/EventContext';
import { RadioGroup } from '@tamagui/radio-group';
import { useBackNavigation } from './hooks/useBackNavigation';
import { buildTaskSummary } from './lib/taskSummary';
import { buildTaskSectionCounts, type TaskSectionKey } from './lib/taskSectionCounts';
import { useAdminTheme } from './theme';

function TaskSummaryCard({
  summary,
  text,
  muted,
  border,
  surfaceMuted,
}: {
  summary: ReturnType<typeof buildTaskSummary>;
  text: string;
  muted: string;
  border: string;
  surfaceMuted: string;
}) {
  const { t } = useTranslation('management');
  return (
    <MobileCard space="$2" borderColor={border}>
      <XStack alignItems="center" justifyContent="space-between" space="$2">
        <SummaryItem
          label={t('events.tasks.summary.assigned', 'Assigned')}
          value={summary.assigned}
          text={text}
          muted={muted}
          surfaceMuted={surfaceMuted}
        />
        <SummaryItem
          label={t('events.tasks.summary.library', 'Library')}
          value={summary.library}
          text={text}
          muted={muted}
          surfaceMuted={surfaceMuted}
        />
      </XStack>
      <XStack alignItems="center" justifyContent="space-between" space="$2">
        <SummaryItem
          label={t('events.tasks.summary.collections', 'Collections')}
          value={summary.collections}
          text={text}
          muted={muted}
          surfaceMuted={surfaceMuted}
        />
        <SummaryItem
          label={t('events.tasks.summary.emotions', 'Emotions')}
          value={summary.emotions}
          text={text}
          muted={muted}
          surfaceMuted={surfaceMuted}
        />
      </XStack>
    </MobileCard>
  );
}

function SummaryItem({
  label,
  value,
  text,
  muted,
  surfaceMuted,
}: {
  label: string;
  value: number;
  text: string;
  muted: string;
  surfaceMuted: string;
}) {
  return (
    <YStack flex={1} padding="$2" borderRadius={12} backgroundColor={surfaceMuted} space="$1">
      <Text fontSize={11} color={muted}>
        {label}
      </Text>
      <Text fontSize={16} fontWeight="800" color={text}>
        {value}
      </Text>
    </YStack>
  );
}

export default function MobileEventTasksPage() {
  const { slug: slugParam } = useParams<{ slug?: string }>();
  const { activeEvent, selectEvent } = useEventContext();
  const slug = slugParam ?? activeEvent?.slug ?? null;
  const navigate = useNavigate();
  const { t } = useTranslation('management');
  const { textStrong, muted, subtle, border, primary, danger, surface, surfaceMuted, dangerBg, dangerText, overlay } = useAdminTheme();
  const [assignedTasks, setAssignedTasks] = React.useState<TenantTask[]>([]);
  const [library, setLibrary] = React.useState<TenantTask[]>([]);
  const [collections, setCollections] = React.useState<TenantTaskCollection[]>([]);
  const [emotions, setEmotions] = React.useState<TenantEmotion[]>([]);
  const [showCollectionSheet, setShowCollectionSheet] = React.useState(false);
  const [showTaskSheet, setShowTaskSheet] = React.useState(false);
  const [newTask, setNewTask] = React.useState({
    id: null as number | null,
    title: '',
    description: '',
    emotion_id: '' as string | '',
    tenant_id: null as number | null,
  });
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const [busyId, setBusyId] = React.useState<number | null>(null);
  const [assigningId, setAssigningId] = React.useState<number | null>(null);
  const [deleteCandidate, setDeleteCandidate] = React.useState<TenantTask | null>(null);
  const [eventId, setEventId] = React.useState<number | null>(null);
  const [searchTerm, setSearchTerm] = React.useState('');
  const [emotionFilter, setEmotionFilter] = React.useState<string>('');
  const [expandedLibrary, setExpandedLibrary] = React.useState(false);
  const [expandedCollections, setExpandedCollections] = React.useState(false);
  const [showFabMenu, setShowFabMenu] = React.useState(false);
  const [showBulkSheet, setShowBulkSheet] = React.useState(false);
  const [bulkLines, setBulkLines] = React.useState('');
  const [showEmotionSheet, setShowEmotionSheet] = React.useState(false);
  const [editingEmotion, setEditingEmotion] = React.useState<TenantEmotion | null>(null);
  const [emotionForm, setEmotionForm] = React.useState({ name: '', color: String(border) });
  const [savingEmotion, setSavingEmotion] = React.useState(false);
  const [showEmotionFilterSheet, setShowEmotionFilterSheet] = React.useState(false);
  const text = textStrong;
  const assignedRef = React.useRef<HTMLDivElement>(null);
  const libraryRef = React.useRef<HTMLDivElement>(null);
  const back = useBackNavigation(slug ? adminPath(`/mobile/events/${slug}`) : adminPath('/mobile/events'));
  const summary = buildTaskSummary({
    assigned: assignedTasks.length,
    library: library.length,
    collections: collections.length,
    emotions: emotions.length,
  });
  const sectionCounts = React.useMemo(() => buildTaskSectionCounts(summary), [summary]);
  React.useEffect(() => {
    if (slugParam && activeEvent?.slug !== slugParam) {
      selectEvent(slugParam);
    }
  }, [slugParam, activeEvent?.slug, selectEvent]);

  // Reset filters when switching events to avoid empty lists due to stale filters.
  React.useEffect(() => {
    setEmotionFilter('');
    setSearchTerm('');
  }, [slug]);

  const scrollToSection = (ref: React.RefObject<HTMLDivElement | null>) => {
    if (ref.current) {
      ref.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  const handleQuickNav = (key: TaskSectionKey) => {
    if (key === 'assigned') {
      scrollToSection(assignedRef);
      return;
    }
    if (key === 'library') {
      scrollToSection(libraryRef);
      return;
    }
    if (key === 'collections') {
      setShowCollectionSheet(true);
      return;
    }
    setShowEmotionSheet(true);
  };

  const load = React.useCallback(async () => {
    if (!slug) {
      try {
        const available = await getEvents({ force: true });
        if (available.length) {
          const target = available[0];
          selectEvent(target.slug ?? null);
          navigate(adminPath(`/mobile/events/${target.slug ?? ''}/tasks`));
          return;
        }
      } catch {
        // ignore
      } finally {
        setError(t('events.errors.missingSlug', 'Kein Event-Slug angegeben.'));
        setLoading(false);
      }
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const event = await getEvent(slug);
      setEventId(event.id);
      const [result, libraryTasks] = await Promise.all([
        getEventTasks(event.id, 1),
        getTasks({ per_page: 200 }),
      ]);
      const collectionList = await getTaskCollections({ per_page: 50 });
      const emotionList = await getEmotions();
      const assignedIds = new Set(result.data.map((t) => t.id));
      const eventTypeId = event.event_type_id ?? event.event_type?.id ?? null;
      const filteredLibrary = libraryTasks.data.filter((task) => {
        if (assignedIds.has(task.id)) return false;
        if (eventTypeId && task.event_type_id && task.event_type_id !== eventTypeId) return false;
        return true;
      });
      setAssignedTasks(result.data);
      setLibrary(filteredLibrary);
      setCollections(collectionList.data ?? []);
      setEmotions(emotionList ?? []);
    } catch (err) {
      if (!isAuthError(err)) {
        const message = getApiErrorMessage(err, t('events.errors.loadFailed', 'Tasks konnten nicht geladen werden.'));
        setError(message);
        toast.error(message);
        // If the current slug is invalid, attempt to recover to a valid event to avoid empty lists.
        try {
          const available = await getEvents({ force: true });
          const fallback = available.find((e: TenantEvent) => e.slug !== slug) ?? available[0];
          if (fallback?.slug) {
            selectEvent(fallback.slug);
            navigate(adminPath(`/mobile/events/${fallback.slug}/tasks`));
          }
        } catch {
          // ignore
        }
      }
    } finally {
      setLoading(false);
    }
  }, [slug, t, navigate, selectEvent]);

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

  async function quickAssign(taskId: number) {
    if (!eventId) return;
    setAssigningId(taskId);
    try {
      await assignTasksToEvent(eventId, [taskId]);
      const result = await getEventTasks(eventId, 1);
      setAssignedTasks(result.data);
      setLibrary((prev) => prev.filter((t) => t.id !== taskId));
      toast.success(t('events.tasks.assigned', 'Task hinzugefügt'));
    } catch (err) {
      if (!isAuthError(err)) {
        setError(getApiErrorMessage(err, t('events.errors.saveFailed', 'Task konnte nicht zugewiesen werden.')));
        toast.error(t('events.tasks.updateFailed', 'Task konnte nicht zugewiesen werden.'));
      }
    } finally {
      setAssigningId(null);
    }
  }

  async function importCollection(collectionId: number) {
    if (!slug || !eventId) return;
    try {
      await importTaskCollection(collectionId, slug);
      const result = await getEventTasks(eventId, 1);
      const assignedIds = new Set(result.data.map((t) => t.id));
      setAssignedTasks(result.data);
      setLibrary((prev) => prev.filter((t) => !assignedIds.has(t.id)));
      toast.success(t('events.tasks.imported', 'Aufgabenpaket importiert'));
    } catch (err) {
      if (!isAuthError(err)) {
        setError(getApiErrorMessage(err, t('events.errors.saveFailed', 'Paket konnte nicht importiert werden.')));
        toast.error(t('events.errors.saveFailed', 'Paket konnte nicht importiert werden.'));
      }
    }
  }

  async function createNewTask() {
    if (!eventId || !newTask.title.trim()) return;
    try {
      if (newTask.id) {
        if (!Number.isFinite(Number(newTask.id))) {
          toast.error(t('events.tasks.updateFailed', 'Task konnte nicht gespeichert werden (ID fehlt).'));
          return;
        }

        const isGlobal = !newTask.tenant_id;

        // Global tasks must not be edited in place: clone and replace.
        if (isGlobal) {
          const cloned = await createTask({
            title: newTask.title.trim(),
            description: newTask.description.trim() || null,
            emotion_id: newTask.emotion_id ? Number(newTask.emotion_id) : undefined,
          } as any);
          await assignTasksToEvent(eventId, [cloned.id]);
          await detachTasksFromEvent(eventId, [Number(newTask.id)]);
        } else {
          // Tenant-owned task: update in place.
          await updateTask(Number(newTask.id), {
            id: Number(newTask.id),
            title: newTask.title.trim(),
            description: newTask.description.trim() || null,
            emotion_id: newTask.emotion_id ? Number(newTask.emotion_id) : undefined,
          } as any);
        }
      } else {
        const created = await createTask({
          title: newTask.title.trim(),
          description: newTask.description.trim() || null,
          emotion_id: newTask.emotion_id ? Number(newTask.emotion_id) : undefined,
        } as any);
        await assignTasksToEvent(eventId, [created.id]);
      }
      const result = await getEventTasks(eventId, 1);
      const assignedIds = new Set(result.data.map((t) => t.id));
      setAssignedTasks(result.data);
      setLibrary((prev) => prev.filter((t) => !assignedIds.has(t.id)));
      setShowTaskSheet(false);
      setNewTask({ id: null, title: '', description: '', emotion_id: '', tenant_id: null });
      toast.success(t('events.tasks.created', 'Aufgabe gespeichert'));
    } catch (err) {
      if (!isAuthError(err)) {
        setError(getApiErrorMessage(err, t('events.errors.saveFailed', 'Aufgabe konnte nicht erstellt werden.')));
        toast.error(t('events.errors.saveFailed', 'Aufgabe konnte nicht erstellt werden.'));
      }
    }
  }

  async function detachTask(taskId: number) {
    if (!eventId) return;
    setBusyId(taskId);
    try {
      await detachTasksFromEvent(eventId, [taskId]);
      setAssignedTasks((prev) => prev.filter((task) => task.id !== taskId));
      toast.success(t('events.tasks.removed', 'Aufgabe entfernt'));
    } catch (err) {
      if (!isAuthError(err)) {
        setError(getApiErrorMessage(err, t('events.errors.saveFailed', 'Aufgabe konnte nicht entfernt werden.')));
        toast.error(t('events.errors.saveFailed', 'Aufgabe konnte nicht entfernt werden.'));
      }
    } finally {
      setBusyId(null);
    }
  }

  async function confirmDeleteTask() {
    if (!deleteCandidate) return;
    const taskId = deleteCandidate.id;
    setDeleteCandidate(null);
    await detachTask(taskId);
  }

  const startEdit = (task: TenantTask) => {
    setNewTask({
      id: task.id,
      title: task.title,
      description: task.description ?? '',
      emotion_id: task.emotion?.id ? String(task.emotion.id) : '',
      tenant_id: (task as any).tenant_id ?? null,
    });
    setShowTaskSheet(true);
  };

  const filteredTasks = assignedTasks.filter((task) => {
    const matchText =
      !searchTerm ||
      task.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (task.description ?? '').toLowerCase().includes(searchTerm.toLowerCase());
    const matchEmotion = !emotionFilter || task.emotion?.id === Number(emotionFilter);
    return matchText && matchEmotion;
  });

  async function handleBulkAdd() {
    if (!eventId || !bulkLines.trim()) return;
    const lines = bulkLines
      .split('\n')
      .map((l) => l.trim())
      .filter(Boolean);
    if (!lines.length) return;
    try {
      for (const line of lines) {
        const created = await createTask({ title: line } as any);
        await assignTasksToEvent(eventId, [created.id]);
      }
      const result = await getEventTasks(eventId, 1);
      setAssignedTasks(result.data);
      setBulkLines('');
      setShowBulkSheet(false);
      toast.success(t('events.tasks.created', 'Aufgabe gespeichert'));
    } catch (err) {
      if (!isAuthError(err)) {
        toast.error(t('events.errors.saveFailed', 'Aufgabe konnte nicht erstellt werden.'));
      }
    }
  }

  async function saveEmotion() {
    if (!emotionForm.name.trim()) return;
    setSavingEmotion(true);
    try {
      if (editingEmotion) {
        const updated = await updateEmotionApi(editingEmotion.id, { name: emotionForm.name.trim(), color: emotionForm.color });
        setEmotions((prev) => prev.map((em) => (em.id === editingEmotion.id ? updated : em)));
      } else {
        const created = await createEmotion({ name: emotionForm.name.trim(), color: emotionForm.color });
        setEmotions((prev) => [...prev, created]);
      }
      setShowEmotionSheet(false);
      setEditingEmotion(null);
      setEmotionForm({ name: '', color: border });
      toast.success(t('events.tasks.emotionSaved', 'Emotion gespeichert'));
    } catch (err) {
      if (!isAuthError(err)) {
        toast.error(getApiErrorMessage(err, t('events.errors.saveFailed', 'Konnte nicht gespeichert werden.')));
      }
    } finally {
      setSavingEmotion(false);
    }
  }

  async function removeEmotion(emotionId: number) {
    try {
      await deleteEmotionApi(emotionId);
      setEmotions((prev) => prev.filter((em) => em.id !== emotionId));
      toast.success(t('events.tasks.emotionRemoved', 'Emotion entfernt'));
    } catch (err) {
      if (!isAuthError(err)) {
        toast.error(getApiErrorMessage(err, t('events.errors.saveFailed', 'Konnte nicht gespeichert werden.')));
      }
    }
  }

  return (
    <MobileShell
      activeTab="tasks"
      title={t('events.tasks.title', 'Tasks & Checklists')}
      onBack={back}
      headerActions={
        <XStack space="$2">
          <HeaderActionButton onPress={() => load()} ariaLabel={t('common.refresh', 'Refresh')}>
            <RefreshCcw size={18} color={text} />
          </HeaderActionButton>
        </XStack>
      }
    >
      {error ? (
        <MobileCard>
          <Text fontSize={13} fontWeight="600" color={danger}>
            {error}
          </Text>
          <CTAButton
            label={t('common.retry', 'Retry')}
            tone="ghost"
            fullWidth={false}
            onPress={() => load()}
          />
        </MobileCard>
      ) : null}

      {!loading ? (
        <TaskSummaryCard
          summary={summary}
          text={text}
          muted={muted}
          border={border}
          surfaceMuted={surfaceMuted}
        />
      ) : null}

      {!loading ? (
        <YStack space="$2">
          <Text fontSize={12} fontWeight="700" color={muted}>
            {t('events.tasks.quickNav', 'Quick jump')}
          </Text>
          <XStack space="$2" flexWrap="wrap">
            {sectionCounts.map((section) => (
              <Button
                key={section.key}
                unstyled
                onPress={() => handleQuickNav(section.key)}
                borderRadius={14}
                borderWidth={1}
                borderColor={border}
                backgroundColor={surface}
                paddingVertical="$2"
                paddingHorizontal="$3"
                pressStyle={{ backgroundColor: surfaceMuted }}
                style={{ flexGrow: 1 }}
              >
                <XStack alignItems="center" justifyContent="center" space="$1.5">
                  <Text fontSize="$xs" fontWeight="700" color={text}>
                    {t(`events.tasks.sections.${section.key}`, section.key)}
                  </Text>
                  <PillBadge tone="muted">{section.count}</PillBadge>
                </XStack>
              </Button>
            ))}
          </XStack>
        </YStack>
      ) : null}

      {loading ? (
        <YStack space="$2">
          {Array.from({ length: 4 }).map((_, idx) => (
            <SkeletonCard key={`tsk-${idx}`} height={70} />
          ))}
        </YStack>
      ) : assignedTasks.length === 0 ? (
        <YStack space="$2">
          <MobileCard space="$2">
            <Text fontSize={13} fontWeight="700" color={text}>
              {t('events.tasks.emptyTitle', 'No tasks yet')}
            </Text>
            <Text fontSize={12} color={muted}>
              {t('events.tasks.emptyBody', 'Create tasks or import a pack for your event.')}
            </Text>
            <XStack space="$2">
              <CTAButton
                label={t('events.tasks.emptyActionTask', 'Add task')}
                onPress={() => setShowTaskSheet(true)}
                fullWidth={false}
              />
              <CTAButton
                label={t('events.tasks.emptyActionPack', 'Import pack')}
                tone="ghost"
                onPress={() => setShowCollectionSheet(true)}
                fullWidth={false}
              />
            </XStack>
          </MobileCard>
          <YGroup {...({ borderWidth: 1, borderColor: border, borderRadius: "$4", overflow: "hidden" } as any)}>
            <YGroup.Item>
              <ListItem
                hoverTheme
                pressTheme
                onPress={() => setShowTaskSheet(true)}
                title={
                  <XStack alignItems="center" space="$2">
                    <YStack
                      width={28}
                      height={28}
                      borderRadius={14}
                      backgroundColor={primary}
                      alignItems="center"
                      justifyContent="center"
                    >
                      <Plus size={14} color={surface} />
                    </YStack>
                    <Text fontSize={12.5} fontWeight="700" color={text}>
                      {t('events.tasks.addTask', 'Aufgabe hinzufügen')}
                    </Text>
                  </XStack>
                }
                subTitle={
                  <Text fontSize={11.5} color={muted}>
                    {t('events.tasks.addTaskHint', 'Erstelle eine neue Aufgabe für dieses Event.')}
                  </Text>
                }
                paddingVertical="$2"
                paddingHorizontal="$3"
                iconAfter={<ChevronRight size={16} color={muted} />}
              />
            </YGroup.Item>
            <YGroup.Item>
              <ListItem
                hoverTheme
                pressTheme
                onPress={() => setShowCollectionSheet(true)}
                title={
                  <XStack alignItems="center" space="$2">
                    <YStack
                      width={28}
                      height={28}
                      borderRadius={14}
                      backgroundColor={primary}
                      alignItems="center"
                      justifyContent="center"
                    >
                      <Plus size={14} color={surface} />
                    </YStack>
                    <Text fontSize={12.5} fontWeight="700" color={text}>
                      {t('events.tasks.import', 'Aufgabenpaket importieren')}
                    </Text>
                  </XStack>
                }
                subTitle={
                  <Text fontSize={11.5} color={muted}>
                    {t('events.tasks.importHint', 'Nutze vordefinierte Pakete für deinen Event-Typ.')}
                  </Text>
                }
                paddingVertical="$2"
                paddingHorizontal="$3"
                iconAfter={<ChevronRight size={16} color={muted} />}
              />
            </YGroup.Item>
          </YGroup>
        </YStack>
      ) : (
        <YStack space="$2">
          <div ref={assignedRef} />
          <YStack space="$2">
            <MobileInput
              type="search"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder={t('events.tasks.search', 'Search tasks')}
              compact
            />
            <Pressable onPress={() => setShowEmotionFilterSheet(true)}>
              <MobileCard borderColor={border} backgroundColor={surface} space="$2">
                <XStack alignItems="center" justifyContent="space-between">
                  <YStack>
                    <Text fontSize={12} fontWeight="700" color={text}>
                      {t('events.tasks.emotionFilter', 'Emotion filter')}
                    </Text>
                    <Text fontSize={11} color={muted}>
                      {emotionFilter
                        ? emotions.find((e) => String(e.id) === emotionFilter)?.name ?? t('events.tasks.customEmotion', 'Custom emotion')
                        : t('events.tasks.allEmotions', 'All')}
                    </Text>
                  </YStack>
                  <ChevronDown size={16} color={muted} />
                </XStack>
              </MobileCard>
            </Pressable>
          </YStack>

          <Text fontSize="$sm" color={muted}>
            {t('events.tasks.count', '{{count}} Tasks', { count: filteredTasks.length })}
          </Text>
          <YGroup {...({ borderWidth: 1, borderColor: border, borderRadius: "$4", overflow: "hidden" } as any)}>
            {filteredTasks.map((task, idx) => (
              <YGroup.Item key={task.id}>
                <ListItem
                  hoverTheme
                  pressTheme
                  onPress={() => startEdit(task)}
                  title={
                    <Text fontSize={12.5} fontWeight="600" color={text}>
                      {task.title}
                    </Text>
                  }
                  subTitle={
                    task.description ? (
                      <Text fontSize={11.5} fontWeight="400" color={subtle}>
                        {task.description}
                      </Text>
                    ) : null
                  }
                  iconAfter={
                    <XStack space="$2" alignItems="center">
                      {task.emotion ? (
                        <Tag label={task.emotion.name ?? ''} color={task.emotion.color ?? text} />
                      ) : null}
                      <Button
                        size="$2"
                        circular
                        backgroundColor={dangerBg}
                        borderWidth={1}
                        borderColor={`${danger}33`}
                        icon={<Trash2 size={14} color={dangerText} />}
                        aria-label={t('events.tasks.remove', 'Remove task')}
                        disabled={busyId === task.id}
                        onPress={(event: any) => {
                          event?.stopPropagation?.();
                          setDeleteCandidate(task);
                        }}
                      />
                      <ChevronRight size={14} color={subtle} />
                    </XStack>
                  }
                  paddingVertical="$2"
                  paddingHorizontal="$3"
                />
              </YGroup.Item>
            ))}
          </YGroup>
          <XStack justifyContent="space-between" alignItems="center" marginTop="$2">
            <div ref={libraryRef} />
            <Text fontSize={12.5} fontWeight="600" color={text}>
              {t('events.tasks.library', 'Weitere Aufgaben')}
            </Text>
            <Pressable onPress={() => setShowCollectionSheet(true)}>
              <Text fontSize={12} fontWeight="600" color={primary}>
                {t('events.tasks.import', 'Import Pack')}
              </Text>
            </Pressable>
          </XStack>
          <Pressable onPress={() => setExpandedLibrary((prev) => !prev)}>
            <Text fontSize={12} fontWeight="600" color={primary}>
              {expandedLibrary ? t('events.tasks.hideLibrary', 'Hide library') : t('events.tasks.viewAllLibrary', 'View all')}
            </Text>
          </Pressable>
          {library.length === 0 ? (
            <Text fontSize={12} fontWeight="500" color={subtle}>
              {t('events.tasks.libraryEmpty', 'Keine weiteren Aufgaben verfügbar.')}
            </Text>
          ) : (
            <YGroup {...({ borderWidth: 1, borderColor: border, borderRadius: "$4", overflow: "hidden" } as any)}>
              {(expandedLibrary ? library : library.slice(0, 6)).map((task, idx, arr) => (
                <YGroup.Item key={`lib-${task.id}`}>
                  <ListItem
                    hoverTheme
                    pressTheme
                    title={
                      <Text fontSize={12.5} fontWeight="600" color={text}>
                        {task.title}
                      </Text>
                    }
                    subTitle={
                      task.description ? (
                        <Text fontSize={11.5} fontWeight="400" color={subtle}>
                          {task.description}
                        </Text>
                      ) : null
                    }
                    iconAfter={
                      <XStack space="$1.5" alignItems="center">
                        <Pressable onPress={() => quickAssign(task.id)}>
                          <Text fontSize={12} fontWeight="600" color={primary}>
                            {assigningId === task.id ? t('common.processing', '...') : t('events.tasks.add', 'Add')}
                          </Text>
                        </Pressable>
                        <ChevronRight size={14} color={subtle} />
                      </XStack>
                    }
                    paddingVertical="$2"
                    paddingHorizontal="$3"
                  />
                </YGroup.Item>
              ))}
            </YGroup>
          )}
        </YStack>
      )}

      <MobileSheet
        open={showCollectionSheet}
        onClose={() => setShowCollectionSheet(false)}
        title={t('events.tasks.import', 'Aufgabenpaket importieren')}
        footer={null}
      >
        <YStack space="$2">
          {collections.length > 6 ? (
            <Pressable onPress={() => setExpandedCollections((prev) => !prev)}>
              <Text fontSize={12} fontWeight="600" color={primary}>
                {expandedCollections ? t('events.tasks.hideCollections', 'Hide collections') : t('events.tasks.showCollections', 'Show all')}
              </Text>
            </Pressable>
          ) : null}
          {collections.length === 0 ? (
            <Text fontSize={13} fontWeight="500" color={muted}>
              {t('events.tasks.collectionsEmpty', 'Keine Pakete vorhanden.')}
            </Text>
          ) : (
            <YGroup {...({ borderWidth: 1, borderColor: border, borderRadius: "$4", overflow: "hidden" } as any)}>
              {(expandedCollections ? collections : collections.slice(0, 6)).map((collection, idx, arr) => (
                <YGroup.Item key={collection.id}>
                  <ListItem
                    hoverTheme
                    pressTheme
                    title={
                      <Text fontSize={12.5} fontWeight="600" color={text}>
                        {collection.name}
                      </Text>
                    }
                    subTitle={
                      collection.description ? (
                        <Text fontSize={11.5} fontWeight="400" color={subtle}>
                          {collection.description}
                        </Text>
                      ) : null
                    }
                    iconAfter={
                      <XStack space="$1.5" alignItems="center">
                        <Pressable onPress={() => importCollection(collection.id)}>
                          <Text fontSize={12} fontWeight="600" color={primary}>
                            {t('events.tasks.import', 'Import')}
                          </Text>
                        </Pressable>
                        <ChevronRight size={14} color={subtle} />
                      </XStack>
                    }
                    paddingVertical="$2"
                    paddingHorizontal="$3"
                  />
                </YGroup.Item>
              ))}
            </YGroup>
          )}
        </YStack>
      </MobileSheet>

      <MobileSheet
        open={showTaskSheet}
        onClose={() => setShowTaskSheet(false)}
        title={t('events.tasks.addTask', 'Aufgabe hinzufügen')}
        footer={
          <CTAButton label={t('events.tasks.saveTask', 'Aufgabe speichern')} onPress={() => createNewTask()} />
        }
      >
        <YStack space="$2">
          <MobileField label={t('events.tasks.titleLabel', 'Titel')}>
            <MobileInput
              type="text"
              value={newTask.title}
              onChange={(e) => setNewTask((prev) => ({ ...prev, title: e.target.value }))}
              placeholder={t('events.tasks.titlePlaceholder', 'z.B. Erstes Gruppenfoto')}
            />
          </MobileField>
          <MobileField label={t('events.tasks.description', 'Beschreibung')}>
            <MobileTextArea
              value={newTask.description}
              onChange={(e) => setNewTask((prev) => ({ ...prev, description: e.target.value }))}
              placeholder={t('events.tasks.descriptionPlaceholder', 'Optionale Hinweise')}
              compact
              style={{ minHeight: 80 }}
            />
          </MobileField>
          <MobileField label={t('events.tasks.emotion', 'Emotion')}>
            <MobileSelect
              value={newTask.emotion_id}
              onChange={(e) => setNewTask((prev) => ({ ...prev, emotion_id: e.target.value }))}
            >
              <option value="">{t('events.tasks.emotionNone', 'Keine')}</option>
              {emotions.map((emotion) => (
                <option key={emotion.id} value={emotion.id}>
                  {emotion.name}
                </option>
              ))}
            </MobileSelect>
          </MobileField>
        </YStack>
      </MobileSheet>

      <MobileSheet
        open={showBulkSheet}
        onClose={() => setShowBulkSheet(false)}
        title={t('events.tasks.bulkAdd', 'Bulk add')}
        footer={<CTAButton label={t('events.tasks.saveTask', 'Aufgabe speichern')} onPress={() => handleBulkAdd()} />}
      >
        <YStack space="$2">
          <Text fontSize={12} color={muted}>
            {t('events.tasks.bulkHint', 'One task per line. These will be created and added to the event.')}
          </Text>
          <MobileTextArea
            value={bulkLines}
            onChange={(e) => setBulkLines(e.target.value)}
            placeholder={t('events.tasks.bulkPlaceholder', 'e.g.\nBride & groom portrait\nGroup photo main guests')}
            style={{ minHeight: 140, fontSize: 12.5 }}
          />
        </YStack>
      </MobileSheet>

      <MobileSheet
        open={showEmotionSheet}
        onClose={() => {
          setShowEmotionSheet(false);
          setEditingEmotion(null);
          setEmotionForm({ name: '', color: border });
        }}
        title={t('events.tasks.manageEmotions', 'Manage emotions')}
        footer={
          <CTAButton
            label={savingEmotion ? t('common.saving', 'Saving...') : t('events.tasks.saveEmotion', 'Emotion speichern')}
            onPress={() => saveEmotion()}
          />
        }
      >
        <YStack space="$2">
          <MobileField label={t('events.tasks.emotionName', 'Name')}>
            <MobileInput
              type="text"
              value={emotionForm.name}
              onChange={(e) => setEmotionForm((prev) => ({ ...prev, name: e.target.value }))}
              placeholder={t('events.tasks.emotionNamePlaceholder', 'z.B. Joy')}
            />
          </MobileField>
          <MobileField label={t('events.tasks.emotionColor', 'Farbe')}>
            <MobileInput
              type="color"
              value={emotionForm.color}
              onChange={(e) => setEmotionForm((prev) => ({ ...prev, color: e.target.value }))}
              style={{ padding: 0 }}
            />
          </MobileField>
          <YGroup {...({ borderWidth: 1, borderColor: border, borderRadius: "$4", overflow: "hidden" } as any)}>
            {emotions.map((em, idx) => (
              <YGroup.Item key={`emo-${em.id}`}>
                <ListItem
                  hoverTheme
                  pressTheme
                  title={
                    <XStack alignItems="center" space="$2">
                      <Tag label={em.name ?? ''} color={em.color ?? border} />
                    </XStack>
                  }
                  iconAfter={
                    <XStack space="$2">
                      <Pressable
                        onPress={() => {
                          setEditingEmotion(em);
                          setEmotionForm({ name: em.name ?? '', color: em.color ?? border });
                        }}
                      >
                        <Pencil size={14} color={primary} />
                      </Pressable>
                      <Pressable onPress={() => removeEmotion(em.id)}>
                        <Trash2 size={14} color={danger} />
                      </Pressable>
                      <ChevronRight size={14} color={subtle} />
                    </XStack>
                  }
                  paddingVertical="$2"
                  paddingHorizontal="$3"
                />
              </YGroup.Item>
            ))}
          </YGroup>
        </YStack>
      </MobileSheet>

      <MobileSheet
        open={showEmotionFilterSheet}
        onClose={() => setShowEmotionFilterSheet(false)}
        title={t('events.tasks.emotionFilter', 'Emotion filter')}
        footer={
          <CTAButton label={t('common.close', 'Close')} onPress={() => setShowEmotionFilterSheet(false)} />
        }
      >
        <RadioGroup
          value={emotionFilter}
          onValueChange={(val) => {
            setEmotionFilter(val);
            setShowEmotionFilterSheet(false);
          }}
        >
          <YStack space="$2">
            <XStack alignItems="center" space="$2">
              <RadioGroup.Item value="">
                <RadioGroup.Indicator />
              </RadioGroup.Item>
              <Text fontSize={12.5} color={text}>
                {t('events.tasks.allEmotions', 'All')}
              </Text>
            </XStack>
            {emotions.map((emotion) => (
              <XStack key={`emo-filter-${emotion.id}`} alignItems="center" space="$2">
                <RadioGroup.Item value={String(emotion.id)}>
                  <RadioGroup.Indicator />
                </RadioGroup.Item>
                <Text fontSize={12.5} color={emotion.color ?? text}>
                  {emotion.name ?? ''}
                </Text>
              </XStack>
            ))}
          </YStack>
        </RadioGroup>
      </MobileSheet>

      <AlertDialog
        open={Boolean(deleteCandidate)}
        onOpenChange={(open) => {
          if (!open) {
            setDeleteCandidate(null);
          }
        }}
      >
        <AlertDialog.Portal>
          <AlertDialog.Overlay backgroundColor={`${overlay}66` as any} />
          <AlertDialog.Content
            {...({ borderRadius: 20 } as any)}
            borderWidth={1}
            borderColor={border}
            backgroundColor={surface}
            padding="$4"
            maxWidth={420}
            width="90%"
          >
            <YStack space="$3">
              <AlertDialog.Title>
                <Text fontSize="$md" fontWeight="800" color={text}>
                  {t('events.tasks.removeTitle', 'Remove task?')}
                </Text>
              </AlertDialog.Title>
              <AlertDialog.Description>
                <Text fontSize="$sm" color={muted}>
                  {deleteCandidate
                    ? t('events.tasks.removeBody', 'This will remove "{{title}}" from the event.', { title: deleteCandidate.title })
                    : t('events.tasks.removeBodyFallback', 'This will remove the task from the event.')}
                </Text>
              </AlertDialog.Description>
              <XStack space="$2" justifyContent="flex-end">
                <AlertDialog.Cancel asChild>
                  <CTAButton
                    label={t('common.cancel', 'Cancel')}
                    tone="ghost"
                    fullWidth={false}
                    onPress={() => setDeleteCandidate(null)}
                  />
                </AlertDialog.Cancel>
                <AlertDialog.Action asChild>
                  <CTAButton
                    label={t('events.tasks.remove', 'Remove')}
                    tone="danger"
                    fullWidth={false}
                    onPress={() => confirmDeleteTask()}
                  />
                </AlertDialog.Action>
              </XStack>
            </YStack>
          </AlertDialog.Content>
        </AlertDialog.Portal>
      </AlertDialog>

      <FloatingActionButton
        onPress={() => setShowFabMenu(true)}
        label={t('events.tasks.add', 'Add')}
        icon={Plus}
      />

      <MobileSheet
        open={showFabMenu}
        onClose={() => setShowFabMenu(false)}
        title={t('events.tasks.actions', 'Aktionen')}
        footer={null}
      >
        <YGroup {...({ borderWidth: 1, borderColor: border, borderRadius: "$4", overflow: "hidden" } as any)}>
          <YGroup.Item>
            <ListItem
              hoverTheme
              pressTheme
              title={
                <Text fontSize={12.5} fontWeight="600" color={text}>
                  {t('events.tasks.addTask', 'Aufgabe hinzufügen')}
                </Text>
              }
              onPress={() => {
                setShowFabMenu(false);
                setShowTaskSheet(true);
              }}
              paddingVertical="$2"
              paddingHorizontal="$3"
              iconAfter={<ChevronRight size={14} color={subtle} />}
            />
          </YGroup.Item>
          <YGroup.Item>
            <ListItem
              hoverTheme
              pressTheme
              title={
                <Text fontSize={12.5} fontWeight="600" color={text}>
                  {t('events.tasks.bulkAdd', 'Bulk add')}
                </Text>
              }
              onPress={() => {
                setShowFabMenu(false);
                setShowBulkSheet(true);
              }}
              paddingVertical="$2"
              paddingHorizontal="$3"
              iconAfter={<ChevronRight size={14} color={subtle} />}
            />
          </YGroup.Item>
          <YGroup.Item>
            <ListItem
              hoverTheme
              pressTheme
              title={
                <Text fontSize={12.5} fontWeight="600" color={text}>
                  {t('events.tasks.manageEmotions', 'Manage emotions')}
                </Text>
              }
              subTitle={
                <Text fontSize={11.5} fontWeight="400" color={subtle}>
                  {t('events.tasks.manageEmotionsHint', 'Filter and keep your taxonomy tidy.')}
                </Text>
              }
              onPress={() => {
                setShowFabMenu(false);
                setShowEmotionSheet(true);
              }}
              paddingVertical="$2"
              paddingHorizontal="$3"
              iconAfter={<ChevronRight size={14} color={subtle} />}
            />
          </YGroup.Item>
        </YGroup>
      </MobileSheet>
    </MobileShell>
  );
}
