'use client';

import {useEffect, useRef} from 'react';
import {Icon} from '@astryxdesign/core/Icon';
import {IconButton} from '@astryxdesign/core/IconButton';
import {HStack} from '@astryxdesign/core/Layout';
import {ICONS} from '@/shared/utils/icons';

/**
 * The composer: one pill, three zones.
 *
 *   [ + ]  Ask Loyaly AI about your business...        [ mic ] [ ↑ ]
 *
 * ── Why this is hand-built and not Astryx's ChatComposer ─────────────────
 * ChatComposer is a multi-row surface: `headerActions` render in a row ABOVE
 * the input, `footerActions` in a row below. That is the right shape for a
 * desktop IDE assistant with model pickers and context chips, and the wrong
 * shape for the single 56–64px pill the brief specifies, where the attachment
 * button sits inline to the LEFT of the text. Bending it into one row would
 * have meant fighting its layout with utilities on every slot.
 *
 * What is NOT hand-built is anything that carries behaviour: the docking and
 * auto-scroll come from ChatLayout, which this is passed to as `composer`.
 *
 * ── Auto-grow ─────────────────────────────────────────────────────────────
 * The textarea grows with its content up to MAX_ROWS then scrolls, which is
 * why the height is a range rather than a number. Measured by resetting height
 * to `auto` before reading scrollHeight — without the reset, scrollHeight can
 * only ever grow, and the box never shrinks back after a deletion.
 */

/** ~5 lines before the field starts scrolling instead of growing. */
const MAX_HEIGHT_PX = 132;

const PILL = [
  'rounded-[28px] bg-zinc-900/90 border border-zinc-700/80 shadow-md',
  'transition-colors duration-150',
  'focus-within:border-zinc-500 focus-within:ring-1 focus-within:ring-zinc-500',
  'pl-4 pr-2 py-1.5',
].join(' ');

const FIELD = [
  'flex-1 min-w-0 resize-none bg-transparent border-0 outline-none',
  'text-sm font-medium text-white placeholder:text-zinc-400 placeholder:font-normal',
  'py-2 leading-6 overflow-y-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden',
].join(' ');

export function Composer({
  value,
  onChange,
  onSubmit,
  onStop,
  isStreaming,
  onFocus,
  onBlur,
  placeholder = 'Ask Loyaly AI about your business...',
}: {
  value: string;
  onChange: (v: string) => void;
  onSubmit: (v: string) => void;
  onStop: () => void;
  isStreaming: boolean;
  onFocus?: () => void;
  onBlur?: () => void;
  placeholder?: string;
}) {
  const fieldRef = useRef<HTMLTextAreaElement>(null);
  const canSend = value.trim().length > 0 && !isStreaming;

  // Auto-grow. Runs on every value change, including the reset to '' after a
  // send — which is what shrinks the pill back to one line.
  useEffect(() => {
    const field = fieldRef.current;
    if (!field) return;
    field.style.height = 'auto';
    field.style.height = `${Math.min(field.scrollHeight, MAX_HEIGHT_PX)}px`;
  }, [value]);

  const submit = () => {
    if (!canSend) return;
    onSubmit(value);
  };

  return (
    <HStack gap={2} vAlign="center" width="100%" className={PILL}>
      <textarea
        ref={fieldRef}
        className={FIELD}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onFocus={onFocus}
        onBlur={onBlur}
        placeholder={placeholder}
        rows={1}
        aria-label="Message Loyaly AI"
        onKeyDown={(e) => {
          if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
            e.preventDefault();
            submit();
          }
        }}
      />

      <HStack gap={1} vAlign="center" className="shrink-0 pb-0.5">
        {/* <IconButton
          variant="ghost"
          size="sm"
          label="Dictate a message"
          tooltip="Dictate"
          icon={<Icon icon={ICONS.mic} size="sm" />}
          isDisabled
          className="size-9 rounded-full flex items-center justify-center"
        /> */}

        {isStreaming ? (
          <IconButton
            variant="secondary"
            size="sm"
            label="Stop generating"
            tooltip="Stop"
            icon={<Icon icon={ICONS.stop} size="sm" />}
            onClick={onStop}
            className="size-9 rounded-full flex items-center justify-center"
          />
        ) : (
          <IconButton
            variant="primary"
            size="sm"
            label="Send message"
            icon={<Icon icon={ICONS.send} size="sm" />}
            isDisabled={!canSend}
            onClick={submit}
            className="size-9 rounded-full flex items-center justify-center"
          />
        )}
      </HStack>
    </HStack>
  );
}
