import { useRouter } from "expo-router";
import { useState } from "react";
import {
  FlatList,
  Pressable,
  RefreshControl,
  StyleSheet,
  Text,
  TextInput,
  View,
} from "react-native";
import { createTask, sync, tasksByStatus, updateTask } from "../lib/store";
import { C } from "../lib/theme";
import { useStore } from "../lib/useStore";
import type { Task, TaskStatus } from "../lib/types";

function TaskRow({ task, listStatus }: { task: Task; listStatus: TaskStatus }) {
  const router = useRouter();
  const meta = [task.context, task.waiting_for && `→ ${task.waiting_for}`, task.due_date && `due ${task.due_date}`]
    .filter(Boolean)
    .join("  ·  ");
  return (
    <Pressable style={s.row} onPress={() => router.push(`/task/${task.id}`)}>
      <Pressable
        style={s.checkbox}
        hitSlop={10}
        onPress={() => updateTask(task.id, { status: task.status === "done" ? listStatus : "done" })}
      >
        {task.status === "done" && <View style={s.checkboxFill} />}
      </Pressable>
      <View style={{ flex: 1 }}>
        <Text style={s.title} numberOfLines={2}>
          {task.title}
        </Text>
        {!!meta && <Text style={s.meta}>{meta}</Text>}
      </View>
    </Pressable>
  );
}

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 = () => {
    const title = draft.trim();
    if (!title) return;
    setDraft("");
    createTask({ title, 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} listStatus={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,
  },
  row: {
    flexDirection: "row",
    alignItems: "center",
    gap: 12,
    paddingVertical: 14,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: C.border,
  },
  checkbox: {
    width: 22,
    height: 22,
    borderRadius: 11,
    borderWidth: 2,
    borderColor: C.muted,
    alignItems: "center",
    justifyContent: "center",
  },
  checkboxFill: { width: 12, height: 12, borderRadius: 6, backgroundColor: C.done },
  title: { color: C.text, fontSize: 16 },
  meta: { color: C.muted, fontSize: 13, marginTop: 2 },
  empty: { color: C.muted, textAlign: "center", marginTop: 48, fontSize: 15 },
});
