"use client";

/**
 * Schema Code Editor — dark-themed JSON-LD editor with validation,
 * format, copy, and reset. Used in Schema Generator + Content Briefs.
 */

import { useState, useCallback, useRef, useEffect } from "react";
import { Check, Copy, AlertTriangle, CheckCircle2, RotateCcw, Wand2 } from "lucide-react";

interface Props {
  value: string;
  onChange: (value: string) => void;
  originalValue?: string;
  showReset?: boolean;
  height?: string;
}

function clientValidate(code: string): { errors: string[]; warnings: string[] } {
  const errors: string[] = [];
  const warnings: string[] = [];
  let obj: Record<string, unknown>;
  try { obj = JSON.parse(code); } catch { return { errors: ["Invalid JSON — check syntax"], warnings: [] }; }
  if (!obj["@context"]) errors.push("Missing @context — should be \"https://schema.org\"");
  else if (obj["@context"] !== "https://schema.org") warnings.push("@context should be \"https://schema.org\"");
  if (!obj["@type"]) errors.push("Missing @type");
  const t = String(obj["@type"] || "");
  if ((t === "LocalBusiness" || t === "MedicalBusiness") && !obj.name) errors.push(`${t} requires "name"`);
  if (t === "FAQPage" && (!Array.isArray(obj.mainEntity) || !obj.mainEntity.length)) errors.push("FAQPage requires \"mainEntity\" array");
  if (t === "HowTo" && (!Array.isArray(obj.step) || !obj.step.length)) errors.push("HowTo requires \"step\" array");
  if (t === "Article" && !obj.headline) warnings.push("Article should have \"headline\"");
  return { errors, warnings };
}

export default function SchemaCodeEditor({ value, onChange, originalValue, showReset = false, height = "h-64" }: Props) {
  const [errors, setErrors] = useState<string[]>([]);
  const [warnings, setWarnings] = useState<string[]>([]);
  const [copied, setCopied] = useState(false);
  const [edited, setEdited] = useState(false);
  const debounceRef = useRef<ReturnType<typeof setTimeout>>();

  const validate = useCallback((code: string) => {
    const { errors: e, warnings: w } = clientValidate(code);
    setErrors(e); setWarnings(w);
  }, []);

  useEffect(() => {
    if (value.trim()) validate(value);
  }, []); // validate initial value

  function handleChange(newVal: string) {
    onChange(newVal);
    setEdited(true);
    clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => validate(newVal), 500);
  }

  function handleFormat() {
    try {
      const parsed = JSON.parse(value);
      const formatted = JSON.stringify(parsed, null, 2);
      onChange(formatted);
      validate(formatted);
    } catch { /* can't format invalid JSON */ }
  }

  function handleCopy() {
    navigator.clipboard.writeText(value).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    }).catch(() => {});
  }

  function handleReset() {
    if (originalValue) {
      onChange(originalValue);
      setEdited(false);
      validate(originalValue);
    }
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-2">
        <h4 className="font-semibold text-sm text-slate-800">Schema Markup (JSON-LD)</h4>
        <div className="flex gap-1.5">
          <button onClick={() => validate(value)} className="text-[11px] px-2.5 py-1 rounded-md bg-slate-100 hover:bg-slate-200 text-slate-600 font-medium flex items-center gap-1">
            <CheckCircle2 className="w-3 h-3" /> Validate
          </button>
          <button onClick={handleFormat} className="text-[11px] px-2.5 py-1 rounded-md bg-slate-100 hover:bg-slate-200 text-slate-600 font-medium flex items-center gap-1">
            <Wand2 className="w-3 h-3" /> Format
          </button>
          <button onClick={handleCopy} className="text-[11px] px-2.5 py-1 rounded-md bg-slate-100 hover:bg-slate-200 text-slate-600 font-medium flex items-center gap-1">
            {copied ? <Check className="w-3 h-3 text-green-600" /> : <Copy className="w-3 h-3" />} {copied ? "Copied" : "Copy"}
          </button>
          {showReset && originalValue && (
            <button onClick={handleReset} className="text-[11px] px-2.5 py-1 rounded-md bg-slate-100 hover:bg-slate-200 text-slate-600 font-medium flex items-center gap-1">
              <RotateCcw className="w-3 h-3" /> Reset
            </button>
          )}
        </div>
      </div>

      <textarea
        className={`w-full ${height} font-mono text-[12px] leading-relaxed bg-[#0F172A] text-[#4ADE80] p-4 rounded-lg border border-slate-700 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none resize-y`}
        value={value}
        onChange={(e) => handleChange(e.target.value)}
        spellCheck={false}
      />

      {/* Validation results */}
      {errors.length > 0 && (
        <div className="mt-2 space-y-1">
          {errors.map((err, i) => (
            <p key={i} className="text-xs text-red-500 flex items-center gap-1">
              <AlertTriangle className="w-3 h-3 shrink-0" /> {err}
            </p>
          ))}
        </div>
      )}
      {warnings.length > 0 && (
        <div className="mt-1 space-y-1">
          {warnings.map((w, i) => (
            <p key={i} className="text-xs text-amber-500 flex items-center gap-1">
              <AlertTriangle className="w-3 h-3 shrink-0" /> {w}
            </p>
          ))}
        </div>
      )}
      {errors.length === 0 && value.trim() && (
        <p className="mt-2 text-xs text-green-500 flex items-center gap-1"><CheckCircle2 className="w-3 h-3" /> Schema is valid</p>
      )}
      {edited && (
        <p className="mt-1 text-xs text-amber-500">Schema has been manually edited</p>
      )}
    </div>
  );
}
