"use client";

import React from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Send, Paperclip } from 'lucide-react';

interface MessageFormProps {
  input: string;
  setInput: (value: string) => void;
  handleSendMessage: (e: React.FormEvent<HTMLFormElement>) => Promise<void>;
  isLoading: boolean;
  handleFileChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  isFileSelected: boolean;
}

export default function MessageForm({
  input,
  setInput,
  handleSendMessage,
  isLoading,
  handleFileChange,
  isFileSelected,
}: MessageFormProps) {
  const fileInputRef = React.useRef<HTMLInputElement>(null);

  const handleAttachClick = () => {
    fileInputRef.current?.click();
  }

  const handleFileReset = (e: React.MouseEvent<HTMLInputElement>) => {
    // Reset file input value so the same file can be selected again
    (e.target as HTMLInputElement).value = '';
  }

  return (
    <form onSubmit={handleSendMessage} className="relative flex w-full items-center">
      <Button 
        type="button" 
        variant="ghost" 
        size="icon" 
        disabled={isLoading} 
        onClick={handleAttachClick} 
        className="absolute left-3 top-1/2 -translate-y-1/2 h-8 w-8 shrink-0 rounded-full"
      >
        <Paperclip className="h-4 w-4" />
        <span className="sr-only">Attach file</span>
      </Button>
      <input
        type="file"
        ref={fileInputRef}
        onChange={handleFileChange}
        onClick={handleFileReset}
        className="hidden"
        accept="image/*"
        disabled={isLoading}
      />
      <Input
        type="text"
        placeholder="Type a message..."
        value={input}
        onChange={(e) => setInput(e.target.value)}
        disabled={isLoading}
        className="flex-1 rounded-full border bg-input pr-12 pl-12 py-6 shadow-lg focus-visible:ring-0 focus-visible:ring-offset-0"
        autoComplete="off"
        onKeyDown={(e) => {
          if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            const form = e.target as HTMLInputElement;
            form.form?.requestSubmit();
          }
        }}
      />
      <Button type="submit" size="icon" disabled={isLoading || (!input.trim() && !isFileSelected)} className="absolute right-3 top-1/2 -translate-y-1/2 h-8 w-8 shrink-0 rounded-full">
        <Send className="h-4 w-4" />
        <span className="sr-only">Send</span>
      </Button>
    </form>
  );
}
