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

import { useState } from 'react';
import { Pencil, FileText, BookOpen } from 'lucide-react';
import { useTranslation } from '@/i18n/TranslationProvider';
import { ChunkEditModal } from './ChunkEditModal';
import type { PlaygroundSource } from '@archer/api-interface';

interface PlaygroundSourceRowProps {
  tenantId: string;
  source: PlaygroundSource;
  rank: number;
  onChange: () => void;
}

const TYPE_COLORS: Record<string, { bg: string; text: string }> = {
  PRODUCT: { bg: 'bg-blue-100', text: 'text-blue-800' },
  PAGE: { bg: 'bg-green-100', text: 'text-green-800' },
  DOCUMENT: { bg: 'bg-purple-100', text: 'text-purple-800' },
  FAQ: { bg: 'bg-amber-100', text: 'text-amber-800' },
  CUSTOM: { bg: 'bg-gray-100', text: 'text-gray-800' },
  content: { bg: 'bg-cyan-100', text: 'text-cyan-800' },
};

const SOURCE_COLORS: Record<string, { bg: string; text: string }> = {
  WORDPRESS: { bg: 'bg-indigo-100', text: 'text-indigo-800' },
  SHOPIFY: { bg: 'bg-green-100', text: 'text-green-800' },
  MANUAL: { bg: 'bg-gray-100', text: 'text-gray-700' },
  UPLOAD: { bg: 'bg-cyan-100', text: 'text-cyan-800' },
  SCOUT: { bg: 'bg-orange-100', text: 'text-orange-800' },
};

function Badge({ label, colors }: { label: string; colors: { bg: string; text: string } }) {
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${colors.bg} ${colors.text}`}>
      {label}
    </span>
  );
}

export function PlaygroundSourceRow({ tenantId, source, rank, onChange }: PlaygroundSourceRowProps) {
  const { t } = useTranslation();
  const [isEditing, setIsEditing] = useState(false);

  const isDocChunk = !!source.parentId;
  const headline = isDocChunk
    ? source.filename || t('knowledge.playground.docChunkLabel')
    : source.title || t('knowledge.playground.entryLabel');
  const scorePct = Math.round(source.score * 100);
  const typeColors = TYPE_COLORS[source.type] ?? TYPE_COLORS.CUSTOM;
  const sourceColors = SOURCE_COLORS[source.source] ?? SOURCE_COLORS.MANUAL;

  return (
    <>
      <div className="bg-white border border-gray-200 rounded-lg p-3 shadow-sm">
        <div className="flex items-start gap-3">
          <div className="flex items-center gap-2 shrink-0">
            <span className="text-xs font-mono text-gray-400">[{rank}]</span>
            {isDocChunk ? (
              <FileText size={16} className="text-purple-600" />
            ) : (
              <BookOpen size={16} className="text-cyan-600" />
            )}
          </div>
          <div className="min-w-0 flex-1">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="font-medium text-gray-900 truncate">{headline}</span>
              {isDocChunk && source.chunkIndex !== null && (
                <span className="text-xs text-gray-500">#{source.chunkIndex + 1}</span>
              )}
              {source.type && <Badge label={source.type} colors={typeColors} />}
              {source.source && <Badge label={source.source} colors={sourceColors} />}
              <span className="text-xs text-gray-500">
                {t('knowledge.playground.scoreLabel')}: {scorePct}%
              </span>
            </div>
            <p className="mt-2 text-sm text-gray-700 line-clamp-3 whitespace-pre-wrap">
              {source.snippet}
            </p>
          </div>
          <button
            onClick={() => setIsEditing(true)}
            className="p-1.5 text-gray-400 hover:text-cyan-700 hover:bg-cyan-50 rounded-lg transition-colors shrink-0"
            title={t('knowledge.playground.editChunkTitle')}
          >
            <Pencil size={16} />
          </button>
        </div>
      </div>
      {isEditing && (
        <ChunkEditModal
          tenantId={tenantId}
          source={source}
          onClose={() => setIsEditing(false)}
          onSaved={onChange}
        />
      )}
    </>
  );
}
