import { Form, Input, Select, Collapse, Button, List, Popconfirm, Tag, Switch, InputNumber } from 'antd';
import { DatabaseOutlined, RocketOutlined, SettingOutlined, ToolOutlined } from '@ant-design/icons';
import { Agent, Team, AgentAPI } from '../../../api';
import { STATUS_TAG, isImageUrl, parseModelSelections } from '../constants';
import ModelCheckboxDropdown from './ModelCheckboxDropdown';

interface CapabilitySettingsProps {
  form: any;
  agent: Agent | null;
  teams: Team[];
  models: any[];
  currentName?: string;
  agentName: string;
  selectedAvatar: string;
  setAvatarSelectorOpen: (open: boolean) => void;
  beforeUploadKnowledge: (file: any) => Promise<boolean>;
  onDeleteKnowledge: (fileId: string) => Promise<void>;
  markDirty: () => void;
}

export default function CapabilitySettings({
  form,
  agent,
  teams,
  models,
  currentName,
  agentName,
  selectedAvatar,
  setAvatarSelectorOpen,
  beforeUploadKnowledge,
  onDeleteKnowledge,
  markDirty,
}: CapabilitySettingsProps) {
  return (
    <div className="flex-1 agent-editor-pane">
      <div className="agent-editor-pane-body">
        <div className="agent-editor-pane-header">
          <div>
            <h3 className="agent-editor-pane-title">能力与设置</h3>
            <p className="agent-editor-pane-subtitle">
              这里决定它用什么模型、拥有哪些知识和技能，以及它会以怎样的方式被别人看到。
            </p>
          </div>
          <span className="agent-editor-badge">
            <ToolOutlined />
            Capability
          </span>
        </div>

        <Form form={form} layout="vertical" onValuesChange={markDirty}>
          <div className="agent-editor-intro" style={{ marginBottom: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <div
                className="rounded-full flex items-center justify-center text-3xl text-white font-bold shadow-xl relative transition-all duration-500 overflow-hidden ring-4 ring-white mx-auto"
                style={{
                  width: 88,
                  height: 88,
                  background: isImageUrl(agent?.avatar) ? '#f3f4f6' : agent?.avatar,
                  border: '3px solid rgba(255,255,255,0.92)',
                }}
                onClick={() => setAvatarSelectorOpen(true)}
              >
                {isImageUrl(agent?.avatar) ? (
                  <img src={agent?.avatar} style={{ width: '100%', height: '100%', objectFit: 'cover' }} alt="avatar" />
                ) : (
                  (agent?.name?.charAt(0) || agentName?.charAt(0) || '?').toUpperCase()
                )}
                <div className="avatar-overlay">
                  <span className="avatar-overlay-text">更换形象</span>
                </div>
              </div>
              <div style={{ minWidth: 0 }}>
                {currentName && (
                  <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--color-text)', marginBottom: 4 }}>
                    {currentName}
                  </div>
                )}
                <div style={{ fontSize: 12.5, color: 'var(--color-text-secondary)', marginBottom: 8 }}>
                  {agent?.description || '补充基础资料后，这里会更像一个完整可运营的产品角色。'}
                </div>
                <Button size="small" type="default" className="rounded-lg h-8" onClick={() => setAvatarSelectorOpen(true)}>
                  修改头像
                </Button>
              </div>
            </div>
          </div>

          <Collapse
            ghost
            expandIconPosition="end"
            className="monica-collapse-bordered mb-4"
            defaultActiveKey={['basic']}
            items={[
              {
                key: 'basic',
                label: (
                  <div className="flex items-center gap-2 font-medium text-gray-700" style={{ color: 'var(--color-text)' }}>
                    <SettingOutlined style={{ color: 'var(--color-brand)' }} />
                    基础设置
                  </div>
                ),
                children: (
                  <div className="space-y-4">
                    <div className="flex items-center gap-4 mb-2">
                      <div className="flex flex-col gap-1">
                        <span className="text-[11px] text-gray-400">名称、描述和可见性决定了这个智能体如何被理解和管理。</span>
                      </div>
                    </div>
                    <Form.Item name="name" label="名称" rules={[{ required: true }]} className="mb-3">
                      <Input placeholder="智能体名称" style={{ borderRadius: 12, height: 42 }} />
                    </Form.Item>
                    <Form.Item name="description" label="描述" className="mb-3">
                      <Input.TextArea rows={3} placeholder="简短描述这个智能体是做什么的..." style={{ borderRadius: 12 }} />
                    </Form.Item>
                    <div className="flex gap-2">
                      <Form.Item name="visibility" label="可见性" className="flex-1 mb-0">
                        <Select
                          size="middle"
                          style={{ minHeight: 42 }}
                          options={[
                            { value: 'private', label: '🔒 私有' },
                            { value: 'team', label: '👥 团队' },
                            { value: 'public', label: '🌐 公开' },
                          ]}
                        />
                      </Form.Item>
                      <Form.Item name="teamId" label="归属团队" className="flex-1 mb-0" tooltip="团队功能暂未开放">
                        <Select
                          size="middle"
                          placeholder="暂不开放"
                          disabled
                          allowClear
                          style={{ minHeight: 42 }}
                          options={teams.map((t) => ({ value: t.id, label: t.name }))}
                        />
                      </Form.Item>
                    </div>
                  </div>
                ),
              },
            ]}
          />

          <div className="monica-card !mb-4" style={{ borderRadius: 18 }}>
            <div className="flex items-center gap-2 mb-4 font-medium text-gray-700">
              <SettingOutlined style={{ color: 'var(--color-brand)' }} />
              模型设置
            </div>
            <div className="space-y-4">
              <Form.Item
                name="model"
                label="模型"
                className="mb-0"
                getValueProps={(value) => ({ value: parseModelSelections(value) })}
              >
                <ModelCheckboxDropdown models={models} />
              </Form.Item>
              <Form.Item name="temperature" label="Temperature" className="mb-0" hidden>
                <div className="flex items-center gap-4">
                  <InputNumber min={0} max={2} step={0.1} className="w-20" style={{ borderRadius: 12, height: 42 }} />
                  <span className="text-[11px] text-gray-400">控制随机性，数值越高越发散</span>
                </div>
              </Form.Item>
            </div>
          </div>

          <Collapse
            ghost
            expandIconPosition="end"
            className="monica-collapse"
            items={[
              {
                key: 'knowledge',
                label: (
                  <div className="flex items-center gap-2 font-medium text-gray-700" style={{ color: 'var(--color-text)' }}>
                    <DatabaseOutlined style={{ color: 'var(--color-brand)' }} />
                    知识库 ({agent?.knowledge?.length ?? 0})
                  </div>
                ),
                children: (
                  <div className="px-1">
                    <div className="flex justify-between items-center mb-4">
                      <span className="text-xs text-gray-500">上传文档以增强 AI 知识</span>
                      <Input
                        type="file"
                        multiple
                        style={{ display: 'none' }}
                        id="knowledge-upload"
                        onChange={async (e) => {
                          const files = e.target.files;
                          if (files) {
                            for (let i = 0; i < files.length; i++) {
                              await beforeUploadKnowledge(files[i]);
                            }
                          }
                        }}
                      />
                      <Button
                        type="primary"
                        size="small"
                        ghost
                        icon={<DatabaseOutlined />}
                        style={{ borderRadius: 10 }}
                        onClick={() => document.getElementById('knowledge-upload')?.click()}
                      >
                        添加
                      </Button>
                    </div>
                    <List
                      size="small"
                      dataSource={agent?.knowledge ?? []}
                      renderItem={(item) => (
                        <List.Item
                          className="bg-white mb-2 rounded-lg border border-gray-100 p-2"
                          actions={[
                            <Popconfirm
                            key="del"
                            title="确认删除？"
                            onConfirm={() => onDeleteKnowledge(item.id)}
                          >
                              <Button type="text" danger size="small" style={{ borderRadius: 8 }}>
                                删除
                              </Button>
                            </Popconfirm>,
                          ]}
                        >
                          <div className="flex flex-col gap-1 overflow-hidden">
                            <span className="text-sm font-medium truncate">{item.originalName}</span>
                            <span className="text-[10px] text-gray-400">
                              {item.size ? `${(item.size / 1024).toFixed(1)} KB` : ''} ·{' '}
                              {item.status === 'indexing' ? (
                                <Tag color="processing" className="m-0 text-[10px] px-1">
                                  <span
                                    className="inline-block"
                                    style={{ animation: 'pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite' }}
                                  >
                                    索引中…
                                  </span>
                                </Tag>
                              ) : (
                                <Tag color={STATUS_TAG[(item.status || 'ready')].color} className="m-0 text-[10px] px-1">
                                  {STATUS_TAG[(item.status || 'ready')].text}
                                </Tag>
                              )}
                            </span>
                          </div>
                        </List.Item>
                      )}
                    />
                  </div>
                ),
              },
              {
                key: 'skills',
                collapsible: 'disabled',
                label: (
                  <div
                    className="flex items-center gap-2 font-medium text-gray-400 cursor-not-allowed"
                    title="技能功能开发中"
                  >
                    <ToolOutlined />
                    技能 & 工具 (开发中)
                  </div>
                ),
                children: null,
              },
            ]}
          />

          <div className="monica-card mt-6" style={{ borderRadius: 18 }}>
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2 font-medium text-gray-700" style={{ color: 'var(--color-text)' }}>
                <RocketOutlined style={{ color: 'var(--color-brand)' }} />
                联网搜索
              </div>
              <Form.Item name="webSearchEnabled" valuePropName="checked" className="mb-0">
                <Switch size="small" />
              </Form.Item>
            </div>
            <div className="text-[11px] text-gray-400">
              启用后，智能体可以在回答时通过 DuckDuckGo 搜索实时信息。
            </div>
          </div>
        </Form>
      </div>
    </div>
  );
}
