import { useState } from 'react';
import { Button, Checkbox, Dropdown } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import { AiModel } from '../../../api';
import { DEFAULT_RH_40X40_GRAY } from '../../../constants';

interface ModelCheckboxDropdownProps {
  value?: string[];
  onChange?: (value: string[]) => void;
  models: AiModel[];
}

export default function ModelCheckboxDropdown({ value = [], onChange, models }: ModelCheckboxDropdownProps) {
  const [open, setOpen] = useState(false);
  const summary = value.length ? `${value.length} 个已选` : '选择模型';

  return (
    <Dropdown
      trigger={['click']}
      open={open}
      onOpenChange={setOpen}
      popupRender={() => (
        <div className="agent-model-dropdown-panel" onClick={(e) => e.stopPropagation()}>
          <Checkbox.Group
            value={value}
            onChange={(checked) => onChange?.(checked.map((item) => String(item)))}
            className="agent-model-checkbox-group"
          >
            {models.map((m) => {
              const inputPrice = 2 * m.model_ratio;
              const outputPrice = inputPrice * m.completion_ratio;
              return (
                <Checkbox key={m.id} value={m.id} className="agent-model-checkbox-item">
                  <div className="agent-model-checkbox-content">
                    <div className="agent-model-checkbox-meta">
                      <img
                        src={m.icon || DEFAULT_RH_40X40_GRAY}
                        alt={m.model_name}
                        className="agent-model-checkbox-icon"
                      />
                      <span className="agent-model-checkbox-name">{m.model_name}</span>
                    </div>
                    <div className="agent-model-checkbox-price">
                      <span>输入: ${inputPrice.toFixed(2)}/M</span>
                      <span>输出: ${outputPrice.toFixed(2)}/M</span>
                    </div>
                  </div>
                </Checkbox>
              );
            })}
          </Checkbox.Group>
        </div>
      )}
    >
      <Button type="text" block className="agent-model-dropdown-trigger">
        <span className="agent-model-dropdown-summary">{summary}</span>
        <span className="agent-model-dropdown-values">
          {value.length ? value.join(', ') : '未选择'}
        </span>
        <DownOutlined className="agent-model-dropdown-arrow" />
      </Button>
    </Dropdown>
  );
}
