import React from "react";

import { Button } from "@/components/Button";
import { Input } from "@/components/Input";
import { useThemeContext, emptyPalette } from "@/components/Theme";
import { Title } from "@/components/Title";

import styles from "./themer.module.css";

export default function Themer() {
  const context = useThemeContext();
  const palette = context?.theme.palette ?? emptyPalette;

  return (
    <main className={styles.page}>
      <Title>Themer</Title>
      <h1>Themer</h1>
      <form onSubmit={(event) => event.preventDefault()}>
        <div className={styles.controls}>
          <Button
            type="reset"
            onClick={() => {
              context?.clearSaved();
              context?.setTheme("light");
            }}
          >
            Reset to light mode
          </Button>
          <Button type="submit" onClick={() => context?.save()}>
            Save
          </Button>
        </div>
        <div className={styles.palette}>
          {Object.entries(palette).map(([key, value]) => {
            const color =
              value.length === 4 && value.startsWith("#")
                ? `#${value[1].repeat(2)}${value[2].repeat(2)}${value[3].repeat(
                    2
                  )}`
                : value;

            const isValidColor = color.startsWith("#") && color.length === 7;

            return (
              <div key={key}>
                <Input
                  id={`color-${key}`}
                  type="color"
                  className={styles.colorSelector}
                  value={color}
                  onChange={(event) =>
                    context?.setTheme({ [key]: event.target.value })
                  }
                />
                <Button
                  type="button"
                  className={styles.colorReset}
                  size="small"
                  onClick={() => context?.setTheme({ [key]: "" })}
                >
                  Reset
                </Button>
                <code className={styles.colorName}>
                  <label htmlFor={`color-${key}`}>
                    {!isValidColor && "🚧 "}
                    {key
                      .slice(2)
                      .split("-")
                      .map((word) => word[0].toUpperCase() + word.slice(1))
                      .join(" ")}
                    {!isValidColor && " 🚧"}
                  </label>
                </code>
              </div>
            );
          })}
        </div>
      </form>
    </main>
  );
}
