import { ArrowUpOutlined, BookOutlined, CloseOutlined, DownOutlined, PaperClipOutlined } from '@ant-design/icons';
import { Button, Image as AntImage, Input, Select, Tag, Upload } from 'antd';
import type { ChatAttachment } from '../../../api';

export default function ChatInput(props: {
  input: string;
  setInput: (v: string) => void;
  sending: boolean;
  attachments: ChatAttachment[];
  setAttachments: (updater: (prev: ChatAttachment[]) => ChatAttachment[]) => void;
  imageUrls: string[];
  setImageUrls: (updater: (prev: string[]) => string[]) => void;
  onSend: () => void;
  onStop: () => void;
  onAttach: (files: File[]) => void;
  onOpenTpl: () => void;
  modelOptions: Array<{ value: string; label: string }>;
  activeModelValue: string;
  onChangeModel: (modelId: string) => void;
}) {
  const {
    input,
    setInput,
    sending,
    attachments,
    setAttachments,
    imageUrls,
    setImageUrls,
    onSend,
    onStop,
    onAttach,
    onOpenTpl,
    modelOptions,
    activeModelValue,
    onChangeModel
  } = props;

  return (
    <div className="chat-input-wrapper">
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 8 }}>
        {attachments.map((a, i) => (
          <Tag key={i} color="blue" closable style={{ borderRadius: 6, padding: '4px 8px' }} onClose={() => setAttachments((arr) => arr.filter((_, j) => j !== i))}>
            📎 {a.name}
          </Tag>
        ))}
        {imageUrls.map((u, i) => (
          <div key={i} style={{ position: 'relative' }}>
            <AntImage src={u} width={48} height={48} style={{ objectFit: 'cover', borderRadius: 8, border: '1px solid var(--color-border)' }} />
            <Button
              size="small"
              type="primary"
              shape="circle"
              icon={<CloseOutlined style={{ fontSize: 8 }} />}
              style={{ position: 'absolute', top: -6, right: -6, width: 16, height: 16, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
              onClick={() => setImageUrls((arr) => arr.filter((_, j) => j !== i))}
            />
          </div>
        ))}
      </div>

      <div className="chat-input-card">
        <div className="chat-input-stack">
          <Input.TextArea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="问我任何问题..."
            autoSize={{ minRows: 3, maxRows: 10 }}
            onKeyDown={(e) => {
              if (e.key !== 'Enter') return;
              if ((e as any).isComposing) return;

              if (e.metaKey || e.ctrlKey) {
                e.preventDefault();
                const el = e.currentTarget;
                const start = el.selectionStart ?? input.length;
                const end = el.selectionEnd ?? input.length;
                const next = input.slice(0, start) + '\n' + input.slice(end);
                setInput(next);
                requestAnimationFrame(() => {
                  el.selectionStart = el.selectionEnd = start + 1;
                });
                return;
              }

              if (!e.shiftKey && !e.altKey) {
                e.preventDefault();
                onSend();
              }
            }}
            className="chat-input-textarea"
            disabled={sending}
          />

          <div className="chat-input-toolbar">
            <div className="chat-input-toolbar-left">
              <Select
                value={activeModelValue || undefined}
                className="chat-model-select"
                popupMatchSelectWidth={false}
                options={modelOptions}
                suffixIcon={<DownOutlined className="chat-model-select-arrow" />}
                placeholder="选择模型"
                onChange={onChangeModel}
              />

              <Upload
                className="chat-upload"
                multiple
                beforeUpload={(_f, files) => {
                  onAttach(files as File[]);
                  return false;
                }}
                showUploadList={false}
                accept=".txt,.md,.markdown,.json,.csv,.pdf,.docx,.html,.htm,image/png,image/jpeg,image/webp,image/gif"
              >
                <Button type="text" className="chat-tool-button" icon={<PaperClipOutlined style={{ fontSize: 18 }} />} />
              </Upload>
              <Button type="text" className="chat-tool-button" icon={<BookOutlined style={{ fontSize: 18 }} />} onClick={onOpenTpl} />
            </div>

            {sending ? (
              <Button danger shape="circle" onClick={onStop} icon={<span className="chat-stop-icon" />} className="chat-send-button" />
            ) : (
              <Button
                type="primary"
                shape="circle"
                onClick={onSend}
                icon={<ArrowUpOutlined />}
                disabled={!input.trim()}
                className="chat-send-button chat-send-button-primary"
              />
            )}
          </div>
        </div>
      </div>

      <div className="chat-disclaimer">AI 可能会产生错误信息，请核实重要信息。</div>
    </div>
  );
}

