import { useState } from "react";
import { FlatList, RefreshControl, StyleSheet, Text, TextInput, View } from "react-native";
import { haptic } from "../lib/haptics";
import { parseQuickAdd } from "../lib/quickadd";
import { createTask, 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,
  capture,
  emptyHint,
}: {
  status: TaskStatus;
  capture?: boolean;
  emptyHint: string;
}) {
  const store = useStore();
  const [refreshing, setRefreshing] = useState(false);
  const [draft, setDraft] = useState("");
  const tasks = tasksByStatus(store, status);

  const add = () => {
    if (!draft.trim()) return;
    const parsed = parseQuickAdd(draft, store.projects);
    if (!parsed.title) return;
    setDraft("");
    haptic.tap();
    createTask({ ...parsed, status });
  };

  return (
    <View style={s.screen}>
      {capture && (
        <TextInput
          style={s.capture}
          placeholder="Capture anything…"
          placeholderTextColor={C.muted}
          value={draft}
          onChangeText={setDraft}
          onSubmitEditing={add}
          submitBehavior="submit"
          returnKeyType="done"
        />
      )}
      <FlatList
        data={tasks}
        keyExtractor={(t) => t.id}
        renderItem={({ item }) => <TaskRow task={item} uncheckTo={status} />}
        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 },
  capture: {
    margin: 12,
    marginBottom: 4,
    padding: 14,
    borderRadius: 12,
    backgroundColor: C.surface,
    color: C.text,
    fontSize: 16,
    borderWidth: 1,
    borderColor: C.border,
  },
  empty: { color: C.muted, textAlign: "center", marginTop: 48, fontSize: 15 },
});
