// (c) 2025 TWWIM UG. All rights reserved.

import { useState } from 'react';
import { FileText, Trash2, Plus, Search, X, Upload, AlertCircle, Database, ShieldAlert } from 'lucide-react';
import { useKnowledgeEntries, useKnowledgeStats, useCreateKnowledgeEntry, useDeleteKnowledgeEntry } from '../hooks';
import { useTranslation } from '@/i18n/TranslationProvider';
import { tokenStorage } from '@/infrastructure/storage/LocalTokenStorage';
import type { KnowledgeEntry } from '@/infrastructure/http/api/knowledge';

const MAX_CONTENT_BYTES = 2 * 1024 * 1024; // 2 MB

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' },
};

function contentByteSize(text: string): number {
  return new Blob([text]).size;
}

function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
}

function TypeBadge({ type }: { type: string }) {
  const colors = TYPE_COLORS[type] || TYPE_COLORS.CUSTOM;
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${colors.bg} ${colors.text}`}>
      {type}
    </span>
  );
}

function UsageBar({ used, max }: { used: number; max: number }) {
  const pct = max > 0 ? Math.min((used / max) * 100, 100) : 0;
  const color = pct >= 100 ? 'bg-red-500' : pct >= 80 ? 'bg-amber-500' : 'bg-cyan-500';
  return (
    <div className="flex items-center gap-3">
      <div className="flex-1 h-2 bg-gray-200 rounded-full overflow-hidden">
        <div className={`h-full ${color} rounded-full transition-all`} style={{ width: `${pct}%` }} />
      </div>
      <span className={`text-sm font-medium tabular-nums ${pct >= 100 ? 'text-red-600' : 'text-gray-700'}`}>
        {used}/{max}
      </span>
    </div>
  );
}

function AddEntryForm({
  tenantId,
  onClose,
}: {
  tenantId: string;
  onClose: () => void;
}) {
  const { t } = useTranslation();
  const createMutation = useCreateKnowledgeEntry(tenantId);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [type, setType] = useState<'FAQ' | 'PRODUCT' | 'PAGE' | 'DOCUMENT' | 'CUSTOM'>('FAQ');
  const [url, setUrl] = useState('');
  const [category, setCategory] = useState('');

  const contentBytes = contentByteSize(content);
  const oversized = contentBytes > MAX_CONTENT_BYTES;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim() || !content.trim() || oversized) return;

    createMutation.mutate(
      {
        type,
        title: title.trim(),
        content: content.trim(),
        ...(url.trim() ? { url: url.trim() } : {}),
        ...(category.trim() ? { category: category.trim() } : {}),
      },
      {
        onSuccess: () => {
          onClose();
        },
      },
    );
  };

  return (
    <div className="bg-white border border-gray-200 rounded-lg p-6 mb-6">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-gray-900">{t('knowledge.addEntry')}</h3>
        <button onClick={onClose} className="p-1 text-gray-400 hover:text-gray-600">
          <X size={20} />
        </button>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">{t('knowledge.type')}</label>
            <select
              value={type}
              onChange={(e) => setType(e.target.value as typeof type)}
              className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:outline-none"
            >
              <option value="FAQ">FAQ</option>
              <option value="PRODUCT">Product</option>
              <option value="PAGE">Page</option>
              <option value="DOCUMENT">Document</option>
              <option value="CUSTOM">Custom</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">{t('knowledge.category')}</label>
            <input
              type="text"
              value={category}
              onChange={(e) => setCategory(e.target.value)}
              placeholder={t('common.optional')}
              className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:outline-none"
            />
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">{t('knowledge.title')}</label>
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder={t('knowledge.titlePlaceholder')}
            className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:outline-none"
            required
          />
        </div>

        <div>
          <div className="flex items-center justify-between mb-1">
            <label className="block text-sm font-medium text-gray-700">{t('knowledge.content')}</label>
            <span className={`text-xs ${oversized ? 'text-red-600 font-medium' : 'text-gray-400'}`}>
              {formatBytes(contentBytes)} / {formatBytes(MAX_CONTENT_BYTES)}
            </span>
          </div>
          <textarea
            value={content}
            onChange={(e) => setContent(e.target.value)}
            placeholder={t('knowledge.contentPlaceholder')}
            rows={4}
            className={`w-full px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-cyan-500 focus:outline-none resize-y ${oversized ? 'border-red-400 bg-red-50' : 'border-gray-300'}`}
            required
          />
          {oversized && (
            <p className="mt-1 text-xs text-red-600">{t('knowledge.contentTooLarge')}</p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">URL</label>
          <input
            type="url"
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            placeholder="https://..."
            className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:outline-none"
          />
        </div>

        <div className="flex justify-end gap-3">
          <button
            type="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"
          >
            {t('common.cancel')}
          </button>
          <button
            type="submit"
            disabled={createMutation.isPending || !title.trim() || !content.trim() || oversized}
            className="px-4 py-2 text-sm font-medium text-white bg-cyan-600 rounded-lg hover:bg-cyan-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
          >
            {createMutation.isPending ? (
              <span className="animate-spin h-4 w-4 border-2 border-white border-t-transparent rounded-full" />
            ) : (
              <Upload size={16} />
            )}
            {t('knowledge.save')}
          </button>
        </div>

        {createMutation.isError && (
          <div className="flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
            <AlertCircle size={16} />
            {createMutation.error?.message || t('knowledge.createError')}
          </div>
        )}
      </form>
    </div>
  );
}

function EntryRow({
  entry,
  tenantId,
}: {
  entry: KnowledgeEntry;
  tenantId: string;
}) {
  const { t } = useTranslation();
  const deleteMutation = useDeleteKnowledgeEntry(tenantId);
  const [confirmDelete, setConfirmDelete] = useState(false);

  const handleDelete = () => {
    deleteMutation.mutate(entry.id, {
      onSuccess: () => setConfirmDelete(false),
    });
  };

  return (
    <tr className="hover:bg-gray-50 transition-colors">
      <td className="px-4 py-3">
        <div className="flex items-start gap-2">
          <FileText size={16} className="text-gray-400 mt-0.5 shrink-0" />
          <div className="min-w-0">
            <div className="text-sm font-medium text-gray-900 truncate">{entry.title}</div>
            <div className="text-xs text-gray-500 truncate max-w-md">{entry.content.slice(0, 120)}{entry.content.length > 120 ? '...' : ''}</div>
          </div>
        </div>
      </td>
      <td className="px-4 py-3">
        <TypeBadge type={entry.type} />
      </td>
      <td className="px-4 py-3 text-xs text-gray-500">
        {entry.category || '-'}
      </td>
      <td className="px-4 py-3 text-xs text-gray-500">
        {entry.qdrantPointId ? (
          <span className="inline-flex items-center gap-1 text-green-600">
            <Database size={12} />
            {t('knowledge.embedded')}
          </span>
        ) : (
          <span className="text-amber-600">{t('knowledge.notEmbedded')}</span>
        )}
      </td>
      <td className="px-4 py-3 text-xs text-gray-500">
        {new Date(entry.createdAt).toLocaleDateString()}
      </td>
      <td className="px-4 py-3 text-right">
        {confirmDelete ? (
          <div className="flex items-center justify-end gap-2">
            <button
              onClick={() => setConfirmDelete(false)}
              className="px-2 py-1 text-xs text-gray-600 hover:text-gray-800"
            >
              {t('common.cancel')}
            </button>
            <button
              onClick={handleDelete}
              disabled={deleteMutation.isPending}
              className="px-2 py-1 text-xs text-white bg-red-600 rounded hover:bg-red-700 disabled:opacity-50"
            >
              {deleteMutation.isPending ? '...' : t('common.confirm')}
            </button>
          </div>
        ) : (
          <button
            onClick={() => setConfirmDelete(true)}
            className="p-1.5 text-gray-400 hover:text-red-600 rounded hover:bg-red-50 transition-colors"
            title={t('common.delete')}
          >
            <Trash2 size={14} />
          </button>
        )}
      </td>
    </tr>
  );
}

interface KnowledgeFilesTabProps {
  tenantId: string;
}

export function KnowledgeFilesTab({ tenantId }: KnowledgeFilesTabProps) {
  const { t } = useTranslation();
  const [isAdding, setIsAdding] = useState(false);
  const [typeFilter, setTypeFilter] = useState<string>('');
  const [searchQuery, setSearchQuery] = useState('');

  const { data, isLoading, error } = useKnowledgeEntries(tenantId, typeFilter ? { type: typeFilter } : undefined);
  const { data: stats } = useKnowledgeStats(tenantId);

  const capValue = tokenStorage.getCapability('knowledge_files_max');
  const maxFiles = capValue ? parseInt(capValue, 10) : 0;
  const featureEnabled = maxFiles > 0;
  const totalEntries = stats?.total || 0;
  const atLimit = !featureEnabled || totalEntries >= maxFiles;

  const entries = data?.items || [];

  // Client-side search filter (API handles type filter)
  const filtered = searchQuery
    ? entries.filter(
        (e) =>
          e.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
          e.content.toLowerCase().includes(searchQuery.toLowerCase()),
      )
    : entries;

  if (isLoading) {
    return (
      <div className="animate-pulse space-y-4 p-6">
        <div className="h-10 bg-gray-200 rounded w-1/3" />
        <div className="h-64 bg-gray-200 rounded" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-6">
        <div className="flex items-center gap-2 p-4 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
          <AlertCircle size={16} />
          {t('knowledge.loadError')}: {error.message}
        </div>
      </div>
    );
  }

  return (
    <div>
      {/* Stats bar */}
      <div className="px-6 py-3 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
        <div className="flex items-center gap-4 text-sm text-gray-600">
          {featureEnabled ? (
            <div className="flex items-center gap-3 min-w-[200px]">
              <span className="text-xs font-medium text-gray-500 uppercase whitespace-nowrap">{t('knowledge.usage')}</span>
              <UsageBar used={totalEntries} max={maxFiles} />
            </div>
          ) : (
            <span className="text-xs text-gray-500">{t('knowledge.featureDisabled')}</span>
          )}
        </div>
      </div>

      {/* Limit / feature warning */}
      {!featureEnabled && (
        <div className="mx-6 mt-4 flex items-center gap-2 p-3 bg-gray-100 border border-gray-200 rounded-lg text-sm text-gray-600">
          <ShieldAlert size={16} className="shrink-0" />
          {t('knowledge.featureDisabled')}
        </div>
      )}
      {featureEnabled && totalEntries >= maxFiles && (
        <div className="mx-6 mt-4 flex items-center gap-2 p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-800">
          <ShieldAlert size={16} className="shrink-0" />
          {t('knowledge.limitReached')}
        </div>
      )}

      {/* Toolbar */}
      <div className="px-6 py-4 flex items-center gap-3 flex-wrap">
        <div className="flex-1 min-w-[200px] max-w-sm relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
          <input
            type="text"
            placeholder={t('knowledge.searchPlaceholder')}
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-9 pr-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:outline-none"
          />
        </div>

        <select
          value={typeFilter}
          onChange={(e) => setTypeFilter(e.target.value)}
          className="px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:outline-none"
        >
          <option value="">{t('knowledge.allLegalDocTypes')}</option>
          <option value="FAQ">FAQ</option>
          <option value="PRODUCT">Product</option>
          <option value="PAGE">Page</option>
          <option value="DOCUMENT">Document</option>
          <option value="CUSTOM">Custom</option>
        </select>

        <button
          onClick={() => setIsAdding(true)}
          disabled={atLimit}
          className="ml-auto px-4 py-2 text-sm font-medium text-white bg-cyan-600 rounded-lg hover:bg-cyan-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
        >
          <Plus size={16} />
          {t('knowledge.addEntry')}
        </button>
      </div>

      {/* Add form */}
      {isAdding && !atLimit && (
        <div className="px-6">
          <AddEntryForm tenantId={tenantId} onClose={() => setIsAdding(false)} />
        </div>
      )}

      {/* Table */}
      {filtered.length === 0 ? (
        <div className="px-6 py-12 text-center">
          <Database className="mx-auto h-12 w-12 text-gray-300 mb-3" />
          <p className="text-sm text-gray-500 mb-1">{t('knowledge.noEntries')}</p>
          <p className="text-xs text-gray-400">{t('knowledge.noEntriesHint')}</p>
        </div>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 border-y border-gray-200">
              <tr>
                <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-500 uppercase">{t('knowledge.title')}</th>
                <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-500 uppercase">{t('knowledge.type')}</th>
                <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-500 uppercase">{t('knowledge.category')}</th>
                <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-500 uppercase">{t('knowledge.status')}</th>
                <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-500 uppercase">{t('knowledge.created')}</th>
                <th className="px-4 py-2.5 text-right text-xs font-medium text-gray-500 uppercase">{t('common.actions')}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {filtered.map((entry) => (
                <EntryRow key={entry.id} entry={entry} tenantId={tenantId} />
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
