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 { SizableText as Text } from '@tamagui/text';
import { ListItem } from '@tamagui/list-item';
import { Pressable } from '@tamagui/react-native-web-lite';
import { MobileShell, HeaderActionButton } from './components/MobileShell';
import { MobileCard, CTAButton, SkeletonCard } 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 { useTheme } from '@tamagui/core';
import { RadioGroup } from '@tamagui/radio-group';

function InlineSeparator() {
  const theme = useTheme();
  return <XStack height={1} opacity={0.7} marginLeft="$3" backgroundColor={theme.borderColor?.val ?? '#e5e7eb'} />;
}

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 theme = useTheme();
  const text = String(theme.color12?.val ?? theme.color?.val ?? '#e5e7eb');
  const muted = String(theme.gray11?.val ?? theme.gray?.val ?? '#cbd5e1');
  const subtle = String(theme.gray8?.val ?? '#94a3b8');
  const border = String(theme.borderColor?.val ?? '#334155');
  const primary = String(theme.primary?.val ?? '#007AFF');
  const danger = String(theme.red10?.val ?? '#ef4444');
  const surface = String(theme.surface?.val ?? '#ffffff');
  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 [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);
  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 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);
    }
  }

  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={() => navigate(-1)}
      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>
        </MobileCard>
      ) : 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.empty', 'Noch keine Aufgaben zugewiesen.')}
            </Text>
            <Text fontSize={12} color={muted}>
              {t('events.tasks.emptyHint', 'Lege jetzt Tasks an oder importiere ein Paket.')}
            </Text>
          </MobileCard>
          <YStack borderWidth={1} borderColor={border} borderRadius="$4" overflow="hidden">
            <Pressable onPress={() => setShowTaskSheet(true)}>
              <ListItem
                hoverTheme
                pressTheme
                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} />}
              />
            </Pressable>
            <InlineSeparator />
            <Pressable onPress={() => setShowCollectionSheet(true)}>
              <ListItem
                hoverTheme
                pressTheme
                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} />}
              />
            </Pressable>
          </YStack>
        </YStack>
      ) : (
        <YStack space="$2">
          <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>
          <YStack borderWidth={1} borderColor={border} borderRadius="$4" overflow="hidden">
            {filteredTasks.map((task, idx) => (
              <React.Fragment key={task.id}>
                <Pressable onPress={() => startEdit(task)}>
                  <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="$2" alignItems="flex-start">
                        {task.emotion ? (
                          <Tag label={task.emotion.name ?? ''} color={task.emotion.color ?? text} />
                        ) : null}
                        <Pressable disabled={busyId === task.id} onPress={() => detachTask(task.id)}>
                          <Trash2 size={14} color={danger} />
                        </Pressable>
                        <ChevronRight size={14} color={subtle} />
                      </XStack>
                    }
                    paddingVertical="$2"
                    paddingHorizontal="$3"
                  />
                </Pressable>
                {idx < assignedTasks.length - 1 ? <InlineSeparator /> : null}
              </React.Fragment>
            ))}
          </YStack>
          <XStack justifyContent="space-between" alignItems="center" marginTop="$2">
            <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>
          ) : (
          <YStack borderWidth={1} borderColor={border} borderRadius="$4" overflow="hidden">
              {(expandedLibrary ? library : library.slice(0, 6)).map((task, idx, arr) => (
                <React.Fragment 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"
                  />
                  {idx < arr.length - 1 ? <InlineSeparator /> : null}
                </React.Fragment>
              ))}
            </YStack>
          )}
        </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>
          ) : (
          <YStack borderWidth={1} borderColor={border} borderRadius="$4" overflow="hidden">
              {(expandedCollections ? collections : collections.slice(0, 6)).map((collection, idx, arr) => (
                <React.Fragment 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"
                    />
                  {idx < arr.length - 1 ? <InlineSeparator /> : null}
                </React.Fragment>
              ))}
            </YStack>
          )}
        </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>
          <YStack space="$2">
            {emotions.map((em) => (
              <ListItem
                key={`emo-${em.id}`}
                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>
                }
              />
            ))}
          </YStack>
        </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>

  <Pressable
    onPress={() => setShowFabMenu(true)}
    style={{
      position: 'fixed',
      right: 20,
      bottom: 'calc(env(safe-area-inset-bottom, 0px) + 96px)',
      width: 56,
      height: 56,
      borderRadius: 28,
      backgroundColor: primary,
      justifyContent: 'center',
      alignItems: 'center',
      boxShadow: '0 10px 25px rgba(0,122,255,0.35)',
      zIndex: 60,
    }}
  >
    <Plus size={20} color={surface} />
  </Pressable>

      <MobileSheet
        open={showFabMenu}
        onClose={() => setShowFabMenu(false)}
        title={t('events.tasks.actions', 'Aktionen')}
        footer={null}
      >
        <YStack space="$1">
          <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} />}
          />
          <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} />}
          />
          <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} />}
          />
        </YStack>
      </MobileSheet>
    </MobileShell>
  );
}
