"use client";

import { useState } from "react";
import { Button, Card } from "@/components/ui";
import { Field, inputClass } from "@/components/ui/form";
import { SaveBar, useSection } from "./section-kit";

/** ShowOff "Site robots.txt": view and edit the whole file. */
export function RobotsForm({ siteId, robotsFile, generated, indexing }: { siteId: string; robotsFile: string; generated: string; indexing: boolean }) {
  const { pending, msg, errors, save } = useSection(siteId);
  const [text, setText] = useState(robotsFile || generated);
  const custom = text.trim() !== "" && text.trim() !== generated.trim();
  return (
    <Card className="space-y-4 p-4">
      <div>
        <h2 className="text-sm font-semibold">Site robots.txt file</h2>
        <p className="text-xs text-muted-foreground">This tells search engine crawlers which URLs they can or cannot access on the site. Keep each rule on its own line and use valid syntax.</p>
      </div>
      {!indexing ? <p role="note" className="rounded-md border border-border bg-muted px-3 py-2 text-sm">This website is set to <strong>noindex</strong> (SEO tab), so robots.txt currently disallows all crawling whatever is written here.</p> : null}
      <Field id="robots-file" label="robots.txt" error={errors["robotsFile"]}>
        <textarea id="robots-file" rows={14} spellCheck={false} className={`${inputClass} font-mono`} maxLength={5000} value={text} onChange={(e) => setText(e.target.value)} />
      </Field>
      <div className="flex flex-wrap items-center gap-3">
        <SaveBar pending={pending} msg={msg} onSave={() => save("robots", { robotsFile: custom ? text : "" })} />
        <Button variant="secondary" onClick={() => setText(generated)} disabled={pending || !custom}>Reset to default</Button>
      </div>
    </Card>
  );
}
