import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import { ToolShell } from "@/components/ToolShell";
import { Input } from "@/components/ui/input";

export const Route = createFileRoute("/tools/color-converter")({
  head: () => ({
    meta: [
      { title: "Color Converter — Toolkit" },
      {
        name: "description",
        content: "Convert between HEX, RGB and HSL with a live color preview.",
      },
      { property: "og:title", content: "Color Converter — Toolkit" },
      {
        property: "og:description",
        content: "Live HEX ↔ RGB ↔ HSL color conversion.",
      },
    ],
  }),
  component: ColorConverter,
});

function hexToRgb(hex: string) {
  const m = hex.replace("#", "").match(/^([\da-f]{6})$/i);
  if (!m) return null;
  const n = parseInt(m[1], 16);
  return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 };
}

function rgbToHsl(r: number, g: number, b: number) {
  r /= 255;
  g /= 255;
  b /= 255;
  const max = Math.max(r, g, b),
    min = Math.min(r, g, b);
  let h = 0,
    s = 0;
  const l = (max + min) / 2;
  if (max !== min) {
    const d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch (max) {
      case r:
        h = (g - b) / d + (g < b ? 6 : 0);
        break;
      case g:
        h = (b - r) / d + 2;
        break;
      case b:
        h = (r - g) / d + 4;
        break;
    }
    h /= 6;
  }
  return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100) };
}

function ColorConverter() {
  const [hex, setHex] = useState("#5b6cff");
  const rgb = useMemo(() => hexToRgb(hex), [hex]);
  const hsl = useMemo(() => (rgb ? rgbToHsl(rgb.r, rgb.g, rgb.b) : null), [rgb]);

  return (
    <ToolShell
      title="Color Converter"
      description="Pick a color or paste a HEX value to see its RGB and HSL equivalents."
    >
      <div className="grid gap-6 md:grid-cols-[1fr_1.2fr]">
        <div
          className="flex aspect-square items-end rounded-2xl border border-border/80 p-5 shadow-[var(--shadow-elegant)] transition-colors"
          style={{ backgroundColor: rgb ? hex : "transparent" }}
        >
          <span className="rounded-md bg-background/80 px-2.5 py-1 font-mono text-sm backdrop-blur">
            {hex.toUpperCase()}
          </span>
        </div>

        <div className="space-y-5">
          <div>
            <label className="mb-2 block text-sm font-medium">Color picker</label>
            <input
              type="color"
              value={hex}
              onChange={(e) => setHex(e.target.value)}
              className="h-12 w-full cursor-pointer rounded-xl border border-border/80 bg-card"
            />
          </div>
          <Field label="HEX">
            <Input
              value={hex}
              onChange={(e) => setHex(e.target.value)}
              className="font-mono"
            />
          </Field>
          <Field label="RGB">
            <Input
              readOnly
              value={rgb ? `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})` : "Invalid HEX"}
              className="bg-muted/40 font-mono"
            />
          </Field>
          <Field label="HSL">
            <Input
              readOnly
              value={hsl ? `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)` : "Invalid HEX"}
              className="bg-muted/40 font-mono"
            />
          </Field>
        </div>
      </div>
    </ToolShell>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="mb-2 block text-sm font-medium">{label}</label>
      {children}
    </div>
  );
}
