import { Send } from 'lucide-react';

import { FileAttachmentPicker } from '@/components/chat/file-attachment-picker';
import { ModelSelector } from '@/components/chat/model-selector';
import { PreviewContextButton } from '@/components/chat/preview-context-button';
import { ResearchToggle } from '@/components/chat/research-toggle';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { useMessageComposerState } from '@/hooks/chat/use-message-composer-state';
import { useTranslation } from '@/lib/i18n';
import type { MessageComposerProps } from '@/types';

export function MessageComposer({
  onSend,
  isPending,
  selectedModel,
  onModelChange,
  threadId,
}: MessageComposerProps): React.ReactElement {
  const { t } = useTranslation();
  const {
    content,
    validationError,
    selectedFileIds,
    setSelectedFileIds,
    research,
    setResearch,
    researchProviders,
    isResearchProvidersLoading,
    handleSubmit,
    handleKeyDown,
    handleChange,
  } = useMessageComposerState({ onSend, isPending, selectedModel });

  return (
    <form onSubmit={handleSubmit} className="flex h-full flex-col gap-1">
      <div className="mb-1 flex shrink-0 flex-wrap items-center gap-2">
        <ModelSelector value={selectedModel} onChange={onModelChange} disabled={isPending} />
        <FileAttachmentPicker
          selectedFileIds={selectedFileIds}
          onChange={setSelectedFileIds}
          disabled={isPending}
        />
        <ResearchToggle
          value={research}
          providers={researchProviders}
          isProvidersLoading={isResearchProvidersLoading}
          onChange={setResearch}
          disabled={isPending}
        />
        {threadId ? <PreviewContextButton threadId={threadId} draft={content} /> : null}
      </div>
      <div className="flex min-h-0 flex-1 gap-2">
        <Textarea
          value={content}
          onChange={handleChange}
          onKeyDown={handleKeyDown}
          placeholder={t('chat.composerPlaceholder')}
          className="h-full min-h-0 flex-1 resize-none"
          disabled={isPending}
        />
        <Button
          type="submit"
          size="icon"
          className="min-h-11 min-w-11 shrink-0 self-end"
          disabled={isPending || !content.trim()}
        >
          <Send className="h-4 w-4" />
          <span className="sr-only">{t('chat.sendMessage')}</span>
        </Button>
      </div>
      {validationError ? <p className="mt-1 text-sm text-destructive">{validationError}</p> : null}
    </form>
  );
}
