import { useRouter } from "expo-router";
import { useState } from "react";
import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native";
import DateField from "../components/DateField";
import PriorityChips from "../components/PriorityChips";
import { Chips, Field } from "../components/ui";
import { haptic } from "../lib/haptics";
import { activeProjects, createTask } from "../lib/store";
import { C } from "../lib/theme";
import { useStore } from "../lib/useStore";
import type { Task, TaskStatus } from "../lib/types";

const BOXES: { key: TaskStatus; label: string }[] = [
  { key: "next", label: "Next up" },
  { key: "waiting", label: "Waiting" },
  { key: "someday", label: "Someday" },
];

const ESTIMATES = [15, 30, 45, 60, 90, 120];

export default function AddTask() {
  const router = useRouter();
  const store = useStore();
  const [title, setTitle] = useState("");
  const [notes, setNotes] = useState("");
  const [priority, setPriority] = useState<Task["priority"] | null>(null);
  const [estimate, setEstimate] = useState<number | null>(null);
  const [due, setDue] = useState("");
  const [box, setBox] = useState<TaskStatus>("next");
  const [projectId, setProjectId] = useState<string | null>(null);

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

  // Every task must be born fully scoped: title + priority + due date.
  const dueValid = /^\d{4}-\d{2}-\d{2}$/.test(due.trim());
  const ready = title.trim().length > 0 && priority !== null && dueValid;

  const save = () => {
    if (!ready || priority === null) return;
    createTask({
      title: title.trim(),
      notes,
      status: box,
      priority,
      estimate_min: estimate,
      due_date: due.trim(),
      project_id: projectId,
    });
    haptic.success();
    router.back();
  };

  return (
    <ScrollView style={{ flex: 1, backgroundColor: C.bg }} contentContainerStyle={{ padding: 16 }}>
      <Field label="Task" value={title} onChangeText={setTitle} placeholder="What needs doing?" autoFocus />
      <Field
        label="Description"
        value={notes}
        onChangeText={setNotes}
        placeholder="Details, links, notes…"
        multiline
        style={{ minHeight: 64, textAlignVertical: "top" }}
      />
      <PriorityChips value={priority} onChange={setPriority} />
      <DateField label="Due date" value={due || null} onChange={(v) => setDue(v ?? "")} />
      <View style={{ marginBottom: 14 }}>
        <Text style={s.label}>Estimated time</Text>
        <View style={s.rowWrap}>
          {ESTIMATES.map((m) => {
            const active = estimate === m;
            return (
              <Pressable
                key={m}
                style={[s.chip, active && s.chipActive]}
                onPress={() => {
                  haptic.select();
                  setEstimate(active ? null : m);
                }}
              >
                <Text style={[s.chipText, active && { color: C.text }]}>
                  {m < 60 ? `${m}m` : m % 60 ? `${Math.floor(m / 60)}h${m % 60}` : `${m / 60}h`}
                </Text>
              </Pressable>
            );
          })}
        </View>
      </View>
      <Chips
        label="Box"
        options={BOXES.map((b) => b.key)}
        labels={Object.fromEntries(BOXES.map((b) => [b.key, b.label]))}
        value={box}
        onChange={(b) => {
          haptic.select();
          setBox(b);
        }}
      />
      <Chips
        label="Project"
        options={projectOptions}
        labels={projectLabels}
        value={projectId ?? "none"}
        onChange={(v) => setProjectId(v === "none" ? null : v)}
      />
      <Pressable style={[s.save, !ready && s.saveDisabled]} onPress={save} disabled={!ready}>
        <Text style={[s.saveText, !ready && { color: C.muted }]}>
          {ready ? "Add task" : "Needs a title, priority & due date"}
        </Text>
      </Pressable>
    </ScrollView>
  );
}

const s = StyleSheet.create({
  label: { color: C.muted, fontSize: 13, marginBottom: 6, textTransform: "uppercase", letterSpacing: 0.5 },
  rowWrap: { flexDirection: "row", flexWrap: "wrap", gap: 8, marginBottom: 12 },
  chip: {
    paddingVertical: 8,
    paddingHorizontal: 14,
    borderRadius: 20,
    backgroundColor: C.surface,
    borderWidth: 1,
    borderColor: C.border,
  },
  chipActive: { backgroundColor: C.surface2, borderColor: C.accent },
  chipText: { color: C.muted, fontSize: 14 },
  save: {
    backgroundColor: C.accent,
    borderRadius: 10,
    padding: 14,
    alignItems: "center",
    marginTop: 8,
    marginBottom: 24,
  },
  saveDisabled: { backgroundColor: C.surface },
  saveText: { color: C.text, fontSize: 16, fontWeight: "600" },
});
