"use client";

import type { ReactNode } from "react";
import { markdownToPortableText } from "./content-contract";
import type { ContentChannel } from "./types";

export function MarkdownInput({
  label,
  name,
  value,
  onChange,
  required = false,
  placeholder,
  rows = 10,
}: {
  label: string;
  name: string;
  value: string;
  onChange: (value: string) => void;
  required?: boolean;
  placeholder?: string;
  rows?: number;
}) {
  return (
    <div className="min-w-0">
      <label className="field-label" htmlFor={name}>
        {label}{required && <span className="text-destructive"> *</span>}
      </label>
      <textarea
        id={name}
        name={name}
        value={value}
        onChange={(event) => onChange(event.target.value)}
        required={required}
        rows={rows}
        placeholder={placeholder}
        className="w-full resize-y rounded-lg border border-input bg-card px-4 py-3 text-sm leading-6 outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
      />
      <p className="mt-1 text-xs text-muted-foreground">Markdown formatting: headings, bold, italic, code, and quotes.</p>
    </div>
  );
}

export function ChannelPicker({
  channels,
  selectedIds,
  onChange,
}: {
  channels: ContentChannel[];
  selectedIds: string[];
  onChange: (ids: string[]) => void;
}) {
  function toggle(id: string) {
    onChange(selectedIds.includes(id) ? selectedIds.filter((value) => value !== id) : [...selectedIds, id]);
  }

  return (
    <fieldset className="min-w-0">
      <legend className="field-label">Channels <span className="font-normal text-muted-foreground">(optional)</span></legend>
      {channels.length ? (
        <div className="max-h-40 space-y-1 overflow-y-auto rounded-lg border bg-card p-2">
          {channels.map((channel) => (
            <label key={channel.id} className="flex min-h-10 cursor-pointer items-center gap-3 rounded-md px-3 hover:bg-muted">
              <input
                type="checkbox"
                checked={selectedIds.includes(channel.id)}
                onChange={() => toggle(channel.id)}
                className="size-4 accent-primary"
              />
              <span className="text-sm">{channel.name || "Unnamed channel"}</span>
            </label>
          ))}
        </div>
      ) : (
        <p className="rounded-lg border bg-muted/30 px-3 py-3 text-sm text-muted-foreground">No channels are configured for this organization.</p>
      )}
    </fieldset>
  );
}

export function MarkdownPreview({ value }: { value: string }) {
  const blocks = markdownToPortableText(value);
  if (blocks.length === 0) return <p className="text-sm text-muted-foreground">No content yet.</p>;

  function renderInline(block: (typeof blocks)[number]) {
    return block.children.map((span) => {
      let node: ReactNode = span.text;
      for (const mark of span.marks ?? []) {
        if (mark === "strong") node = <strong>{node}</strong>;
        if (mark === "em") node = <em>{node}</em>;
        if (mark === "code") node = <code className="rounded bg-muted px-1 py-0.5">{node}</code>;
      }
      return <span key={span._key} className="whitespace-pre-wrap">{node}</span>;
    });
  }

  return (
    <div className="space-y-4 break-words">
      {blocks.map((block) => {
        const children = renderInline(block);
        if (block.style === "h1") return <h1 key={block._key} className="text-2xl font-semibold">{children}</h1>;
        if (block.style === "h2") return <h2 key={block._key} className="text-xl font-semibold">{children}</h2>;
        if (block.style === "h3") return <h3 key={block._key} className="text-lg font-semibold">{children}</h3>;
        if (block.style === "blockquote") return <blockquote key={block._key} className="border-l-2 pl-4 text-muted-foreground">{children}</blockquote>;
        return <p key={block._key} className="leading-7">{children}</p>;
      })}
    </div>
  );
}
