import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { ToolShell } from "@/components/ToolShell";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";

export const Route = createFileRoute("/tools/json-formatter")({
  head: () => ({
    meta: [
      { title: "JSON Formatter — Toolkit" },
      {
        name: "description",
        content: "Beautify, minify and validate JSON in your browser. Fast and private.",
      },
      { property: "og:title", content: "JSON Formatter — Toolkit" },
      {
        property: "og:description",
        content: "Beautify, minify and validate JSON instantly.",
      },
    ],
  }),
  component: JsonFormatter,
});

function JsonFormatter() {
  const [input, setInput] = useState('{"hello":"world","items":[1,2,3]}');
  const [output, setOutput] = useState("");
  const [error, setError] = useState<string | null>(null);

  const run = (mode: "pretty" | "minify") => {
    try {
      const parsed = JSON.parse(input);
      setOutput(mode === "pretty" ? JSON.stringify(parsed, null, 2) : JSON.stringify(parsed));
      setError(null);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Invalid JSON");
      setOutput("");
    }
  };

  const copy = () => output && navigator.clipboard.writeText(output);

  return (
    <ToolShell
      title="JSON Formatter"
      description="Paste JSON to beautify, minify or validate it. Everything runs locally."
    >
      <div className="grid gap-4 lg:grid-cols-2">
        <div>
          <label className="mb-2 block text-sm font-medium">Input</label>
          <Textarea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            spellCheck={false}
            className="min-h-[340px] resize-y rounded-xl border-border/80 bg-card font-mono text-sm shadow-[var(--shadow-soft)]"
          />
        </div>
        <div>
          <label className="mb-2 block text-sm font-medium">Output</label>
          <Textarea
            value={output}
            readOnly
            spellCheck={false}
            placeholder="Formatted JSON will appear here…"
            className="min-h-[340px] resize-y rounded-xl border-border/80 bg-muted/40 font-mono text-sm shadow-[var(--shadow-soft)]"
          />
        </div>
      </div>

      {error && (
        <p className="mt-4 rounded-lg border border-destructive/40 bg-destructive/5 px-4 py-2 text-sm text-destructive">
          {error}
        </p>
      )}

      <div className="mt-6 flex flex-wrap gap-2">
        <Button onClick={() => run("pretty")}>Beautify</Button>
        <Button variant="secondary" onClick={() => run("minify")}>
          Minify
        </Button>
        <Button variant="outline" onClick={copy} disabled={!output}>
          Copy output
        </Button>
      </div>
    </ToolShell>
  );
}
