"use client";

import { useMemo, useState } from "react";
import { Copy, RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { getKotschQuickTool } from "@/tools/kotsch-imports";
import { runKotschQuickCalc } from "@/tools/kotsch-quick-calc";
import type { Tool } from "@/tools/registry";

type Values = Record<string, string>;

function htmlToText(html: string): string {
  return html
    .replace(/<\/span>/gi, ": ")
    .replace(/<\/(div|p|li|h\d)>/gi, "\n")
    .replace(/<br\s*\/?>/gi, "\n")
    .replace(/<[^>]+>/g, "")
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/\n{2,}/g, "\n")
    .trim();
}

export function KotschQuickTool({ tool }: { tool: Tool }) {
  const imported = getKotschQuickTool(tool.slug);
  const initialValues = useMemo(
    () => Object.fromEntries((imported?.inputs ?? []).map((input) => [input.id, String(input.value ?? "")])),
    [imported],
  );
  const [values, setValues] = useState<Values>(initialValues);
  const html = useMemo(() => runKotschQuickCalc(tool.slug, values), [tool.slug, values]);
  const copyText = useMemo(() => htmlToText(html), [html]);

  if (!imported) return null;

  return (
    <div className="space-y-6">
      <p className="text-sm leading-6 text-ink-secondary">{imported.intro ?? imported.desc}</p>
      <div className="grid gap-4 sm:grid-cols-2">
        {imported.inputs.map((input) => (
          <label key={input.id} className="grid gap-2 text-sm font-medium text-ink-primary">
            {input.label}
            {input.type === "textarea" ? (
              <textarea
                value={values[input.id] ?? ""}
                onChange={(event) => setValues((current) => ({ ...current, [input.id]: event.target.value }))}
                className="min-h-28 rounded-none border-2 border-ink-primary bg-surface-raised px-3 py-2 text-sm font-normal text-ink-primary outline-none focus:shadow-[3px_3px_0_rgb(var(--brand-500))]"
              />
            ) : input.type === "select" ? (
              <select
                value={values[input.id] ?? ""}
                onChange={(event) => setValues((current) => ({ ...current, [input.id]: event.target.value }))}
                className="h-10 rounded-none border-2 border-ink-primary bg-surface-raised px-3 text-sm font-normal text-ink-primary outline-none focus:shadow-[3px_3px_0_rgb(var(--brand-500))]"
              >
                {(input.options ?? []).map((option) => (
                  <option key={option.value} value={option.value}>{option.label}</option>
                ))}
              </select>
            ) : (
              <Input
                type={input.type ?? "text"}
                step={input.step ?? "any"}
                value={values[input.id] ?? ""}
                onChange={(event) => setValues((current) => ({ ...current, [input.id]: event.target.value }))}
              />
            )}
          </label>
        ))}
      </div>
      <div className="flex flex-wrap gap-2">
        <Button type="button" onClick={() => navigator.clipboard?.writeText(copyText)}>
          <Copy className="mr-2 h-4 w-4" /> Ergebnis kopieren
        </Button>
        <Button type="button" variant="outline" onClick={() => setValues(initialValues)}>
          <RotateCcw className="mr-2 h-4 w-4" /> Zurücksetzen
        </Button>
      </div>
      <div className="kotsch-quick-result" dangerouslySetInnerHTML={{ __html: html }} />
    </div>
  );
}
