import { useState } from 'react';
import { Loader2, Mic, Send, Square } from 'lucide-react';
import { Button } from '@/components/ui/button';
import type { UseEmbeddableChatType } from '../EmbeddableChat/useEmbeddableChat';
import { useAudioRecording } from '../useAudioRecording';
import { ModelSelector } from './ModelSelector';
import { AttachmentList } from './AttachmentList';
import { AttachButton } from './AttachButton';
import { WebpageDialog } from './WebpageDialog';

type InputAreaProps = {
  manager: UseEmbeddableChatType;
};

export const InputArea = ({ manager }: InputAreaProps) => {
  const {
    input,
    setInput,
    handleSend,
    handleKeyDown,
    stopGeneration,
    isGenerating,
    isConnected,
    commandFeedback,
    textareaRef,
    messages,
    availableModels,
    selectedModel,
    setSelectedModel,
    model,
    hasStarted,
    attachments,
    attachWebpage,
    attachImage,
    removeAttachment,
    appendToInput,
    thinkingLevel,
    setThinkingLevel,
  } = manager;

  const { recording, transcribing, toggleRecording } = useAudioRecording(appendToInput);
  const [urlDialogOpen, setUrlDialogOpen] = useState(false);

  return (
    <div className="shrink-0 border-t border-duck-dark/10 bg-background/60 p-2 md:p-3">
      {commandFeedback && (
        <div className="mb-2 px-3 py-1.5 text-xs text-duck-teal bg-duck-teal/10 rounded-md">{commandFeedback}</div>
      )}

      <AttachmentList attachments={attachments} onRemove={removeAttachment} />

      <div className="flex items-end gap-1 md:gap-2">
        <AttachButton onAttachImage={attachImage} onAttachWebpage={() => setUrlDialogOpen(true)} />
        <MicButton recording={recording} transcribing={transcribing} onToggle={toggleRecording} />

        <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="Type a message..."
          rows={1}
          className="min-w-0 flex-1 resize-none rounded-lg border border-duck-dark/20 bg-background/80 px-2 py-1.5 md:px-3 md:py-2 text-base md:text-sm text-duck-dark placeholder:text-duck-dark/30 focus:outline-none focus:ring-2 focus:ring-duck-teal/30 focus:border-duck-teal/50"
        />
        {isGenerating ? (
          <Button onClick={stopGeneration} variant="destructive" size="icon" className="shrink-0 h-7 w-7 md:h-9 md:w-9 cursor-pointer">
            <Square className="h-4 w-4" />
          </Button>
        ) : (
          <Button
            onClick={handleSend}
            disabled={!input.trim() || !isConnected}
            size="icon"
            className="shrink-0 h-7 w-7 md:h-9 md:w-9 bg-duck-teal hover:bg-duck-teal/90 cursor-pointer disabled:opacity-40"
          >
            <Send className="h-4 w-4" />
          </Button>
        )}
      </div>
      <ModelSelector
        messages={messages}
        availableModels={availableModels}
        selectedModel={selectedModel}
        onModelChange={setSelectedModel}
        model={model}
        isConnected={isConnected}
        isGenerating={isGenerating}
        hasStarted={hasStarted}
        thinkingLevel={thinkingLevel}
        onThinkingChange={setThinkingLevel}
      />

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

// ── Helpers ──

type MicButtonProps = {
  recording: boolean;
  transcribing: boolean;
  onToggle: () => void;
};

const MicButton = ({ recording, transcribing, onToggle }: MicButtonProps) => (
  <button
    type="button"
    disabled={transcribing}
    onClick={onToggle}
    className="relative shrink-0 h-7 w-7 md:h-9 md:w-9 flex items-center justify-center rounded-lg text-duck-dark/40 hover:text-duck-dark/70 hover:bg-duck-dark/5 transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
  >
    {transcribing ? (
      <Loader2 className="h-4 w-4 animate-spin" />
    ) : recording ? (
      <>
        <span className="absolute inset-0 rounded-lg animate-ping bg-red-400/30" />
        <Square className="h-3.5 w-3.5 text-red-500" />
      </>
    ) : (
      <Mic className="h-4 w-4" />
    )}
  </button>
);
