"use client";

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>
  );
}
