import { useState, useRef, useEffect, type KeyboardEvent } from 'react';
import { Send } from 'lucide-react';
import { Button } from '@/components/ui/button';
import type { ModelOption } from '../types';
import { useAttachments } from '../useAttachments';
import { ModelSelector } from '../components/ModelSelector';
import { AttachmentList } from '../components/AttachmentList';
import { AttachButton } from '../components/AttachButton';
import { WebpageDialog } from '../components/WebpageDialog';

type ChatLauncherProps = {
  availableModels: ModelOption[];
  selectedModel: string | null;
  onModelChange: (modelId: string) => void;
  onSubmit: (data: {
    prompt: string;
    model: string | null;
    attachmentIds?: string[];
    images?: { filename: string; dataUrl: string }[];
  }) => void;
  placeholder?: string;
};

export function ChatLauncher({
  availableModels,
  selectedModel,
  onModelChange,
  onSubmit,
  placeholder = 'What do you want to work on now?',
}: ChatLauncherProps) {
  const { attachments, attachWebpage, attachImage, removeAttachment, clearAttachments, processAttachments } =
    useAttachments();
  const [input, setInput] = useState('');
  const [urlDialogOpen, setUrlDialogOpen] = useState(false);
  const textareaRef = useRef<HTMLTextAreaElement | null>(null);

  const handleSubmit = () => {
    const text = input.trim();
    if (!text) return;

    const { prefix, ids, images } = processAttachments();
    const prompt = prefix ? `${prefix}${text}` : text;

    onSubmit({
      prompt,
      model: selectedModel,
      attachmentIds: ids.length > 0 ? ids : undefined,
      images: images.length > 0 ? images : undefined,
    });

    setInput('');
    clearAttachments();
  };

  const handleKeyDown = (ev: KeyboardEvent<HTMLTextAreaElement>) => {
    if (ev.key === 'Enter' && !ev.shiftKey) {
      ev.preventDefault();
      handleSubmit();
    }
  };

  // Auto-resize textarea
  useEffect(() => {
    const textarea = textareaRef.current;
    if (!textarea) return;
    textarea.style.height = 'auto';
    textarea.style.height = Math.min(textarea.scrollHeight, 160) + 'px';
  }, [input]);

  return (
    <div className="p-4 pb-2 pt-1">
      <AttachmentList attachments={attachments} onRemove={removeAttachment} />

      <div className="flex items-end gap-2">
        <AttachButton
          size="md"
          onAttachImage={attachImage}
          onAttachWebpage={() => setUrlDialogOpen(true)}
          onAttachText={(text) => setInput((prev) => (prev.trim() ? `${prev.replace(/\s+$/, '')}\n\n${text}` : text))}
        />
        <textarea
          ref={textareaRef}
          value={input}
          onChange={(ev) => setInput(ev.target.value)}
          onKeyDown={handleKeyDown}
          onPaste={(ev) => {
            const items = ev.clipboardData?.items;
            if (!items) return;
            for (const item of Array.from(items)) {
              if (item.type.startsWith('image/')) {
                ev.preventDefault();
                const file = item.getAsFile();
                if (file) attachImage(file);
                return;
              }
            }
          }}
          placeholder={placeholder}
          rows={1}
          className="flex-1 resize-none bg-transparent px-2 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none text-lg"
        />
        <Button
          onClick={handleSubmit}
          disabled={!input.trim()}
          size="icon"
          className="shrink-0 h-10 w-10 bg-duck-teal hover:bg-duck-teal/90 cursor-pointer disabled:opacity-40"
        >
          <Send className="h-4 w-4" />
        </Button>
      </div>

      <ModelSelector
        messages={[]}
        availableModels={availableModels}
        selectedModel={selectedModel}
        onModelChange={onModelChange}
        model={selectedModel}
        isConnected={true}
        isGenerating={false}
        hasStarted={false}
        thinkingLevel={null}
        onThinkingChange={() => {}}
      />

      <WebpageDialog open={urlDialogOpen} onOpenChange={setUrlDialogOpen} onSubmit={attachWebpage} />
    </div>
  );
}
