import { useEffect, useRef } from "react";
import type { AssistantConversationItem } from "../state/types";
import { JsonView } from "./JsonView";
import { PanelFrame } from "./PanelFrame";

interface AssistantPanelProps {
  sessionId: string;
  conversation: AssistantConversationItem[];
  inputValue: string;
  onInputChange: (value: string) => void;
  periodHint: string;
  onPeriodHintChange: (value: string) => void;
  businessContext: string;
  onBusinessContextChange: (value: string) => void;
  useMock: boolean;
  onUseMockChange: (value: boolean) => void;
  onSend: () => Promise<void> | void;
  onClear: () => void;
  busy: boolean;
  statusText: string;
  errorMessage: string;
}

function roleLabel(role: AssistantConversationItem["role"]): string {
  return role === "assistant" ? "Ассистент" : "Вы";
}

function shortTime(iso: string): string {
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) {
    return iso;
  }
  return date.toLocaleTimeString("ru-RU");
}

export function AssistantPanel({
  sessionId,
  conversation,
  inputValue,
  onInputChange,
  periodHint,
  onPeriodHintChange,
  businessContext,
  onBusinessContextChange,
  useMock,
  onUseMockChange,
  onSend,
  onClear,
  busy,
  statusText,
  errorMessage
}: AssistantPanelProps) {
  const listRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (listRef.current) {
      listRef.current.scrollTop = listRef.current.scrollHeight;
    }
  }, [conversation, statusText]);

  return (
    <PanelFrame
      title="Режим ассистента"
      subtitle="Диалоговый слой поверх normalizer, маршрутизации и factual retrieval."
      actions={<span className="status-chip">{sessionId ? `session: ${sessionId}` : "новая сессия"}</span>}
    >
      <div ref={listRef} className="assistant-chat-list">
        {conversation.length === 0 ? (
          <div className="assistant-empty muted">Диалог пуст. Отправьте первый вопрос, чтобы запустить контур ассистента.</div>
        ) : null}
        {conversation.map((item) => (
          <article key={item.message_id} className={`assistant-msg ${item.role}`}>
            <header className="assistant-msg-head">
              <strong>{roleLabel(item.role)}</strong>
              <span>{shortTime(item.created_at)}</span>
            </header>
            <div className="assistant-msg-body">{item.text}</div>
            {item.role === "assistant" && item.debug ? (
              <details className="assistant-debug">
                <summary>Показать технический разбор</summary>
                <JsonView value={item.debug} />
              </details>
            ) : null}
          </article>
        ))}
      </div>

      <div className="assistant-compose">
        <div className="grid-two">
          <label>
            Подсказка по периоду
            <input value={periodHint} onChange={(event) => onPeriodHintChange(event.target.value)} />
          </label>
          <label>
            Бизнес-контекст
            <input value={businessContext} onChange={(event) => onBusinessContextChange(event.target.value)} />
          </label>
        </div>
        <label className="full-width">
          Сообщение
          <textarea
            value={inputValue}
            onChange={(event) => onInputChange(event.target.value)}
            rows={4}
            placeholder="Введите вопрос к данным компании..."
          />
        </label>
        <div className="button-row">
          <label className="checkbox-row">
            <input type="checkbox" checked={useMock} onChange={(event) => onUseMockChange(event.target.checked)} />
            Mock-режим
          </label>
          <button type="button" onClick={() => onSend()} disabled={busy || !inputValue.trim()}>
            {busy ? "Выполняю..." : "Отправить"}
          </button>
          <button type="button" onClick={() => onClear()} disabled={busy && conversation.length === 0}>
            Сбросить сессию
          </button>
        </div>
        {statusText ? <p className="diff-summary">{statusText}</p> : null}
        {errorMessage ? <p className="error-text">{errorMessage}</p> : null}
      </div>
    </PanelFrame>
  );
}
