import { useLocalSearchParams, useRouter } from "expo-router";
import { useState } from "react";
import { ScrollView, Text } from "react-native";
import PriorityChips from "../../components/PriorityChips";
import { Button, Chips, Field } from "../../components/ui";
import { activeProjects, trashTask, updateTask } from "../../lib/store";
import { C } from "../../lib/theme";
import { useStore } from "../../lib/useStore";
import type { 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 store = useStore();
  const original = store.tasks.find((t) => t.id === id);
  // Draft is local to the screen; nothing is written until Save.
  const [draft, setDraft] = useState<Task | null>(original ?? null);

  if (!draft) return <Text style={{ color: C.muted, margin: 16 }}>Task not found.</Text>;

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

  const save = () => {
    updateTask(draft.id, {
      title: draft.title,
      notes: draft.notes,
      status: draft.status,
      project_id: draft.project_id,
      context: draft.context,
      waiting_for: draft.waiting_for,
      due_date: draft.due_date,
      defer_date: draft.defer_date,
      priority: draft.priority,
      estimate_min: draft.estimate_min,
    });
    router.back();
  };

  const projects = activeProjects(store).filter((p) => p.status === "active" || p.id === draft.project_id);
  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={draft.title} onChangeText={(v) => set({ title: v })} />
      <PriorityChips value={draft.priority} onChange={(priority) => set({ priority })} />
      <Field
        label="Estimate (minutes)"
        value={draft.estimate_min ? String(draft.estimate_min) : ""}
        onChangeText={(v) => set({ estimate_min: Number(v.replace(/\D/g, "")) || null })}
        placeholder="30"
        keyboardType="number-pad"
      />
      <Chips label="List" options={STATUSES} value={draft.status} onChange={(status) => set({ status })} />
      <Chips
        label="Project"
        options={projectOptions}
        labels={projectLabels}
        value={draft.project_id ?? "none"}
        onChange={(v) => set({ project_id: v === "none" ? null : v })}
      />
      <Field
        label="Context"
        value={draft.context ?? ""}
        onChangeText={(v) => set({ context: v || null })}
        placeholder="@home, @computer, @errands…"
        autoCapitalize="none"
      />
      {draft.status === "waiting" && (
        <Field
          label="Waiting for"
          value={draft.waiting_for ?? ""}
          onChangeText={(v) => set({ waiting_for: v || null })}
          placeholder="Who or what?"
        />
      )}
      <Field
        label="Due date"
        value={draft.due_date ?? ""}
        onChangeText={(v) => set({ due_date: v || null })}
        placeholder="YYYY-MM-DD"
        autoCapitalize="none"
      />
      <Field
        label="Defer until"
        value={draft.defer_date ?? ""}
        onChangeText={(v) => set({ defer_date: v || null })}
        placeholder="YYYY-MM-DD"
        autoCapitalize="none"
      />
      <Field
        label="Notes"
        value={draft.notes}
        onChangeText={(v) => set({ notes: v })}
        multiline
        style={{ minHeight: 80, textAlignVertical: "top" }}
      />
      <Button title="Save" onPress={save} />
      <Button
        title="Delete"
        danger
        onPress={() => {
          trashTask(draft.id);
          router.back();
        }}
      />
    </ScrollView>
  );
}
