'use client';

import React, { useState, useRef, useEffect } from 'react';
import { queryKeys } from '@/lib/cache/queryKeys';
import { Input, Button, Space, Upload, Tooltip, Avatar, List } from 'antd';
import { message } from '@/lib/feedback/message';
import { Bold, Code, Italic, Link, Paperclip, Send, User } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import type { UploadFile } from 'antd/es/upload';
import type { Usuario } from '@/types';

const { TextArea } = Input;

interface RichCommentEditorProps {
    value?: string;
    onChange?: (value: string) => void;
    onSubmit?: (content: string, mentions: number[], attachments: File[]) => void;
    placeholder?: string;
    loading?: boolean;
    showAttachments?: boolean;
    projetoId?: number;
}

export function RichCommentEditor({
    value = '',
    onChange,
    onSubmit,
    placeholder = 'Digite seu comentário... (use @ para mencionar, ``` para código)',
    loading = false,
    showAttachments = true,
    projetoId: _projetoId,
}: RichCommentEditorProps) {
    const [content, setContent] = useState(value);
    const [mentions, setMentions] = useState<number[]>([]);
    const [files, setFiles] = useState<UploadFile[]>([]);
    const [showMentionSuggestions, setShowMentionSuggestions] = useState(false);
    const [mentionQuery, setMentionQuery] = useState('');
    const [mentionPosition, setMentionPosition] = useState({ top: 0, left: 0 });
    const textareaRef = useRef<HTMLTextAreaElement>(null);
    const [cursorPosition, setCursorPosition] = useState(0);

    // Buscar usuários para mentions
    const { data: usuariosData } = useQueryCache<{ data: Array<Usuario> }>({
        queryKey: queryKeys.usuariosCatalog.list('mentions'),
        endpoint: API_ENDPOINTS.usuarios.index,
        params: { per_page: 100 },
        enabled: showMentionSuggestions && mentionQuery.length > 0,
        staleTime: 5 * 60 * 1000,
    });

    const usuarios = usuariosData?.data || [];

    // Filtrar usuários baseado na query
    const filteredUsuarios = usuarios.filter(
        (u) =>
            u.nome?.toLowerCase().includes(mentionQuery.toLowerCase()) ||
            u.email?.toLowerCase().includes(mentionQuery.toLowerCase())
    );

    // Detectar mentions no texto
    useEffect(() => {
        if (!textareaRef.current) return;

        const textarea = textareaRef.current;
        const position = textarea.selectionStart;
        const textBeforeCursor = content.substring(0, position);
        const lastAtIndex = textBeforeCursor.lastIndexOf('@');

        if (lastAtIndex !== -1) {
            const textAfterAt = textBeforeCursor.substring(lastAtIndex + 1);
            // Verificar se não há espaço após o @
            if (!textAfterAt.includes(' ') && !textAfterAt.includes('\n')) {
                const query = textAfterAt.toLowerCase();
                setMentionQuery(query);
                setShowMentionSuggestions(true);

                // Calcular posição do popover
                const textareaRect = textarea.getBoundingClientRect();
                const lineHeight = 20;
                const lines = textBeforeCursor.split('\n').length;
                setMentionPosition({
                    top: textareaRect.top + lines * lineHeight + 30,
                    left: textareaRect.left + 10,
                });
            } else {
                setShowMentionSuggestions(false);
            }
        } else {
            setShowMentionSuggestions(false);
        }
    }, [content, cursorPosition]);

    // Extrair mentions do conteúdo
    useEffect(() => {
        const mentionRegex = /@\[(\d+)\]/g;
        const foundMentions: number[] = [];
        let match;

        while ((match = mentionRegex.exec(content)) !== null) {
            foundMentions.push(parseInt(match[1], 10));
        }

        setMentions(foundMentions);
    }, [content]);

    const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        const newValue = e.target.value;
        setContent(newValue);
        setCursorPosition(e.target.selectionStart);
        onChange?.(newValue);
    };

    const handleSelectMention = (usuario: Usuario) => {
        if (!textareaRef.current) return;

        const textarea = textareaRef.current;
        const position = textarea.selectionStart;
        const textBeforeCursor = content.substring(0, position);
        const lastAtIndex = textBeforeCursor.lastIndexOf('@');
        const textAfterCursor = content.substring(position);

        const newContent =
            content.substring(0, lastAtIndex) +
            `@[${usuario.id}](${usuario.nome})` +
            textAfterCursor;

        setContent(newContent);
        setShowMentionSuggestions(false);
        onChange?.(newContent);

        // Focar no textarea novamente
        setTimeout(() => {
            textarea.focus();
            const newPosition = lastAtIndex + `@[${usuario.id}](${usuario.nome})`.length;
            textarea.setSelectionRange(newPosition, newPosition);
        }, 0);
    };

    const insertText = (before: string, after: string = '') => {
        if (!textareaRef.current) return;

        const textarea = textareaRef.current;
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        const selectedText = content.substring(start, end);
        const newText =
            content.substring(0, start) + before + selectedText + after + content.substring(end);

        setContent(newText);
        onChange?.(newText);

        setTimeout(() => {
            textarea.focus();
            const newPosition = start + before.length + selectedText.length + after.length;
            textarea.setSelectionRange(newPosition, newPosition);
        }, 0);
    };

    const handleBold = () => insertText('**', '**');
    const handleItalic = () => insertText('*', '*');
    const handleCode = () => insertText('`', '`');
    const handleCodeBlock = () => insertText('```\n', '\n```');
    const handleLink = () => {
        const url = prompt('Digite a URL:');
        if (url) {
            const text = textareaRef.current?.selectionStart !== textareaRef.current?.selectionEnd
                ? content.substring(textareaRef.current!.selectionStart, textareaRef.current!.selectionEnd)
                : 'link';
            insertText(`[${text}](`, ')');
        }
    };

    const handleSubmit = () => {
        if (!content.trim()) {
            message.warning('Digite um comentário');
            return;
        }

        const attachmentFiles = files
            .filter((f) => f.originFileObj)
            .map((f) => f.originFileObj!);

        onSubmit?.(content, mentions, attachmentFiles);
        
        // Reset após envio
        setContent('');
        setFiles([]);
        setMentions([]);
        onChange?.('');
    };

    const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
        // Enter para enviar (sem Shift)
        if (e.key === 'Enter' && !e.shiftKey && !showMentionSuggestions) {
            e.preventDefault();
            handleSubmit();
        }
    };

    return (
        <div>
            {/* Toolbar */}
            <div
                style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    marginBottom: 8,
                    padding: '8px 12px',
                    background: '#f5f5f5',
                    borderRadius: '4px 4px 0 0',
                }}
            >
                <Space>
                    <Tooltip title="Negrito (Ctrl+B)">
                        <Button
                            type="text"
                            size="small"
                            icon={<Bold size={ICON_SIZE_MD} aria-hidden />}
                            onClick={handleBold}
                        />
                    </Tooltip>
                    <Tooltip title="Itálico (Ctrl+I)">
                        <Button
                            type="text"
                            size="small"
                            icon={<Italic size={ICON_SIZE_MD} aria-hidden />}
                            onClick={handleItalic}
                        />
                    </Tooltip>
                    <Tooltip title="Código inline">
                        <Button
                            type="text"
                            size="small"
                            icon={<Code size={ICON_SIZE_MD} aria-hidden />}
                            onClick={handleCode}
                        />
                    </Tooltip>
                    <Tooltip title="Bloco de código">
                        <Button
                            type="text"
                            size="small"
                            onClick={handleCodeBlock}
                        >
                            {'</>'}
                        </Button>
                    </Tooltip>
                    <Tooltip title="Link">
                        <Button
                            type="text"
                            size="small"
                            icon={<Link size={ICON_SIZE_MD} aria-hidden />}
                            onClick={handleLink}
                        />
                    </Tooltip>
                </Space>
                {showAttachments && (
                    <Upload
                        fileList={files}
                        onChange={({ fileList }) => setFiles(fileList)}
                        beforeUpload={() => false}
                        multiple
                        maxCount={5}
                    >
                        <Tooltip title="Anexar arquivo">
                            <Button type="text" size="small" icon={<Paperclip size={ICON_SIZE_MD} aria-hidden />} />
                        </Tooltip>
                    </Upload>
                )}
            </div>

            {/* Textarea */}
            <TextArea
                ref={textareaRef}
                value={content}
                onChange={handleContentChange}
                onKeyDown={handleKeyDown}
                onSelect={(e) => {
                    const target = e.target as HTMLTextAreaElement;
                    setCursorPosition(target.selectionStart);
                }}
                placeholder={placeholder}
                rows={4}
                style={{ borderRadius: '0 0 4px 4px' }}
            />

            {/* Mention Suggestions */}
            {showMentionSuggestions && filteredUsuarios.length > 0 && (
                <div
                    style={{
                        position: 'fixed',
                        top: mentionPosition.top,
                        left: mentionPosition.left,
                        zIndex: 1000,
                        background: 'white',
                        border: '1px solid #d9d9d9',
                        borderRadius: 4,
                        boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                        maxHeight: 200,
                        overflowY: 'auto',
                        minWidth: 200,
                    }}
                >
                    <List
                        size="small"
                        dataSource={filteredUsuarios.slice(0, 5)}
                        renderItem={(usuario) => (
                            <List.Item
                                style={{ cursor: 'pointer', padding: '8px 12px' }}
                                onClick={() => handleSelectMention(usuario)}
                                onMouseEnter={(e) => {
                                    e.currentTarget.style.background = '#f5f5f5';
                                }}
                                onMouseLeave={(e) => {
                                    e.currentTarget.style.background = 'white';
                                }}
                            >
                                <List.Item.Meta
                                    avatar={
                                        <Avatar size="small" icon={<User size={ICON_SIZE_MD} aria-hidden />}>
                                            {usuario.nome?.charAt(0).toUpperCase()}
                                        </Avatar>
                                    }
                                    title={usuario.nome}
                                    description={usuario.email}
                                />
                            </List.Item>
                        )}
                    />
                </div>
            )}

            {/* Preview de arquivos */}
            {files.length > 0 && (
                <div style={{ marginTop: 8, fontSize: 12, color: '#666' }}>
                    {files.length} arquivo(s) anexado(s)
                </div>
            )}

            {/* Botão de enviar */}
            <div style={{ marginTop: 8, display: 'flex', justifyContent: 'flex-end' }}>
                <Button
                    type="primary"
                    icon={<Send size={ICON_SIZE_MD} aria-hidden />}
                    onClick={handleSubmit}
                    loading={loading}
                    disabled={!content.trim()}
                >
                    Enviar
                </Button>
            </div>
        </div>
    );
}

