import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Send, Paperclip, Loader2 } from "lucide-react";
import { base44 } from "@/api/base44Client";

export default function MessageInput({ conversationId, onMessageSent, currentUser }) {
  const [message, setMessage] = useState("");
  const [sending, setSending] = useState(false);

  const handleSend = async () => {
    if (!message.trim() || sending) return;

    setSending(true);
    try {
      await base44.entities.Message.create({
        conversation_id: conversationId,
        sender_id: currentUser.id,
        sender_name: currentUser.full_name || currentUser.email,
        sender_role: currentUser.role || "admin",
        content: message.trim(),
        read_by: [currentUser.id]
      });

      await base44.entities.Conversation.update(conversationId, {
        last_message: message.trim().substring(0, 100),
        last_message_at: new Date().toISOString()
      });

      setMessage("");
      onMessageSent?.();
    } catch (error) {
      console.error("Failed to send message:", error);
    } finally {
      setSending(false);
    }
  };

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

  return (
    <div className="border-t border-slate-200 p-4 bg-white">
      <div className="flex gap-2">
        <Textarea
          placeholder="Type your message..."
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          onKeyPress={handleKeyPress}
          className="min-h-[60px] max-h-[120px]"
          disabled={sending}
        />
        <div className="flex flex-col gap-2">
          <Button
            size="icon"
            onClick={handleSend}
            disabled={!message.trim() || sending}
            className="bg-[#0A39DF] hover:bg-[#0A39DF]/90"
          >
            {sending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
          </Button>
        </div>
      </div>
    </div>
  );
}