import { useRouter } from "expo-router";
import { useState } from "react";
import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native";
import PriorityChips from "../components/PriorityChips";
import { Button, 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: "inbox", label: "Inbox" },
  { key: "next", label: "Next up" },
  { key: "waiting", label: "Waiting" },
  { key: "someday", label: "Someday" },
];

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

function isoToday(offset = 0): string {
  const d = new Date();
  d.setDate(d.getDate() + offset);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

export default function AddTask() {
  const router = useRouter();
  const store = useStore();
  const [title, setTitle] = useState("");
  const [notes, setNotes] = useState("");
  const [priority, setPriority] = useState<Task["priority"]>(4);
  const [estimate, setEstimate] = useState<number | null>(null);
  const [due, setDue] = useState("");
  const [box, setBox] = useState<TaskStatus>("inbox");
  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])]);

  const save = () => {
    if (!title.trim()) return;
    createTask({
      title: title.trim(),
      notes,
      status: box,
      priority,
      estimate_min: estimate,
      due_date: due.trim() || null,
      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} />
      <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>
      <View style={{ marginBottom: 2 }}>
        <View style={s.rowWrap}>
          {[
            { label: "Due today", v: isoToday() },
            { label: "Tomorrow", v: isoToday(1) },
          ].map(({ label, v }) => (
            <Pressable
              key={label}
              style={[s.chip, due === v && s.chipActive]}
              onPress={() => {
                haptic.select();
                setDue(due === v ? "" : v);
              }}
            >
              <Text style={[s.chipText, due === v && { color: C.text }]}>{label}</Text>
            </Pressable>
          ))}
        </View>
      </View>
      <Field label="Due date" value={due} onChangeText={setDue} placeholder="YYYY-MM-DD" autoCapitalize="none" />
      <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)}
      />
      <Button title="Add task" onPress={save} />
    </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 },
});
