import { Modal, Button, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { Agent, AgentAPI } from '../../../api';
import { DEFAULT_AVATAR, PRESET_AVATARS } from '../constants';

interface AvatarSelectorProps {
  open: boolean;
  onCancel: () => void;
  agent: Agent | null;
  avatarUploading: boolean;
  beforeUploadEditAvatar: (file: any) => Promise<boolean>;
  onAvatarSelect: (avatarUrl: string) => Promise<void>;
}

export default function AvatarSelector({
  open,
  onCancel,
  agent,
  avatarUploading,
  beforeUploadEditAvatar,
  onAvatarSelect,
}: AvatarSelectorProps) {
  return (
    <Modal title="选择头像形象" open={open} onCancel={onCancel} footer={null} width={600} centered>
      <div className="py-4">
        <div className="flex items-center justify-between gap-3 mb-4">
          <div className="text-[11px] font-bold text-gray-400 uppercase tracking-widest">
            点击即可更换
          </div>
          <Upload accept="image/png,image/jpeg,image/webp,image/gif" showUploadList={false} beforeUpload={beforeUploadEditAvatar}>
            <Button icon={<UploadOutlined />} loading={avatarUploading} style={{ borderRadius: 10 }}>
              上传图片
            </Button>
          </Upload>
        </div>
        <div className="bg-gray-50 p-4 rounded-2xl max-h-[400px] overflow-y-auto monica-scrollbar" style={{ width: '100%', display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px' }}>
          {[DEFAULT_AVATAR, ...PRESET_AVATARS].map((url) => (
            <div
              key={url}
              onClick={async () => {
                if (!agent?.id) return;
                await onAvatarSelect(url);
                onCancel();
              }}
              className={`relative rounded-full cursor-pointer transition-all duration-300 overflow-hidden border-2 mx-auto ${agent?.avatar === url ? 'scale-110 shadow-lg z-10' : 'border-transparent opacity-70 hover:opacity-100 hover:scale-105'}`}
              style={{ width: 80, height: 80, minWidth: 80, borderColor: agent?.avatar === url ? 'var(--color-brand)' : 'transparent' }}
            >
              <img src={url} className="w-full h-full object-cover" alt="preset" />
              {agent?.avatar === url && (
                <div
                  className="absolute inset-0 flex items-center justify-center"
                  style={{ background: 'rgba(8, 145, 178, 0.10)' }}
                >
                  <div className="bg-white rounded-full p-0.5 shadow-sm">
                    <div className="w-2 h-2 rounded-full" style={{ background: 'var(--color-brand)' }} />
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    </Modal>
  );
}
