import { useId } from "react";
import { HABIT_COLORS, progressShade } from "./calendar-model";
import { Field } from "./Field";

export type HabitColors = {
  -readonly [K in keyof typeof HABIT_COLORS]: string;
};

export function previewHabitColors(
  habits: { id: string; color: string }[],
  selectedId: string,
  draftColor: string,
): HabitColors {
  const colors: HabitColors = { ...HABIT_COLORS };
  for (const habit of habits) {
    if (!Object.hasOwn(colors, habit.id)) continue;
    colors[habit.id as keyof HabitColors] =
      habit.id === selectedId && isHabitColor(draftColor)
        ? draftColor
        : habit.color;
  }
  return colors;
}

export const HABIT_PALETTES = [
  { name: "Earth", colors: ["#58765b", "#977344", "#a3604d", "#76734e"] },
  { name: "Coast", colors: ["#426582", "#427b80", "#657e9c", "#667d70"] },
  { name: "Dusk", colors: ["#79618d", "#9c647c", "#736a9c", "#686878"] },
  { name: "Forest", colors: ["#386641", "#52734d", "#6b705c", "#3d6b62"] },
  { name: "Citrus", colors: ["#b45309", "#a16207", "#9a5b35", "#7a801c"] },
  { name: "Blossom", colors: ["#b05276", "#a34e62", "#a65f5a", "#8e5572"] },
  { name: "Jewel", colors: ["#6d28a8", "#1d678d", "#087f73", "#a12e54"] },
  { name: "Slate", colors: ["#475569", "#52616b", "#65605b", "#404047"] },
] as const;

export function isHabitColor(value: string) {
  return /^#[0-9a-f]{6}$/i.test(value);
}

export function HabitColorPicker({
  value,
  onChange,
  mode = "demo",
}: {
  value: string;
  onChange: (color: string) => void;
  mode?: "demo" | "create" | "edit";
}) {
  const id = useId();
  const valid = isHabitColor(value);
  return (
    <fieldset className="ds-color-picker" aria-describedby={`${id}-hint`}>
      <legend>Habit color</legend>
      <p id={`${id}-hint`} className="ds-footnote">
        Choose a suggested shade or enter a custom color for this habit’s calendar.
      </p>
      <div className="ds-color-palettes">
        {HABIT_PALETTES.map((palette) => (
          <div
            key={palette.name}
            className="ds-color-palette"
            role="group"
            aria-label={`${palette.name} palette`}
          >
            <span>{palette.name}</span>
            <div className="ds-color-swatches">
              {palette.colors.map((color) => (
                <button
                  key={color}
                  type="button"
                  aria-label={`${palette.name} ${color}`}
                  aria-pressed={value.toLowerCase() === color}
                  title={color}
                  onClick={() => onChange(color)}
                >
                  <span style={{ backgroundColor: color }}>
                    {value.toLowerCase() === color ? "✓" : ""}
                  </span>
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div className="ds-custom-color">
        <Field label="Custom color" id={`${id}-native`}>
          {(inputId) => (
          <input
            id={inputId}
            type="color"
            value={valid ? value : "#426582"}
            onInput={(event) => onChange(event.currentTarget.value)}
          />
          )}
        </Field>
        <Field label="Hex color" id={`${id}-hex`}>
          {(inputId) => (
          <input
            id={inputId}
            type="text"
            spellCheck={false}
            autoComplete="off"
            maxLength={7}
            pattern="#[0-9a-fA-F]{6}"
            required
            placeholder="#426582"
            value={value}
            aria-invalid={!valid}
            aria-describedby={`${id}-hint${!valid ? ` ${id}-error` : ""}`}
            onChange={(event) => onChange(event.target.value)}
          />
          )}
        </Field>
      </div>
      {valid && (
        <div
          className="ds-color-live-preview"
          aria-label="Live calendar color preview"
        >
          <span className="ds-muted">Calendar preview</span>
          <div
            className="ds-color-preview-shades"
            role="img"
            aria-label={`Progress shades using ${value}`}
          >
            {Array.from({ length: 9 }, (_, count) => (
              <span
                key={count}
                style={{
                  backgroundColor: progressShade(
                    { date: "", value: count, target: 8, state: "due" },
                    value,
                  ),
                }}
              />
            ))}
          </div>
          <span className="ds-muted">0 → complete</span>
        </div>
      )}
      <p className="ds-footnote">
        {mode === "create"
          ? "Saved with your habit."
          : mode === "edit"
            ? "Save to apply this color; Cancel restores the saved color."
            : "Charts preview changes immediately. Save keeps the demo color; Cancel reverts it."}
      </p>
      {!valid && (
        <p id={`${id}-error`} role="alert" className="ds-form-feedback">
          Use a six-digit hex color, such as #426582.
        </p>
      )}
    </fieldset>
  );
}
