import {
  dateSchema,
  habitInput,
  taskInput,
  type HabitConfig,
} from "../../habits/contracts";
import { demoCalendar, HABIT_COLORS } from "./calendar-model";

export const EDITOR_TODAY = "2026-09-04";
export const EDITOR_START = "2025-10-01";
export const EDITOR_HABITS: {
  id: string;
  color: string;
  config: HabitConfig;
}[] = [
  {
    id: "water",
    color: HABIT_COLORS.water,
    config: {
      name: "Drink water",
      method: "count",
      target: 8,
      unit: "glasses",
      carryPartialProgress: false,
      schedule: { type: "daily" },
      archived: false,
    },
  },
  {
    id: "reading",
    color: HABIT_COLORS.reading,
    config: {
      name: "Read a little",
      method: "manual",
      schedule: { type: "daily" },
      archived: false,
    },
  },
  {
    id: "tasks",
    color: HABIT_COLORS.tasks,
    config: {
      name: "Evening reset",
      method: "tasks",
      schedule: { type: "daily" },
      archived: false,
      tasks: ["Clear desk", "Plan tomorrow", "Stretch"].map((name, index) => ({
        id: `task-${index}`,
        name,
        schedule: { type: "daily" },
      })),
    },
  },
];

export function validateEditor(config: HabitConfig): string | null {
  const { archived: _, ...input } = config;
  const result = habitInput.safeParse(
    config.method === "tasks"
      ? { ...input, tasks: config.tasks.map(({ id: _, ...task }) => task) }
      : input,
  );
  return result.success
    ? null
    : (result.error.issues[0]?.message ?? "Check the habit settings.");
}

export function validateTasks(
  tasks: Extract<HabitConfig, { method: "tasks" }>["tasks"],
): string | null {
  if (tasks.length > 100) return "Use no more than 100 tasks.";
  for (const { id: _, ...task } of tasks) {
    const result = taskInput.safeParse(task);
    if (!result.success)
      return result.error.issues[0]?.message ?? "Check each task.";
  }
  return null;
}

/** Frozen historical requirements deliberately do not read today's edited config. */
export function historicalDays(id: string) {
  const config = EDITOR_HABITS.find((habit) => habit.id === id)!.config;
  return demoCalendar(
    0,
    config.method === "count"
      ? config.target
      : config.method === "tasks"
        ? config.tasks.length
        : 1,
  );
}

export function backfillError(
  id: string,
  date: string,
  value: number,
): string | null {
  if (!dateSchema.safeParse(date).success) return "Choose a valid date.";
  if (date >= EDITOR_TODAY)
    return "Choose a past date. Today is edited in the daily view.";
  if (date < EDITOR_START) return "This habit did not exist on that date.";
  const day = historicalDays(id).find((day) => day.date === date);
  if (!day || day.state !== "due")
    return "Nothing was scheduled on this date. There is no progress to correct.";
  if (!Number.isInteger(value) || value < 0 || value > 1_000_000_000)
    return "Enter a whole number from 0 to 1,000,000,000.";
  if (id !== "water" && value > day.target)
    return "Progress cannot exceed the scheduled items.";
  return null;
}
