'use client';

import type React from 'react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { commonEmojis } from '@/lib/emojiList';
import { FileText, FileVideo, Image, Paperclip, Send, Smile, X } from 'lucide-react';
import { useRef, useState } from 'react';

interface MessageInputProps {
    onSend?: (message: string) => void;
    onFileSend?: (files: File[]) => void;
}

export function MessageInput({ onSend, onFileSend }: MessageInputProps) {
    const [message, setMessage] = useState('');
    const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
    const [isEmojiOpen, setIsEmojiOpen] = useState(false);
    const fileInputRef = useRef<HTMLInputElement>(null);

    const handleSend = () => {
        if (message.trim() || selectedFiles.length > 0) {
            if (message.trim()) {
                onSend?.(message);
            }
            if (selectedFiles.length > 0) {
                onFileSend?.(selectedFiles);
                setSelectedFiles([]);
            }
            setMessage('');
        }
    };

    const handleKeyPress = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSend();
        }
    };

    const handleEmojiSelect = (emoji: string) => {
        setMessage((prev) => prev + emoji);
        setIsEmojiOpen(false);
    };

    const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
        const files = Array.from(e.target.files || []);
        setSelectedFiles((prev) => [...prev, ...files]);
    };

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

    const getFileIcon = (file: File) => {
        if (file.type.startsWith('image/')) return <Image className="h-4 w-4" />;
        if (file.type.startsWith('video/')) return <FileVideo className="h-4 w-4" />;
        return <FileText className="h-4 w-4" />;
    };

    return (
        <div className="border-t border-border bg-background p-4">
            {/* Selected Files Preview */}
            {selectedFiles.length > 0 && (
                <div className="mb-3 flex flex-wrap gap-2">
                    {selectedFiles.map((file, index) => (
                        <div key={index} className="flex items-center gap-2 rounded-lg bg-muted p-2 text-sm">
                            {getFileIcon(file)}
                            <span className="max-w-32 truncate">{file.name}</span>
                            <Button size="icon" variant="ghost" className="h-5 w-5" onClick={() => removeFile(index)}>
                                <X className="h-3 w-3" />
                            </Button>
                        </div>
                    ))}
                </div>
            )}

            <div className="flex items-center gap-2">
                <Input
                    placeholder="Type your message..."
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    onKeyPress={handleKeyPress}
                    className="flex-1"
                />

                {/* Emoji Picker */}
                <Popover open={isEmojiOpen} onOpenChange={setIsEmojiOpen}>
                    <PopoverTrigger asChild>
                        <Button size="icon" variant="ghost" className="h-10 w-10">
                            <Smile className="h-5 w-5" />
                        </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-80 p-2" align="end">
                        <div className="grid max-h-64 grid-cols-8 gap-1 overflow-y-auto">
                            {commonEmojis.map((emoji, index) => (
                                <Button
                                    key={index}
                                    variant="ghost"
                                    size="sm"
                                    className="h-8 w-8 p-0 text-lg hover:bg-accent"
                                    onClick={() => handleEmojiSelect(emoji)}
                                >
                                    {emoji}
                                </Button>
                            ))}
                        </div>
                    </PopoverContent>
                </Popover>

                {/* File Picker */}
                <Button size="icon" variant="ghost" className="h-10 w-10" onClick={() => fileInputRef.current?.click()}>
                    <Paperclip className="h-5 w-5" />
                </Button>
                <input
                    ref={fileInputRef}
                    type="file"
                    multiple
                    accept="image/*,video/*,.pdf,.doc,.docx,.txt"
                    onChange={handleFileSelect}
                    className="hidden"
                />

                <Button size="icon" onClick={handleSend} disabled={!message.trim() && selectedFiles.length === 0} className="h-10 w-10">
                    <Send className="h-5 w-5" />
                </Button>
            </div>
        </div>
    );
}
