import { useId, type CSSProperties, type ReactNode } from "react";
import { ChevronDown, ListChecks } from "lucide-react";
import { CalendarHeatmap } from "./CalendarHeatmap";
import { demoCalendar } from "./calendar-model";

/** Open chart section: intentionally no card surface or enclosing border. */
export function HabitChart({
  name,
  method,
  value,
  target,
  unit,
  color,
  children,
  headingActions,
  editor,
  tasks,
  tasksLabel = "Tasks for today",
  calendar,
  schedule = "Every day",
  due = true,
  id,
  headingLevel = 4,
}: {
  name: string;
  method: string;
  value: number;
  target: number;
  unit: string;
  color: string;
  children?: ReactNode;
  headingActions?: ReactNode;
  editor?: ReactNode;
  tasks?: ReactNode;
  tasksLabel?: string;
  calendar?: ReactNode;
  schedule?: string;
  due?: boolean;
  id?: string;
  headingLevel?: 3 | 4;
}) {
  const headingId = useId();
  const Heading = `h${headingLevel}` as const;
  return (
    <section className="ds-habit-chart" id={id} aria-labelledby={headingId} style={{ "--habit-color": color } as CSSProperties}>
      <header className="ds-habit-chart-heading">
        <div>
          <div className="ds-habit-title-row">
            <Heading id={headingId}>
              <span style={{ backgroundColor: color }} aria-hidden="true" />
              {name}
            </Heading>
            {headingActions}
          </div>
          <p>
            {method} · {schedule}
          </p>
        </div>
        {children}
      </header>
      {editor}
      <p className="ds-habit-chart-progress" aria-live="polite">
        <span>
          {due
            ? `${value} of ${target} ${unit}`
            : "A day off isn’t a missed day."}
        </span>
        <span>
          {!due
            ? "Not scheduled"
            : value >= target
              ? "Complete"
              : "In progress"}
        </span>
      </p>
      {calendar ?? (
        <CalendarHeatmap
          days={demoCalendar(value, target)}
          label={`${name} progress calendar`}
          unit={unit}
          color={color}
          compact
        />
      )}
      {tasks && (
        <details className="ds-task-accordion">
          <summary>
            <ListChecks size={20} aria-hidden="true" />
            <span className="ds-task-accordion-title">{tasksLabel}</span>
            <span className="ds-task-accordion-progress">
              <progress aria-label={`${name} tasks completed`} value={Math.max(0, Math.min(value, target))} max={Math.max(1, target)} />
              <span>{value} / {target}</span>
            </span>
            <ChevronDown className="ds-task-accordion-chevron" size={18} aria-hidden="true" />
          </summary>
          <div className="ds-task-accordion-content">{tasks}</div>
        </details>
      )}
    </section>
  );
}
