import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { ToolShell } from "@/components/ToolShell";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";

export const Route = createFileRoute("/tools/qr-code")({
  head: () => ({
    meta: [
      { title: "QR Code Generator — Create QR Codes Free" },
      { name: "description", content: "Generate a QR code from any text or URL and download it as a PNG. Free, private, runs in your browser." },
      { property: "og:title", content: "QR Code Generator" },
      { property: "og:description", content: "Create QR codes for URLs, Wi-Fi, contacts and more." },
    ],
  }),
  component: QrTool,
});

function QrTool() {
  const [text, setText] = useState("https://lovable.dev");
  const [size, setSize] = useState(280);
  const imgRef = useRef<HTMLImageElement>(null);
  const src = `https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&data=${encodeURIComponent(text || " ")}`;

  useEffect(() => {}, [src]);

  const download = async () => {
    try {
      const res = await fetch(src);
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url; a.download = "qr-code.png"; a.click();
      URL.revokeObjectURL(url);
    } catch {}
  };

  return (
    <ToolShell title="QR Code Generator" description="Turn any text, link, or contact info into a scannable QR code. Choose a size and download as PNG.">
      <div className="grid gap-6 md:grid-cols-[1fr_auto] md:items-start">
        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="t">Text or URL</Label>
            <Input id="t" value={text} onChange={(e) => setText(e.target.value)} placeholder="https://example.com" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="s">Size: {size}px</Label>
            <input id="s" type="range" min={120} max={500} step={20} value={size} onChange={(e) => setSize(Number(e.target.value))} className="w-full" />
          </div>
          <Button onClick={download}>Download PNG</Button>
        </div>
        <div className="flex items-center justify-center rounded-xl border border-border/80 bg-card p-4">
          <img ref={imgRef} src={src} alt="QR code preview" width={size} height={size} className="rounded" />
        </div>
      </div>
    </ToolShell>
  );
}
