import { useRouter } from "expo-router";
import { useState } from "react";
import { FlatList, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { activeProjects, createProject, openTaskCount } from "../lib/store";
import { C } from "../lib/theme";
import { useStore } from "../lib/useStore";

export default function Projects() {
  const router = useRouter();
  const store = useStore();
  const [draft, setDraft] = useState("");
  const projects = activeProjects(store);

  const add = () => {
    const name = draft.trim();
    if (!name) return;
    setDraft("");
    createProject({ name });
  };

  return (
    <View style={s.screen}>
      <TextInput
        style={s.capture}
        placeholder="New project…"
        placeholderTextColor={C.muted}
        value={draft}
        onChangeText={setDraft}
        onSubmitEditing={add}
        returnKeyType="done"
      />
      <FlatList
        data={projects}
        keyExtractor={(p) => p.id}
        renderItem={({ item }) => (
          <Pressable style={s.row} onPress={() => router.push(`/project/${item.id}`)}>
            <View style={{ flex: 1 }}>
              <Text style={s.title}>{item.name}</Text>
              <Text style={s.meta}>
                {item.status}  ·  {openTaskCount(store, item.id)} open
              </Text>
            </View>
            <Text style={{ color: C.muted }}>›</Text>
          </Pressable>
        )}
        ListEmptyComponent={<Text style={s.empty}>No projects yet.</Text>}
      />
    </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",
    paddingVertical: 14,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: C.border,
  },
  title: { color: C.text, fontSize: 16 },
  meta: { color: C.muted, fontSize: 13, marginTop: 2 },
  empty: { color: C.muted, textAlign: "center", marginTop: 48 },
});
