'use client';

import { useState, useRef, useCallback } from 'react';
import { messageApi, fileApi } from '@/lib/api';
import { emitTyping } from '@/lib/socket';
import { SmilePlus, Paperclip, Send, X } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

interface MessageInputProps {
  channelId: string;
}

export function MessageInput({ channelId }: MessageInputProps) {
  const [content, setContent] = useState('');
  const [files, setFiles] = useState<File[]>([]);
  const [uploading, setUploading] = useState(false);
  const typingTimeout = useRef<NodeJS.Timeout | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleTyping = useCallback(() => {
    emitTyping(channelId, true);
    if (typingTimeout.current) clearTimeout(typingTimeout.current);
    typingTimeout.current = setTimeout(() => {
      emitTyping(channelId, false);
    }, 2000);
  }, [channelId]);

  const handleSend = async () => {
    if ((!content.trim() && files.length === 0) || uploading) return;

    setUploading(true);
    try {
      let uploadedIds: string[] = [];

      if (files.length > 0) {
        const formData = new FormData();
        files.forEach(f => formData.append('files', f));
        const { data } = await fileApi.uploadMultiple(formData);
        uploadedIds = data.map((f: any) => f.id);
      }

      await messageApi.send(channelId, {
        content: content.trim(),
        attachments: uploadedIds
      });

      setContent('');
      setFiles([]);
      emitTyping(channelId, false);
    } catch (err) {
      console.error('Failed to send message', err);
    } finally {
      setUploading(false);
    }
  };

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

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

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

  return (
    <div className="glass rounded-xl border border-vault-border/50">
      {/* File previews */}
      <AnimatePresence>
        {files.length > 0 && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            className="flex flex-wrap gap-2 px-3 pt-3"
          >
            {files.map((file, i) => (
              <div key={i} className="glass-darker px-3 py-1.5 rounded-lg flex items-center gap-2 text-xs">
                <span className="text-vault-muted">
                  {file.type.startsWith('image/') ? '🖼️' : file.type.startsWith('video/') ? '🎬' : '📎'}
                </span>
                <span className="truncate max-w-[120px]">{file.name}</span>
                <button onClick={() => removeFile(i)} className="text-vault-muted hover:text-red-400">
                  <X className="w-3 h-3" />
                </button>
              </div>
            ))}
          </motion.div>
        )}
      </AnimatePresence>

      {/* Input row */}
      <div className="flex items-end gap-2 p-2">
        <button
          onClick={() => fileInputRef.current?.click()}
          className="p-2 rounded-lg text-vault-muted hover:text-vault-text hover:bg-vault-surface/50 transition-all"
        >
          <Paperclip className="w-5 h-5" />
        </button>
        <input
          ref={fileInputRef}
          type="file"
          multiple
          onChange={handleFileSelect}
          className="hidden"
        />

        <div className="flex-1">
          <textarea
            value={content}
            onChange={(e) => { setContent(e.target.value); handleTyping(); }}
            onKeyDown={handleKeyDown}
            placeholder={`Message #${channelId.slice(0, 8)}...`}
            rows={1}
            className="w-full bg-transparent text-sm text-vault-text placeholder-vault-muted/50 resize-none focus:outline-none max-h-32 py-1.5"
          />
        </div>

        <button
          onClick={handleSend}
          disabled={(!content.trim() && files.length === 0) || uploading}
          className="p-2 rounded-lg bg-primary-500 hover:bg-primary-600 text-white transition-all disabled:opacity-30 disabled:cursor-not-allowed"
        >
          {uploading ? (
            <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
          ) : (
            <Send className="w-5 h-5" />
          )}
        </button>
      </div>
    </div>
  );
}
