"use client";

import { useEffect, useRef, useState, type DragEvent } from "react";
import { errorMessage } from "@/app/(admin)/_lib/api";
import { emptyItem, resolveMedia, type Field } from "@/app/(admin)/_lib/cms";
import { ACCEPT, fileProblem, mediaUrl, uploadMedia, type Media } from "@/app/(admin)/_lib/media";
import { isLink, isMediaUrl } from "@/app/(admin)/_lib/validation";
import { Icon } from "./Icon";
import { MediaPicker } from "./MediaLibrary";

type Errors = Record<string, string>;
type Props = { field: Field; value: unknown; onChange: (v: unknown) => void; errors: Errors; path: string; disabled?: boolean };

const str = (v: unknown) => (typeof v === "string" ? v : "");
const obj = (v: unknown) => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
const join = (a: string, b: string | number) => (a ? `${a}.${b}` : String(b));
const fid = (path: string) => `f-${path.replace(/\./g, "-")}`;

/** Server error for this exact path, or for anything nested under it. */
function errAt(errors: Errors, path: string) {
  return errors[path];
}

function FieldError({ msg }: { msg?: string | null }) {
  return msg ? <div className="hint bad">{msg}</div> : null;
}

function Counter({ value, max }: { value: string; max: number }) {
  if (value.length < max * 0.8) return null;
  return <span className={`counter${value.length > max ? " bad" : ""}`}>{`${value.length}/${max}`}</span>;
}

/* ------------------------------------------------------------------ */
/* Image with drag-and-drop                                            */
/* ------------------------------------------------------------------ */

function MediaInput({
  label,
  value,
  onChange,
  errors,
  path,
  disabled,
  required,
  accept = "image",
  withAlt = true,
}: {
  label: string;
  value: Record<string, unknown>;
  onChange: (v: Record<string, unknown>) => void;
  errors: Errors;
  path: string;
  disabled?: boolean;
  required?: boolean;
  accept?: "image" | "video";
  withAlt?: boolean;
}) {
  const url = str(value.url);
  const src = resolveMedia(url);
  const [broken, setBroken] = useState<string | null>(null);
  const [over, setOver] = useState(false);
  const [busy, setBusy] = useState(false);
  const [localPreview, setLocalPreview] = useState<string | null>(null);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const fileRef = useRef<HTMLInputElement>(null);
  const isVideo = accept === "video";
  const [picking, setPicking] = useState(false);
  const altFrom = (m: Pick<Media, "title" | "originalName">) => str(value.alt) || m.title || m.originalName.replace(/\.[^.]+$/, "").replace(/[-_]+/g, " ");
  const pick = (m: Media) => {
    onChange({ ...value, url: mediaUrl(m), ...(withAlt ? { alt: altFrom(m).slice(0, 200) } : {}) });
    setPicking(false);
  };

  useEffect(() => () => {
    if (localPreview) URL.revokeObjectURL(localPreview);
  }, [localPreview]);

  const handleFile = async (file: File | undefined) => {
    if (!file || disabled) return;
    setUploadError(null);
    const problem = fileProblem(file, accept);
    if (problem) return setUploadError(problem);
    setLocalPreview(URL.createObjectURL(file));
    setBusy(true);
    try {
      const m = await uploadMedia(file, file.name.replace(/\.[^.]+$/, "").replace(/[-_]+/g, " "));
      onChange({ ...value, url: mediaUrl(m), ...(withAlt ? { alt: altFrom(m).slice(0, 200) } : {}) });
      setLocalPreview(null);
    } catch (e) {
      setUploadError(errorMessage(e));
    } finally {
      setBusy(false);
    }
  };

  const hasFiles = (e: DragEvent) => Array.from(e.dataTransfer.types).includes("Files");

  const showSrc = localPreview ?? (src && broken !== src ? src : null);
  const urlId = fid(join(path, "url"));
  const urlProblem = url && !isMediaUrl(url) ? "Use an https:// URL or a /path." : null;

  return (
    <div className="field">
      <label htmlFor={urlId}>
        {label}
        {required && <span className="req"> *</span>}
      </label>
      <div
        className={`dropzone${over ? " over" : ""}${disabled ? " off" : ""}`}
        onDragOver={(e) => {
          if (disabled || !hasFiles(e)) return;
          e.preventDefault();
          e.dataTransfer.dropEffect = "copy";
          setOver(true);
        }}
        onDragLeave={() => setOver(false)}
        onDrop={(e) => {
          if (disabled || !hasFiles(e)) return;
          e.preventDefault();
          setOver(false);
          handleFile(e.dataTransfer.files[0]);
        }}
      >
        <div className="dz-thumb">
          {showSrc && !isVideo ? (
            // eslint-disable-next-line @next/next/no-img-element -- arbitrary external CMS media
            <img src={showSrc} alt="" onError={() => setBroken(src)} />
          ) : (
            <Icon name={isVideo ? "file" : "upload"} size={18} />
          )}
          {busy && (
            <span className="dz-busy">
              <span className="spin dark" />
            </span>
          )}
        </div>
        <div className="dz-main">
          <input
            id={urlId}
            className="input input-sm"
            placeholder={isVideo ? "https://… or /videos/hero.mp4" : "https://… or /images/…"}
            value={url}
            disabled={disabled}
            onChange={(e) => onChange({ ...value, url: e.target.value })}
            aria-invalid={!!(errAt(errors, join(path, "url")) || urlProblem)}
          />
          <div className="dz-hint">
            {disabled ? (
              "Inherited from Global"
            ) : (
              <>
                Drop {isVideo ? "a video" : "an image"} here or{" "}
                <button type="button" className="link" onClick={() => fileRef.current?.click()}>
                  browse
                </button>{" "}
                or{" "}
                <button type="button" className="link" onClick={() => setPicking(true)}>
                  choose from library
                </button>
              </>
            )}
          </div>
          <input
            ref={fileRef}
            type="file"
            accept={ACCEPT[accept]}
            hidden
            onChange={(e) => {
              handleFile(e.target.files?.[0] ?? undefined);
              e.target.value = "";
            }}
          />
        </div>
      </div>
      {url && !src && !localPreview && <div className="hint">Website asset: shown in the preview once NEXT_PUBLIC_SITE_URL is set.</div>}
      {picking && <MediaPicker kind={accept} onPick={pick} onClose={() => setPicking(false)} />}
      <FieldError msg={uploadError ?? urlProblem ?? errAt(errors, join(path, "url")) ?? errAt(errors, path)} />
      {withAlt && (
        <input
          className="input input-sm alt-input"
          aria-label={`${label} alt text`}
          placeholder="Alt text (describe the image for screen readers)"
          maxLength={200}
          value={str(value.alt)}
          disabled={disabled}
          onChange={(e) => onChange({ ...value, alt: e.target.value })}
        />
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Field kinds                                                         */
/* ------------------------------------------------------------------ */

function CtaFields({ value, onChange, errors, path, disabled, label }: { value: unknown; onChange: (v: unknown) => void; errors: Errors; path: string; disabled?: boolean; label?: string }) {
  const v = obj(value);
  const href = str(v.href);
  const hrefProblem = href && !isLink(href) ? "Use https://, /path, #anchor, mailto: or tel:." : null;
  return (
    <div className="cta-row">
      {label && <div className="cta-label">{label}</div>}
      <input
        className="input input-sm"
        aria-label={`${label ?? "Button"} label`}
        placeholder="Button label"
        maxLength={60}
        value={str(v.label)}
        disabled={disabled}
        onChange={(e) => onChange({ ...v, label: e.target.value })}
        aria-invalid={!!errAt(errors, join(path, "label"))}
      />
      <input
        className="input input-sm"
        aria-label={`${label ?? "Button"} link`}
        placeholder="/path or https://…"
        value={href}
        disabled={disabled}
        onChange={(e) => onChange({ ...v, href: e.target.value })}
        aria-invalid={!!(errAt(errors, join(path, "href")) || hrefProblem)}
      />
      <label className="check small" title="Open in a new tab">
        <input type="checkbox" checked={v.openInNewTab === true} disabled={disabled} onChange={(e) => onChange({ ...v, openInNewTab: e.target.checked || undefined })} />
        <span>New tab</span>
      </label>
      <FieldError msg={hrefProblem ?? errAt(errors, join(path, "label")) ?? errAt(errors, join(path, "href")) ?? errAt(errors, path)} />
    </div>
  );
}

export function SchemaField({ field, value, onChange, errors, path, disabled }: Props) {
  const id = fid(path);

  switch (field.kind) {
    case "text": {
      const v = str(value);
      const common = {
        id,
        className: "input",
        maxLength: field.max,
        value: v,
        disabled,
        placeholder: field.placeholder,
        "aria-invalid": !!errAt(errors, path),
      };
      return (
        <div className="field">
          <label htmlFor={id}>
            {field.label}
            {field.required && <span className="req"> *</span>}
            <Counter value={v} max={field.max} />
          </label>
          {field.multiline ? (
            <textarea {...common} rows={field.max > 1000 ? 6 : 3} onChange={(e) => onChange(e.target.value)} />
          ) : (
            <input {...common} type={field.inputType ?? "text"} onChange={(e) => onChange(e.target.value)} />
          )}
          {field.hint && <div className="hint">{field.hint}</div>}
          <FieldError msg={errAt(errors, path)} />
        </div>
      );
    }

    case "number": {
      const v = typeof value === "number" ? String(value) : "";
      return (
        <div className="field">
          <label htmlFor={id}>
            {field.label}
            {field.required && <span className="req"> *</span>}
          </label>
          <input
            id={id}
            className="input input-sm"
            type="number"
            inputMode={field.integer ? "numeric" : "decimal"}
            min={field.min}
            max={field.max}
            step={field.integer ? 1 : "any"}
            placeholder={field.placeholder}
            value={v}
            disabled={disabled}
            onChange={(e) => onChange(e.target.value === "" ? undefined : Number(e.target.value))}
            aria-invalid={!!errAt(errors, path)}
            style={{ maxWidth: 200 }}
          />
          <FieldError msg={errAt(errors, path)} />
        </div>
      );
    }

    case "boolean":
      return (
        <div className="field">
          <label className="check">
            <input type="checkbox" checked={value === true} disabled={disabled} onChange={(e) => onChange(e.target.checked || undefined)} />
            <span>{field.label}</span>
          </label>
          <FieldError msg={errAt(errors, path)} />
        </div>
      );

    case "group": {
      const v = obj(value);
      return (
        <div className="field">
          <div className="fs-title">
            {field.label}
            {field.required && <span className="req"> *</span>}
          </div>
          <FieldError msg={errAt(errors, path)} />
          <div className="repeat">
            {field.fields.map((sub) => (
              <SchemaField key={sub.key} field={sub} value={v[sub.key]} onChange={(x) => onChange({ ...v, [sub.key]: x })} errors={errors} path={join(path, sub.key)} disabled={disabled} />
            ))}
          </div>
        </div>
      );
    }

    case "link": {
      const v = str(value);
      const problem = v && !isLink(v) ? "Use https://, /path, #anchor, mailto: or tel:." : null;
      return (
        <div className="field">
          <label htmlFor={id}>{field.label}</label>
          <input id={id} className="input" placeholder="https://… or /path" value={v} disabled={disabled} onChange={(e) => onChange(e.target.value)} aria-invalid={!!(problem || errAt(errors, path))} />
          <FieldError msg={problem ?? errAt(errors, path)} />
        </div>
      );
    }

    case "select":
      return (
        <div className="field">
          <label htmlFor={id}>{field.label}</label>
          <select id={id} className="select input" value={str(value) || field.options[0].value} disabled={disabled} onChange={(e) => onChange(e.target.value)}>
            {field.options.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
          <FieldError msg={errAt(errors, path)} />
        </div>
      );

    case "richTitle": {
      const v = obj(value);
      const text = str(v.text);
      const hl = str(v.highlight);
      const hlProblem = hl.trim() && !text.includes(hl.trim()) ? "The highlight must appear in the title exactly as written." : null;
      return (
        <div className="field-group">
          <div className="field">
            <label htmlFor={id}>
              {field.label}
              {field.required && <span className="req"> *</span>}
              <Counter value={text} max={200} />
            </label>
            <textarea id={id} className="input" rows={2} maxLength={200} value={text} disabled={disabled} onChange={(e) => onChange({ ...v, text: e.target.value })} aria-invalid={!!errAt(errors, join(path, "text"))} />
            <FieldError msg={errAt(errors, join(path, "text")) ?? errAt(errors, path)} />
          </div>
          <div className="field">
            <label htmlFor={`${id}-hl`}>Highlighted words</label>
            <input id={`${id}-hl`} className="input input-sm" maxLength={200} placeholder="Optional: part of the title shown in blue" value={hl} disabled={disabled} onChange={(e) => onChange({ ...v, highlight: e.target.value })} />
            <FieldError msg={hlProblem ?? errAt(errors, join(path, "highlight"))} />
          </div>
        </div>
      );
    }

    case "image":
      return <MediaInput label={field.label} required={field.required} value={obj(value)} onChange={onChange} errors={errors} path={path} disabled={disabled} />;

    case "background": {
      const v = obj(value);
      const type = str(v.type) || "image";
      return (
        <div className="field-group">
          <div className="field">
            <label htmlFor={`${id}-type`}>{field.label} type</label>
            <select id={`${id}-type`} className="select input" value={type} disabled={disabled} onChange={(e) => onChange({ ...v, type: e.target.value })}>
              <option value="image">Image</option>
              <option value="video">Video</option>
            </select>
          </div>
          <MediaInput label={type === "video" ? "Video" : "Image"} required value={{ ...v, type }} onChange={onChange} errors={errors} path={path} disabled={disabled} accept={type === "video" ? "video" : "image"} withAlt={type === "image"} />
          {type === "video" && (
            <MediaInput
              label="Poster image (shown while the video loads)"
              value={{ url: v.posterUrl, alt: v.alt }}
              onChange={(p) => onChange({ ...v, type, posterUrl: p.url, alt: p.alt })}
              errors={errors}
              path={join(path, "posterUrl")}
              disabled={disabled}
            />
          )}
        </div>
      );
    }

    case "cta":
      return (
        <div className="field">
          <div className="lbl">
            {field.label}
            {field.required && <span className="req"> *</span>}
          </div>
          <CtaFields value={value} onChange={onChange} errors={errors} path={path} disabled={disabled} />
        </div>
      );

    case "list": {
      const list = Array.isArray(value) ? value : [];
      const canAdd = list.length < field.max && !disabled;
      const canRemove = list.length > field.min && !disabled;
      const setItem = (i: number, v: unknown) => onChange(list.map((x, j) => (j === i ? v : x)));
      const move = (i: number, d: -1 | 1) => {
        const j = i + d;
        if (j < 0 || j >= list.length) return;
        const next = [...list];
        [next[i], next[j]] = [next[j], next[i]];
        onChange(next);
      };
      return (
        <div className="field">
          <div className="fs-title">
            {field.label} ({list.length}
            {field.max < 50 ? ` of max ${field.max}` : ""})
          </div>
          <FieldError msg={errAt(errors, path)} />
          {list.map((item, i) => {
            const ip = join(path, i);
            const head = (
              <div className="repeat-h">
                <b>
                  {field.itemLabel} {i + 1}
                </b>
                {!disabled && (
                  <span className="repeat-tools">
                    <button type="button" title="Move up" aria-label={`Move ${field.itemLabel} ${i + 1} up`} disabled={i === 0} onClick={() => move(i, -1)}>
                      ↑
                    </button>
                    <button type="button" title="Move down" aria-label={`Move ${field.itemLabel} ${i + 1} down`} disabled={i === list.length - 1} onClick={() => move(i, 1)}>
                      ↓
                    </button>
                    <button type="button" title="Remove" aria-label={`Remove ${field.itemLabel} ${i + 1}`} disabled={!canRemove} onClick={() => onChange(list.filter((_, j) => j !== i))}>
                      <Icon name="x" size={14} />
                    </button>
                  </span>
                )}
              </div>
            );
            if (field.item === "cta")
              return (
                <div className="repeat" key={i}>
                  {head}
                  <CtaFields value={item} onChange={(v) => setItem(i, v)} errors={errors} path={ip} disabled={disabled} />
                </div>
              );
            if (!Array.isArray(field.item)) {
              const max = field.item.string;
              return (
                <div className="repeat" key={i}>
                  {head}
                  <input className="input input-sm" aria-label={`${field.itemLabel} ${i + 1}`} maxLength={max} value={str(item)} disabled={disabled} onChange={(e) => setItem(i, e.target.value)} />
                  <FieldError msg={errAt(errors, ip)} />
                </div>
              );
            }
            const io = obj(item);
            return (
              <div className="repeat" key={i}>
                {head}
                {field.item.map((sub) => (
                  <SchemaField key={sub.key} field={sub} value={io[sub.key]} onChange={(v) => setItem(i, { ...io, [sub.key]: v })} errors={errors} path={join(ip, sub.key)} disabled={disabled} />
                ))}
              </div>
            );
          })}
          {canAdd && (
            <button type="button" className="btn-plain" style={{ color: "var(--blue)" }} onClick={() => onChange([...list, emptyItem(field.item)])}>
              <Icon name="plus" size={15} />
              Add {field.itemLabel.toLowerCase()}
            </button>
          )}
        </div>
      );
    }
  }
}
