"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { Send, FileText, Paperclip, X, FileImage, FileSpreadsheet, FileArchive, File as FileIconGeneric } from "lucide-react";
import toast from "react-hot-toast";
import { TemplatePicker } from "./TemplatePicker";

interface MessageComposerProps {
    onSend: (message: string, files?: File[]) => Promise<void>;
    placeholder?: string;
    contextParams?: Record<string, string>;
    onTypingChange?: (isTyping: boolean) => void;
    conversationId?: string;
}

export function MessageComposer({ onSend, placeholder = "Type a message...", contextParams, onTypingChange, conversationId }: MessageComposerProps) {
    const [message, setMessage] = useState("");
    const [isSending, setIsSending] = useState(false);
    const [showPicker, setShowPicker] = useState(false);
    const [files, setFiles] = useState<File[]>([]);
    const [isDragging, setIsDragging] = useState(false);
    const textareaRef = useRef<HTMLTextAreaElement>(null);
    const fileInputRef = useRef<HTMLInputElement>(null);
    const containerRef = useRef<HTMLDivElement>(null);
    const typingTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
    const draftTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
    const draftRestoredRef = useRef(false);

    // Draft key for localStorage
    const draftKey = conversationId ? `draft_${conversationId}` : null;

    // Restore draft on mount
    useEffect(() => {
        if (draftKey && !draftRestoredRef.current) {
            draftRestoredRef.current = true;
            try {
                const saved = localStorage.getItem(draftKey);
                if (saved) {
                    setMessage(saved);
                }
            } catch {
                // localStorage not available
            }
        }
    }, [draftKey]);

    // Auto-save draft every 2 seconds
    useEffect(() => {
        if (!draftKey) return;

        if (draftTimerRef.current) clearTimeout(draftTimerRef.current);

        draftTimerRef.current = setTimeout(() => {
            try {
                if (message.trim()) {
                    localStorage.setItem(draftKey, message);
                } else {
                    localStorage.removeItem(draftKey);
                }
            } catch {
                // localStorage not available
            }
        }, 2000);

        return () => {
            if (draftTimerRef.current) clearTimeout(draftTimerRef.current);
        };
    }, [message, draftKey]);

    // Clear draft helper
    const clearDraft = useCallback(() => {
        if (draftKey) {
            try { localStorage.removeItem(draftKey); } catch { /* noop */ }
        }
    }, [draftKey]);

    // Auto-resize textarea
    useEffect(() => {
        if (textareaRef.current) {
            textareaRef.current.style.height = "auto";
            textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 150) + "px";
        }
    }, [message]);

    // Click outside to close picker
    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
                setShowPicker(false);
            }
        }
        if (showPicker) {
            document.addEventListener("mousedown", handleClickOutside);
        }
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, [showPicker]);

    const handleSend = async (e?: React.FormEvent) => {
        if (e) e.preventDefault();

        // Prevent sending if empty and no files
        if ((!message.trim() && files.length === 0) || isSending) return;

        // If no message but we have files, send an attachment-only message
        // (the action handles empty initial message if file follows ideally, but we need some text or we need the action to accept it)
        const finalMessage = message.trim() || "[Attachment]";

        setIsSending(true);
        try {
            await onSend(finalMessage, files.length > 0 ? files : undefined);
            setMessage("");
            setFiles([]);
            clearDraft();
            // Stop typing indicator on send
            onTypingChange?.(false);
            if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
        } finally {
            setIsSending(false);
            if (textareaRef.current) {
                textareaRef.current.focus();
            }
        }
    };

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
            handleSend();
        }
        // Also send on Enter without modifier (Shift+Enter for newline)
        if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
            e.preventDefault();
            handleSend();
        }
    };

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files.length > 0) {
            const newFiles = Array.from(e.target.files);
            const validFiles = newFiles.filter(file => {
                if (file.size > 10 * 1024 * 1024) {
                    toast.error(`File ${file.name} exceeds the 10MB limit.`);
                    return false;
                }
                return true;
            });
            if (validFiles.length > 0) {
                setFiles(prev => [...prev, ...validFiles]);
            }
        }
    };

    const removeFile = (index: number) => {
        setFiles(prev => prev.filter((_, i) => i !== index));
    };

    const handleTemplateSelect = (content: string) => {
        setMessage(prev => prev ? `${prev}\n\n${content}` : content);
        setShowPicker(false);
        if (textareaRef.current) {
            textareaRef.current.focus();
        }
    };

    // Typing indicator logic
    const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        setMessage(e.target.value);

        // Emit typing start
        if (e.target.value.trim().length > 0) {
            onTypingChange?.(true);
        }

        // Clear previous timeout
        if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);

        // Set timeout to emit typing stop after 3 seconds of inactivity
        typingTimeoutRef.current = setTimeout(() => {
            onTypingChange?.(false);
        }, 3000);
    };

    // Drag and Drop handlers
    const handleDragOver = (e: React.DragEvent) => {
        e.preventDefault();
        e.stopPropagation();
        if (e.dataTransfer.types.includes("Files")) {
            setIsDragging(true);
        }
    };

    const handleDragLeave = (e: React.DragEvent) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragging(false);
    };

    const handleDrop = (e: React.DragEvent) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragging(false);

        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            const newFiles = Array.from(e.dataTransfer.files).filter(file => {
                if (file.size > 10 * 1024 * 1024) {
                    toast.error(`File ${file.name} exceeds the 10MB limit.`);
                    return false;
                }
                const isValidType = file.type.startsWith('image/') ||
                    file.type === 'application/pdf' ||
                    file.name.match(/\.(doc|docx|csv|txt)$/i);
                if (!isValidType) {
                    toast.error(`File type not supported: ${file.name}`);
                }
                return isValidType;
            });

            if (newFiles.length > 0) {
                setFiles(prev => [...prev, ...newFiles]);
            }
        }
    };

    return (
        <div
            className={`px-5 py-3 border-t border-slate-100 bg-white shrink-0 relative transition-colors ${isDragging ? 'bg-primary/5 border-primary ring-2 ring-inset ring-primary' : ''}`}
            ref={containerRef}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
        >
            {isDragging && (
                <div className="absolute inset-0 z-50 flex items-center justify-center bg-primary/10 rounded-xl backdrop-blur-[1px] m-2 border-2 border-dashed border-primary">
                    <div className="bg-white px-4 py-2 rounded-full shadow-lg flex items-center gap-2 text-primary font-medium text-sm">
                        <Paperclip className="w-4 h-4" /> Drop files here to attach
                    </div>
                </div>
            )}

            {files.length > 0 && (
                <div className="flex flex-wrap gap-3 mb-3 pl-[42px] pr-[52px]">
                    {files.map((file, i) => {
                        const isImage = file.type.startsWith('image/');
                        const previewUrl = isImage ? URL.createObjectURL(file) : null;

                        const getFileIcon = () => {
                            const ext = file.name.split('.').pop()?.toLowerCase() || '';
                            if (['pdf', 'doc', 'docx', 'txt'].includes(ext)) return <FileText className="w-4 h-4 text-slate-400 shrink-0" />;
                            if (['csv', 'xls', 'xlsx'].includes(ext)) return <FileSpreadsheet className="w-4 h-4 text-slate-400 shrink-0" />;
                            if (['zip', 'rar', 'tar', 'gz'].includes(ext)) return <FileArchive className="w-4 h-4 text-slate-400 shrink-0" />;
                            return <FileIconGeneric className="w-4 h-4 text-slate-400 shrink-0" />;
                        };

                        return (
                            <div key={i} className={`relative flex items-center gap-2 bg-slate-50 text-slate-700 rounded-lg text-xs font-medium border border-slate-200 group transition-all hover:border-slate-300 shadow-sm ${isImage ? 'p-1' : 'px-3 py-2'}`}>
                                {isImage && previewUrl ? (
                                    <div className="relative w-14 h-14 rounded overflow-hidden">
                                        <img src={previewUrl} alt={file.name} className="w-full h-full object-cover" />
                                    </div>
                                ) : (
                                    getFileIcon()
                                )}
                                {!isImage && (
                                    <div className="flex flex-col min-w-0 max-w-[140px]">
                                        <span className="truncate">{file.name}</span>
                                        <span className="text-[9px] text-slate-400 font-normal">{(file.size / 1024 / 1024).toFixed(2)} MB</span>
                                    </div>
                                )}
                                <button
                                    type="button"
                                    onClick={() => removeFile(i)}
                                    className="absolute -top-2 -right-2 bg-white border border-slate-200 text-slate-400 hover:text-red-500 hover:border-red-200 rounded-full p-0.5 transition-colors opacity-0 group-hover:opacity-100 shadow-sm"
                                    title="Remove attachment"
                                >
                                    <X className="w-3.5 h-3.5" />
                                </button>
                            </div>
                        );
                    })}
                </div>
            )}

            <form onSubmit={handleSend} className="flex items-end gap-2.5 relative">

                {/* Template Picker Popover */}
                {showPicker && (
                    <TemplatePicker
                        onClose={() => setShowPicker(false)}
                        onSelect={handleTemplateSelect}
                        contextParams={contextParams}
                    />
                )}

                {/* Template Picker Toggle Button */}
                <div className="flex flex-col gap-1.5 shrink-0 mb-0.5">
                    <button
                        type="button"
                        onClick={() => setShowPicker(prev => !prev)}
                        className={`p-2.5 rounded-xl transition-colors ${showPicker
                            ? "bg-slate-800 text-white"
                            : "text-slate-400 hover:bg-slate-100 hover:text-slate-600"
                            }`}
                        title="Insert Template"
                    >
                        <FileText className="w-5 h-5" />
                    </button>

                    <button
                        type="button"
                        onClick={() => fileInputRef.current?.click()}
                        className="p-2.5 rounded-xl text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors"
                        title="Attach File"
                    >
                        <Paperclip className="w-5 h-5" />
                    </button>
                    <input
                        type="file"
                        ref={fileInputRef}
                        onChange={handleFileChange}
                        multiple
                        className="hidden"
                        accept=".pdf,.doc,.docx,.png,.jpg,.jpeg,.webp,.csv"
                    />
                </div>

                <div className="flex-1 relative">
                    <textarea
                        ref={textareaRef}
                        value={message}
                        onChange={handleInputChange}
                        onKeyDown={handleKeyDown}
                        placeholder={placeholder}
                        rows={1}
                        className="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 outline-none focus:border-primary focus:ring-2 focus:ring-primary/10 transition-all text-sm resize-none"
                        disabled={isSending}
                    />
                    {message.length > 4500 && (
                        <span className={`absolute right-3 bottom-3 text-[10px] bg-white px-1 font-medium ${message.length > 4900 ? "text-red-500" : "text-slate-400"
                            }`}>
                            {message.length}/5000
                        </span>
                    )}
                </div>

                <button
                    type="submit"
                    disabled={(!message.trim() && files.length === 0) || isSending || message.length > 5000}
                    className="p-2.5 rounded-xl bg-primary text-white hover:bg-primary/90 transition-colors disabled:opacity-40 disabled:cursor-not-allowed shadow-sm shrink-0 mb-0.5"
                >
                    {isSending ? (
                        <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    ) : (
                        <Send className="w-5 h-5 ml-[-2px] mt-[1px]" />
                    )}
                </button>
            </form>
            <div className="flex justify-end pr-[52px]">
                <p className="text-[10px] text-slate-400 mt-1.5">
                    Enter to send · Shift+Enter for new line
                </p>
            </div>
        </div>
    );
}
