import { useFocusEffect, useRouter } from "expo-router";
import { useCallback, useState } from "react";
import {
  FlatList,
  Pressable,
  RefreshControl,
  StyleSheet,
  Text,
  TextInput,
  View,
} from "react-native";
import { api } from "../lib/api";
import { C } from "../lib/theme";
import type { Task, TaskStatus } from "../lib/types";

function TaskRow({ task, onToggle }: { task: Task; onToggle: (t: Task) => void }) {
  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={() => onToggle(task)}>
        {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 [tasks, setTasks] = useState<Task[]>([]);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [draft, setDraft] = useState("");

  const load = useCallback(async () => {
    try {
      setTasks(await api.tasks.list({ status }));
      setError(null);
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    }
  }, [status]);

  useFocusEffect(
    useCallback(() => {
      load();
    }, [load]),
  );

  const add = async () => {
    const title = draft.trim();
    if (!title) return;
    setDraft("");
    setTasks((cur) => [{ id: `tmp-${title}`, title, status } as Task, ...cur]);
    try {
      await api.tasks.create({ title, status });
    } finally {
      load();
    }
  };

  const toggle = async (task: Task) => {
    const done = task.status !== "done";
    setTasks((cur) => cur.filter((t) => t.id !== task.id));
    try {
      await api.tasks.update(task.id, { status: done ? "done" : status });
    } finally {
      load();
    }
  };

  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"
        />
      )}
      {error && <Text style={s.error}>{error}</Text>}
      <FlatList
        data={tasks}
        keyExtractor={(t) => t.id}
        renderItem={({ item }) => <TaskRow task={item} onToggle={toggle} />}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            tintColor={C.muted}
            onRefresh={async () => {
              setRefreshing(true);
              await load();
              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 },
  error: { color: C.danger, marginHorizontal: 16, marginTop: 8 },
});
