'use client' import { useState } from 'react' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { knowledgeApi, uploadApi } from '@/lib/api' import { useToast } from '@/contexts/ToastContext' import { Plus, Trash2, Edit2, FileText, Image as ImageIcon, Video, Link as LinkIcon, Loader2, Save, X, Tag, Calendar, GitBranch, Sparkles, Upload, Type } from 'lucide-react' import { motion, AnimatePresence } from 'framer-motion' interface KnowledgeFile { id: string name: string file_type: 'document' | 'image' | 'video' | 'link' file_url?: string external_link?: string thumbnail_url?: string description?: string send_condition: string trigger_day?: number trigger_stage_id?: string trigger_event?: string trigger_keywords?: string trigger_stage?: string ai_instruction?: string sort_order: number } const FILE_TYPES = [ { value: 'text', label: 'Текст', icon: Type, desc: 'Вставьте текст напрямую' }, { value: 'document', label: 'Документ', icon: FileText, desc: 'PDF, TXT, DOCX' }, { value: 'image', label: 'Изображение', icon: ImageIcon, desc: 'Фото, схемы' }, { value: 'video', label: 'Видео', icon: Video, desc: 'YouTube, Vimeo' }, { value: 'link', label: 'Ссылка', icon: LinkIcon, desc: 'Внешняя ссылка' } ] const SEND_CONDITIONS = [ { value: 'on_request', label: 'По запросу клиента', icon: Tag }, { value: 'by_day', label: 'На определённый день курса', icon: Calendar }, { value: 'by_stage', label: 'На этапе воронки', icon: GitBranch }, { value: 'ai_decides', label: 'AI решает сам', icon: Sparkles }, { value: 'after_purchase', label: 'После покупки', icon: Tag }, { value: 'after_booking', label: 'После записи', icon: Tag }, { value: 'on_keyword', label: 'По ключевому слову', icon: Tag } ] export function KnowledgeFilesManager() { const toast = useToast() const queryClient = useQueryClient() const [editingFile, setEditingFile] = useState(null) const [showForm, setShowForm] = useState(false) const [uploading, setUploading] = useState(false) const [formData, setFormData] = useState({ name: '', file_type: 'text', file_url: '', external_link: '', thumbnail_url: '', description: '', text_content: '', send_condition: 'on_request', trigger_day: undefined as number | undefined, trigger_stage_id: '', trigger_event: '', trigger_keywords: '', trigger_stage: '', ai_instruction: '', sort_order: 0 }) const { data: files = [], isLoading } = useQuery({ queryKey: ['knowledge-files'], queryFn: knowledgeApi.getKnowledgeFiles }) const createMutation = useMutation({ mutationFn: knowledgeApi.createKnowledgeFile, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['knowledge-files'] }) toast.success('Файл добавлен') resetForm() }, onError: () => toast.error('Ошибка при добавлении') }) const updateMutation = useMutation({ mutationFn: ({ id, data }: { id: string; data: any }) => knowledgeApi.updateKnowledgeFile(id, data), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['knowledge-files'] }) toast.success('Файл обновлён') resetForm() }, onError: () => toast.error('Ошибка при обновлении') }) const deleteMutation = useMutation({ mutationFn: knowledgeApi.deleteKnowledgeFile, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['knowledge-files'] }) toast.success('Файл удалён') }, onError: () => toast.error('Ошибка при удалении') }) const resetForm = () => { setFormData({ name: '', file_type: 'text', file_url: '', external_link: '', thumbnail_url: '', description: '', text_content: '', send_condition: 'on_request', trigger_day: undefined, trigger_stage_id: '', trigger_event: '', trigger_keywords: '', trigger_stage: '', ai_instruction: '', sort_order: 0 }) setEditingFile(null) setShowForm(false) } const handleEdit = (file: KnowledgeFile) => { setFormData({ name: file.name, file_type: file.file_type, file_url: file.file_url || '', external_link: file.external_link || '', thumbnail_url: file.thumbnail_url || '', description: file.description || '', text_content: (file as any).text_content || '', send_condition: file.send_condition, trigger_day: file.trigger_day, trigger_stage_id: file.trigger_stage_id || '', trigger_event: file.trigger_event || '', trigger_keywords: file.trigger_keywords || '', trigger_stage: file.trigger_stage || '', ai_instruction: file.ai_instruction || '', sort_order: file.sort_order }) setEditingFile(file) setShowForm(true) } const handleSubmit = () => { if (!formData.name.trim()) { toast.error('Введите название') return } if (editingFile) { updateMutation.mutate({ id: editingFile.id, data: formData }) } else { createMutation.mutate(formData) } } const getTypeIcon = (type: string) => { const found = FILE_TYPES.find(t => t.value === type) return found?.icon || FileText } if (isLoading) { return (
) } return (

Информационные файлы

Добавьте PDF, изображения, видео или ссылки, которые ИИ будет отправлять клиентам в нужный момент.

{/* List */}
{files.length === 0 ? (
Нет файлов. Добавьте материалы для клиентов!
) : ( files.map((file: KnowledgeFile) => { const TypeIcon = getTypeIcon(file.file_type) return (
{file.name}
{SEND_CONDITIONS.find(c => c.value === file.send_condition)?.label} {file.trigger_day && ( День {file.trigger_day} )} {file.trigger_keywords && ( {file.trigger_keywords} )}
) }) )}
{/* Form Modal */} {showForm && ( resetForm()} > e.stopPropagation()} >

{editingFile ? 'Редактировать файл' : 'Новый файл'}

setFormData({ ...formData, name: e.target.value })} placeholder="Например: Инструкция по курсу" className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white" />
{FILE_TYPES.map(type => ( ))}
{/* Text - Direct paste */} {formData.file_type === 'text' && (