import { useState } from 'react';
import { Drawer, Input, Select, Space, Upload, Button, Switch, message } from 'antd';
import { UploadOutlined, PictureOutlined } from '@ant-design/icons';
import type { ArticleTagItem } from '../../../api/health/articles';
import { uploadFile } from '../../../api/upload';
import MediaPicker from '../../../components/MediaPicker';

interface ArticleSettingsDrawerProps {
  open: boolean;
  onClose: () => void;
  isDark: boolean;
  summary: string;
  onSummaryChange: (v: string) => void;
  coverImage: string;
  onCoverImageChange: (v: string) => void;
  categoryId: string | undefined;
  onCategoryChange: (v: string | undefined) => void;
  selectedTagIds: string[];
  onTagIdsChange: (v: string[]) => void;
  slug: string;
  onSlugChange: (v: string) => void;
  sortOrder: number;
  onSortOrderChange: (v: number) => void;
  isPublic: boolean;
  onIsPublicChange: (v: boolean) => void;
  categories: { id: string; name: string }[];
  tags: ArticleTagItem[];
}

const labelStyle = (isDark: boolean) => ({
  display: 'block',
  fontSize: 13,
  fontWeight: 500 as const,
  marginBottom: 6,
  color: isDark ? '#94a3b8' : '#475569',
});

/**
 * 文章设置抽屉
 * 从原右侧面板迁移，包含分类、标签、摘要、封面图、Slug、排序等设置。
 */
export default function ArticleSettingsDrawer({
  open,
  onClose,
  isDark,
  summary,
  onSummaryChange,
  coverImage,
  onCoverImageChange,
  categoryId,
  onCategoryChange,
  selectedTagIds,
  onTagIdsChange,
  slug,
  onSlugChange,
  sortOrder,
  onSortOrderChange,
  isPublic,
  onIsPublicChange,
  categories,
  tags,
}: ArticleSettingsDrawerProps) {
  const [mediaPickerOpen, setMediaPickerOpen] = useState(false);

  return (
    <>
      <Drawer
        title="文章设置"
        placement="right"
        width={360}
        open={open}
        onClose={onClose}
        styles={{
          body: { padding: '16px 20px' },
          header: {
            background: isDark ? '#0f172a' : undefined,
            borderBottom: `1px solid ${isDark ? '#1e293b' : '#f0f0f0'}`,
          },
        }}
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* 分类 */}
          <div>
            <label style={labelStyle(isDark)}>分类</label>
            <Select
              value={categoryId}
              onChange={onCategoryChange}
              placeholder="选择分类"
              allowClear
              style={{ width: '100%' }}
              options={categories.map((c) => ({ label: c.name, value: c.id }))}
            />
          </div>

          {/* 标签 */}
          <div>
            <label style={labelStyle(isDark)}>标签</label>
            <Select
              mode="multiple"
              value={selectedTagIds}
              onChange={onTagIdsChange}
              placeholder="选择标签"
              allowClear
              style={{ width: '100%' }}
              options={tags.map((t) => ({ label: t.name, value: t.id }))}
              maxTagCount={5}
            />
          </div>

          {/* 摘要 */}
          <div>
            <label style={labelStyle(isDark)}>摘要</label>
            <Input.TextArea
              value={summary}
              onChange={(e) => onSummaryChange(e.target.value)}
              placeholder="请输入文章摘要"
              rows={3}
              maxLength={500}
              showCount
            />
          </div>

          {/* 封面图 */}
          <div>
            <label style={labelStyle(isDark)}>封面图</label>
            <Space.Compact style={{ width: '100%' }}>
              <Input
                value={coverImage}
                onChange={(e) => onCoverImageChange(e.target.value)}
                placeholder="输入 URL 或上传文件"
                style={{ flex: 1 }}
              />
              <Button
                icon={<PictureOutlined />}
                onClick={() => setMediaPickerOpen(true)}
              >
                媒体库
              </Button>
              <Upload
                accept="image/*"
                showUploadList={false}
                beforeUpload={async (file) => {
                  try {
                    const result = await uploadFile(file);
                    onCoverImageChange(result.url);
                    message.success('封面图上传成功');
                  } catch {
                    message.error('封面图上传失败');
                  }
                  return false;
                }}
              >
                <Button icon={<UploadOutlined />}>上传</Button>
              </Upload>
            </Space.Compact>
            {coverImage && (
              <div
                style={{
                  marginTop: 8,
                  borderRadius: 8,
                  overflow: 'hidden',
                  border: `1px solid ${isDark ? '#1e293b' : '#e2e8f0'}`,
                }}
              >
                <img
                  src={coverImage}
                  alt="封面预览"
                  style={{ width: '100%', height: 120, objectFit: 'cover' }}
                  onError={(e) => {
                    (e.target as HTMLImageElement).style.display = 'none';
                  }}
                />
              </div>
            )}
          </div>

          {/* Slug */}
          <div>
            <label style={labelStyle(isDark)}>URL 别名 (Slug)</label>
            <Input
              value={slug}
              onChange={(e) => onSlugChange(e.target.value)}
              placeholder="例如: health-tips-for-elderly"
            />
          </div>

          {/* 排序 */}
          <div>
            <label style={labelStyle(isDark)}>排序</label>
            <Input
              type="number"
              value={sortOrder}
              onChange={(e) => onSortOrderChange(Number(e.target.value))}
              placeholder="0"
            />
          </div>

          {/* 公开可见 */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <label style={{ ...labelStyle(isDark), marginBottom: 2 }}>公开可见</label>
              <div style={{ fontSize: 12, color: isDark ? '#64748b' : '#94a3b8' }}>
                开启后游客可在小程序查看此文章
              </div>
            </div>
            <Switch checked={isPublic} onChange={onIsPublicChange} />
          </div>
        </div>
      </Drawer>

      <MediaPicker
        open={mediaPickerOpen}
        onClose={() => setMediaPickerOpen(false)}
        onSelect={(url) => {
          onCoverImageChange(url);
          message.success('已选择封面图');
        }}
      />
    </>
  );
}
