// (c) 2026 TWWIM UG. All rights reserved. (www.twwim.com)

import { useState } from 'react';
import { Modal } from '@/components/shared';
import { useTranslation } from '@/i18n/TranslationProvider';
import { useUpdateChunk } from '../hooks/useUpdateChunk';
import type { PlaygroundSource } from '@archer/api-interface';

interface ChunkEditModalProps {
  tenantId: string;
  source: PlaygroundSource;
  onClose: () => void;
  onSaved: () => void;
}

/**
 * Modal for surgical edit of a single Qdrant chunk. Identity (pointId) is
 * preserved by the backend; only the chunk text (and optionally entry
 * title) changes.
 */
export function ChunkEditModal({ tenantId, source, onClose, onSaved }: ChunkEditModalProps) {
  const { t } = useTranslation();
  const [content, setContent] = useState<string>(source.content);
  const mutation = useUpdateChunk(tenantId);

  const isDocChunk = !!source.parentId;
  const identifier = isDocChunk
    ? `${t('knowledge.playground.docChunkLabel')}: ${source.filename || '—'}${source.chunkIndex !== null ? ` · #${source.chunkIndex + 1}` : ''}`
    : `${t('knowledge.playground.entryLabel')}: ${source.title || '—'}`;

  const disabled = mutation.isPending || content.trim().length === 0;

  const handleSave = () => {
    mutation.mutate(
      { pointId: source.pointId, body: { content } },
      {
        onSuccess: () => {
          onSaved();
          onClose();
        },
      },
    );
  };

  return (
    <Modal
      title={t('knowledge.playground.editChunkTitle')}
      subtitle={identifier}
      onClose={onClose}
      maxWidth="max-w-2xl"
      footer={
        <div className="flex justify-end gap-2">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
          >
            {t('knowledge.playground.editChunkCancel')}
          </button>
          <button
            onClick={handleSave}
            disabled={disabled}
            className="px-4 py-2 text-sm font-medium text-white bg-cyan-600 rounded-lg hover:bg-cyan-700 disabled:bg-cyan-300 disabled:cursor-not-allowed transition-colors"
          >
            {mutation.isPending
              ? t('knowledge.playground.thinking')
              : t('knowledge.playground.editChunkSave')}
          </button>
        </div>
      }
    >
      <div className="space-y-3">
        <textarea
          value={content}
          onChange={(e) => setContent(e.target.value)}
          className="w-full min-h-[260px] px-3 py-2 text-sm font-mono text-gray-900 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
          maxLength={16000}
        />
        <p className="text-xs text-gray-500">{t('knowledge.playground.editChunkHint')}</p>
        {mutation.error && (
          <p className="text-sm text-red-700 bg-red-50 border border-red-200 rounded-lg p-2">
            {mutation.error.message}
          </p>
        )}
      </div>
    </Modal>
  );
}
