'use client';

import React, { memo, useCallback, useState } from 'react';
import { motion } from 'framer-motion';
import { Image as ImageIcon, Film, MessageSquare, Mic2, Music2, Maximize2, RotateCcw, ArrowRight, Loader2, X } from 'lucide-react';
import { Button } from "@/components/ui/button";
import { GenerationType } from './types';
import { TabButton } from './TabButton';
import type { InputAsset } from '../../types/node';
import { AutoResizeTextarea } from './AutoResizeTextarea';

const TABS = [
    { id: 'text', icon: MessageSquare, label: '助手' },
    { id: 'image', icon: ImageIcon, label: '图片' },
    { id: 'video', icon: Film, label: '视频' },
    { id: 'audio', icon: Mic2, label: '音频' },
    { id: 'music', icon: Music2, label: '音乐' },
] as const;

const TabList = memo(({ activeTab, onTabChange, disabled }: { activeTab: GenerationType, onTabChange: (tab: GenerationType) => void, disabled?: boolean }) => {
    return (
        <div className="flex items-center gap-1 bg-white/5 p-1 rounded-full border border-white/5">
            {TABS.map((tab) => (
                <TabButton
                    key={tab.id}
                    isActive={activeTab === tab.id}
                    onClick={(e) => {
                        e.stopPropagation();
                        onTabChange(tab.id);
                    }}
                    icon={<tab.icon className="w-3.5 h-3.5" />}
                    label={tab.label}
                    disabled={disabled}
                />
            ))}
        </div>
    );
});
TabList.displayName = 'TabList';

export const CollapsedView = memo(({ 
    inputText, 
    activeTab, 
    onTabChange,
    onInputChange,
    onSubmit,
    onWorkflowSubmit,
    onExpand,
    onClearChat,
    disableTabs = false,
    inputAssets,
    inputPlaceholder,
    isGenerating = false,
    canGenerate = true,
    currentTaskId,
    onCancel,
}: { 
    inputText: string;
    activeTab: GenerationType;
    onTabChange: (tab: GenerationType) => void;
    onInputChange: (value: string) => void;
    onSubmit: () => void;
    onWorkflowSubmit?: () => void;
    onExpand: () => void;
    onClearChat: () => void;
    isVisible?: boolean;
    disableTabs?: boolean;
    inputAssets?: InputAsset[];
    inputPlaceholder?: string;
    /** 与展开态一致：生成中时显示 Loader2，有 taskId 时可点击取消 */
    isGenerating?: boolean;
    canGenerate?: boolean;
    currentTaskId?: string;
    onCancel?: () => void;
}) => {
    const [isHoveringCancel, setIsHoveringCancel] = useState(false);
    const showCancelOnHover = isGenerating && currentTaskId;

    const handleExpandClick = useCallback((e: React.MouseEvent) => {
        e.stopPropagation();
        if (activeTab === 'text') {
            onClearChat();
        } else {
            onExpand();
        }
    }, [activeTab, onClearChat, onExpand]);

    const handleSubmitClick = useCallback((e: React.MouseEvent) => {
        e.stopPropagation();
        if (isGenerating && currentTaskId && onCancel) {
            onCancel();
        } else {
            onSubmit();
        }
    }, [onSubmit, isGenerating, currentTaskId, onCancel]);

    return (
        <motion.div 
            key="collapsed"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0, transition: { duration: 0 } }}
            className="w-full h-full flex items-center px-2 gap-3 relative"
         >
              <TabList activeTab={activeTab} onTabChange={onTabChange} disabled={disableTabs} />

              <div 
                  className="flex-1 relative min-w-0 h-full cursor-text"
                  onClick={(e) => {
                      e.stopPropagation();
                      // 点击容器时也聚焦到编辑器
                      const editor = e.currentTarget.querySelector('[contenteditable]') as HTMLElement;
                      if (editor) {
                          editor.focus();
                      }
                  }}
              >
                  <AutoResizeTextarea 
                      value={inputText}
                      onChange={onInputChange}
                      onEnter={() => {
                          // 在折叠模式下，Enter 直接提交（不支持 Shift+Enter 换行）
                          onSubmit();
                      }}
                      isExpanded={false}
                      placeholder={inputPlaceholder}
                      inputAssets={inputAssets}
                  />
              </div>

               <Button 
                  size="sm"
                  variant="ghost"
                  onClick={handleExpandClick}
                  className="flex items-center justify-center w-7 h-7 rounded-full text-foreground/50 hover:bg-white/10 hover:text-foreground transition-colors p-0 shrink-0"
                  title={activeTab === 'text' ? "重新开始对话" : "展开"}
              >
                  {activeTab === 'text' ? <RotateCcw className="w-3.5 h-3.5" /> : <Maximize2 className="w-3.5 h-3.5" />}
              </Button>

               <Button 
                  size="sm"
                  variant="ghost"
                  onClick={handleSubmitClick}
                  disabled={!canGenerate && !(isGenerating && currentTaskId)}
                  onMouseEnter={() => showCancelOnHover && setIsHoveringCancel(true)}
                  onMouseLeave={() => setIsHoveringCancel(false)}
                  className="flex items-center justify-center bg-white/10 w-7 h-7 rounded-full text-foreground hover:bg-white/20 transition-colors p-0 disabled:opacity-50 disabled:cursor-not-allowed shrink-0"
                  title={isGenerating && currentTaskId ? '取消' : '提交'}
              >
                  {isGenerating && currentTaskId && isHoveringCancel ? (
                      <X className="w-4 h-4" />
                  ) : isGenerating ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                      <ArrowRight className="w-4 h-4" />
                  )}
              </Button>
         </motion.div>
    );
});

CollapsedView.displayName = 'CollapsedView';
