import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useState } from "react";
import { FlatList, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { Button, Chips } from "../../components/ui";
import { createTask, dropProject, updateProject, updateTask } from "../../lib/store";
import { C } from "../../lib/theme";
import { useStore } from "../../lib/useStore";
import type { ProjectStatus } from "../../lib/types";

const STATUSES: ProjectStatus[] = ["active", "someday", "completed"];

export default function ProjectDetail() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const router = useRouter();
  const store = useStore();
  const [draft, setDraft] = useState("");

  const project = store.projects.find((p) => p.id === id);
  if (!project) return <Text style={{ color: C.muted, margin: 16 }}>Project not found.</Text>;

  const tasks = store.tasks
    .filter((t) => t.project_id === id && t.status !== "done" && t.status !== "trashed")
    .sort((a, b) => a.sort_order - b.sort_order || b.created_at.localeCompare(a.created_at));

  const add = () => {
    const title = draft.trim();
    if (!title) return;
    setDraft("");
    createTask({ title, status: "next", project_id: id });
  };

  return (
    <View style={{ flex: 1, backgroundColor: C.bg }}>
      <Stack.Screen options={{ title: project.name }} />
      <View style={{ padding: 16, paddingBottom: 0 }}>
        <Chips
          label="Status"
          options={STATUSES}
          value={project.status}
          onChange={(status) => updateProject(project.id, { status })}
        />
      </View>
      <TextInput
        style={s.capture}
        placeholder="Add next action…"
        placeholderTextColor={C.muted}
        value={draft}
        onChangeText={setDraft}
        onSubmitEditing={add}
        submitBehavior="submit"
        returnKeyType="done"
      />
      <FlatList
        data={tasks}
        keyExtractor={(t) => t.id}
        renderItem={({ item }) => (
          <Pressable style={s.row} onPress={() => router.push(`/task/${item.id}`)}>
            <Pressable
              style={s.checkbox}
              hitSlop={10}
              onPress={() => updateTask(item.id, { status: "done" })}
            />
            <View style={{ flex: 1 }}>
              <Text style={s.title}>{item.title}</Text>
              <Text style={s.meta}>{[item.status, item.context].filter(Boolean).join("  ·  ")}</Text>
            </View>
          </Pressable>
        )}
        ListEmptyComponent={<Text style={s.empty}>No open tasks in this project.</Text>}
      />
      <View style={{ padding: 16 }}>
        <Button
          title="Drop project"
          danger
          onPress={() => {
            dropProject(project.id);
            router.back();
          }}
        />
      </View>
    </View>
  );
}

const s = StyleSheet.create({
  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 },
  title: { color: C.text, fontSize: 16 },
  meta: { color: C.muted, fontSize: 13, marginTop: 2 },
  empty: { color: C.muted, textAlign: "center", marginTop: 48 },
});
