import { useState } from "react";
import { RefreshControl, StyleSheet, Text, View } from "react-native";
import DraggableFlatList, { ScaleDecorator } from "react-native-draggable-flatlist";
import { haptic } from "../lib/haptics";
import { reorderTask, sync, tasksByStatus } from "../lib/store";
import { C } from "../lib/theme";
import { useStore } from "../lib/useStore";
import type { TaskStatus } from "../lib/types";
import TaskRow from "./TaskRow";

export default function TaskListScreen({
  status,
  emptyHint,
}: {
  status: TaskStatus;
  emptyHint: string;
}) {
  const store = useStore();
  const [refreshing, setRefreshing] = useState(false);
  const tasks = tasksByStatus(store, status);

  return (
    <View style={s.screen}>
      <DraggableFlatList
        data={tasks}
        keyExtractor={(t) => t.id}
        activationDistance={12}
        onDragBegin={() => haptic.pickup()}
        onDragEnd={({ data, from, to }) => {
          if (from !== to) {
            haptic.success();
            reorderTask(data[to].id, status, to);
          }
        }}
        renderItem={({ item, drag, isActive }) => (
          <ScaleDecorator activeScale={1.03}>
            <View style={isActive && s.activeRow}>
              <TaskRow task={item} uncheckTo={status} onLongPress={drag} />
            </View>
          </ScaleDecorator>
        )}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            tintColor={C.muted}
            onRefresh={async () => {
              setRefreshing(true);
              await sync();
              setRefreshing(false);
            }}
          />
        }
        ListEmptyComponent={<Text style={s.empty}>{emptyHint}</Text>}
        contentContainerStyle={{ paddingBottom: 32 }}
      />
    </View>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1, backgroundColor: C.bg },
  activeRow: { backgroundColor: C.surface2, borderRadius: 12 },
  empty: { color: C.muted, textAlign: "center", marginTop: 48, fontSize: 15 },
});
