import { useState } from "react";
import { CalendarHeatmap } from "./CalendarHeatmap";
import { HabitChart } from "./HabitChart";
import { Button, Checkbox, Counter } from "./primitives";
import { combinedProgress, demoCalendar, HABIT_COLORS, type CalendarDay } from "./calendar-model";

export function CalendarExamples() {
  const [water, setWater] = useState(7);
  const [read, setRead] = useState(true);
  const waterDays = demoCalendar(water, 8);
  const readingDays = demoCalendar(Number(read), 1);
  const combinedDays: CalendarDay[] = waterDays.map((day, index) => {
    const readingDay = readingDays[index]!;
    const total = combinedProgress([day, readingDay].map((entry) => ({
      ...entry,
      due: entry.state === "due",
    })));
    return {
      date: day.date,
      value: total.completed,
      target: total.due,
      state: day.state === "future" ? "future" : total.due === 0 ? "not-due" : "due",
    };
  });

  return (
    <section className="ds-section" aria-labelledby="calendar-examples-title">
      <div className="ds-spec-heading">
        <h3 id="calendar-examples-title">Working calendars</h3>
        <Button variant="text" onClick={() => { setWater(7); setRead(true); }}>Reset examples ↺</Button>
      </div>
      <p className="ds-muted type-small">Demo date · September 4, 2026. Change today’s progress or select a date to inspect its value.</p>
      <div className="ds-habit-chart-grid">
        <HabitChart
          name="Drink water"
          method="Count target"
          value={water}
          target={8}
          unit="glasses"
          color={HABIT_COLORS.water}
        >
          <Counter label="glasses of water" value={water} target={8} onChange={setWater} />
        </HabitChart>
        <HabitChart
          name="Read a little"
          method="Manual checkbox"
          value={Number(read)}
          target={1}
          unit="reading session"
          color={HABIT_COLORS.reading}
        >
          <Checkbox label="Mark reading done" checked={read} onChange={(event) => setRead(event.target.checked)} />
        </HabitChart>
      </div>
      <div className="ds-form-section">
        <div className="ds-spec-heading">
          <h3>Combined completion</h3>
        </div>
        <CalendarHeatmap days={combinedDays} unit="habits complete" label="Combined habit calendar" />
        <p className="ds-footnote">Only fully completed, scheduled habits count. Partial water progress counts once it reaches 8 glasses; days with nothing scheduled have no score.</p>
      </div>
    </section>
  );
}
