import { Stack, useFocusEffect, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useState } from "react";
import { FlatList, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { Button, Chips } from "../../components/ui";
import { api } from "../../lib/api";
import { C } from "../../lib/theme";
import type { Project, ProjectStatus, Task } from "../../lib/types";

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

export default function ProjectDetail() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const router = useRouter();
  const [project, setProject] = useState<Project | null>(null);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [draft, setDraft] = useState("");

  const load = useCallback(async () => {
    const [ps, ts] = await Promise.all([api.projects.list(), api.tasks.list({ project_id: id })]);
    setProject(ps.find((p) => p.id === id) ?? null);
    setTasks(ts.filter((t) => t.status !== "done"));
  }, [id]);

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

  if (!project) return <Text style={{ color: C.muted, margin: 16 }}>Loading…</Text>;

  const add = async () => {
    const title = draft.trim();
    if (!title) return;
    setDraft("");
    await api.tasks.create({ title, status: "next", project_id: id });
    load();
  };

  const complete = async (t: Task) => {
    setTasks((cur) => cur.filter((x) => x.id !== t.id));
    await api.tasks.update(t.id, { status: "done" });
    load();
  };

  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={async (status) => {
            setProject({ ...project, status });
            await api.projects.update(project.id, { status });
          }}
        />
      </View>
      <TextInput
        style={s.capture}
        placeholder="Add next action…"
        placeholderTextColor={C.muted}
        value={draft}
        onChangeText={setDraft}
        onSubmitEditing={add}
        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={() => complete(item)} />
            <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={async () => {
            await api.projects.drop(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 },
});
