import { useLocalSearchParams, useRouter } from "expo-router";
import { useEffect, useState } from "react";
import { ScrollView, Text } from "react-native";
import { Button, Chips, Field } from "../../components/ui";
import { api } from "../../lib/api";
import { C } from "../../lib/theme";
import type { Project, Task, TaskStatus } from "../../lib/types";

const STATUSES: TaskStatus[] = ["inbox", "next", "waiting", "scheduled", "someday", "done"];

export default function TaskDetail() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const router = useRouter();
  const [task, setTask] = useState<Task | null>(null);
  const [projects, setProjects] = useState<Project[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    Promise.all([api.tasks.get(id), api.projects.list()])
      .then(([t, ps]) => {
        setTask(t);
        setProjects(ps.filter((p) => p.status === "active" || p.id === t.project_id));
      })
      .catch((e) => setError(e instanceof Error ? e.message : String(e)));
  }, [id]);

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

  const set = (patch: Partial<Task>) => setTask({ ...task, ...patch });

  const save = async () => {
    try {
      await api.tasks.update(task.id, {
        title: task.title,
        notes: task.notes,
        status: task.status,
        project_id: task.project_id,
        context: task.context,
        waiting_for: task.waiting_for,
        due_date: task.due_date,
        defer_date: task.defer_date,
      });
      router.back();
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    }
  };

  const trash = async () => {
    await api.tasks.trash(task.id);
    router.back();
  };

  const projectOptions = ["none", ...projects.map((p) => p.id)];
  const projectLabels = Object.fromEntries([["none", "None"], ...projects.map((p) => [p.id, p.name])]);

  return (
    <ScrollView style={{ flex: 1, backgroundColor: C.bg }} contentContainerStyle={{ padding: 16 }}>
      <Field label="Title" value={task.title} onChangeText={(v) => set({ title: v })} />
      <Chips label="List" options={STATUSES} value={task.status} onChange={(status) => set({ status })} />
      <Chips
        label="Project"
        options={projectOptions}
        labels={projectLabels}
        value={task.project_id ?? "none"}
        onChange={(v) => set({ project_id: v === "none" ? null : v })}
      />
      <Field
        label="Context"
        value={task.context ?? ""}
        onChangeText={(v) => set({ context: v || null })}
        placeholder="@home, @computer, @errands…"
        autoCapitalize="none"
      />
      {task.status === "waiting" && (
        <Field
          label="Waiting for"
          value={task.waiting_for ?? ""}
          onChangeText={(v) => set({ waiting_for: v || null })}
          placeholder="Who or what?"
        />
      )}
      <Field
        label="Due date"
        value={task.due_date ?? ""}
        onChangeText={(v) => set({ due_date: v || null })}
        placeholder="YYYY-MM-DD"
        autoCapitalize="none"
      />
      <Field
        label="Defer until"
        value={task.defer_date ?? ""}
        onChangeText={(v) => set({ defer_date: v || null })}
        placeholder="YYYY-MM-DD"
        autoCapitalize="none"
      />
      <Field
        label="Notes"
        value={task.notes}
        onChangeText={(v) => set({ notes: v })}
        multiline
        style={{ minHeight: 80, textAlignVertical: "top" }}
      />
      <Button title="Save" onPress={save} />
      <Button title="Delete" onPress={trash} danger />
    </ScrollView>
  );
}
