// My Archive Page - private file management

const { useState, useEffect, useCallback, useRef } = React;

function MyArchivePage() {
  const { navigate, showToast } = useApp();
  const [activeTab, setActiveTab] = useState('all');
  const [files, setFiles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showUpload, setShowUpload] = useState(false);
  const [uploadType, setUploadType] = useState('document');
  const [uploadName, setUploadName] = useState('');
  const [uploadVisibility, setUploadVisibility] = useState('private');
  const [uploadPassword, setUploadPassword] = useState('');
  const [uploadPrice, setUploadPrice] = useState('');
  const [showActionSheet, setShowActionSheet] = useState(null);
  const [showVisibilitySheet, setShowVisibilitySheet] = useState(null);
  const [visibilityPassword, setVisibilityPassword] = useState('');
  const [visibilityPrice, setVisibilityPrice] = useState('');
  const fileInputRef = React.useRef(null);

  const tabs = [
    { id: 'all', label: '全部文件' },
    { id: 'document', label: '文档' },
    { id: 'image', label: '图片' },
    { id: 'video', label: '视频' },
    { id: 'favorite', label: '收藏' },
  ];

  const loadFiles = useCallback(async (category = 'all') => {
    setLoading(true);
    const query = {};
    if (category && category !== 'all') query.category = category;
    const res = await API.get('/archive/files', query);
    if (res.success) setFiles(res.data || []);
    setLoading(false);
  }, []);

  useEffect(() => {
    loadFiles(activeTab);
  }, [activeTab, loadFiles]);

  const formatSize = (bytes) => {
    if (!bytes) return '0B';
    if (bytes < 1024) return bytes + 'B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB';
    if (bytes < 1024 * 1024 * 1024) return (bytes / 1024 / 1024).toFixed(1) + 'MB';
    return (bytes / 1024 / 1024 / 1024).toFixed(2) + 'GB';
  };

  const getFileIcon = (type) => {
    const map = {
      doc: { icon: '📄', color: '#3B82F6', bg: '#EFF6FF' },
      image: { icon: '🖼️', color: '#10B981', bg: '#ECFDF5' },
      video: { icon: '🎬', color: '#8B5CF6', bg: '#F5F3FF' },
    };
    return map[type] || map.doc;
  };

  const typeNameMap = {
    document: '文档',
    image: '图片',
    video: '视频',
  };

  const handleFileSelect = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    let category = 'document';
    let type = 'doc';
    if (file.type.startsWith('image/')) { category = 'image'; type = 'image'; }
    else if (file.type.startsWith('video/')) { category = 'video'; type = 'video'; }
    else { type = 'doc'; category = 'document'; }
    setUploadType(category);
    setUploadName(file.name);
    handleUpload(file.name, type, category, file.size);
    e.target.value = '';
  };

  const handleUpload = async (name, type, category, size) => {
    const payload = { name, type, category, size, visibility: uploadVisibility };
    if (uploadVisibility === 'password') {
      if (!uploadPassword.trim()) {
        showToast('请设置访问密码');
        return;
      }
      payload.password = uploadPassword.trim();
    }
    if (uploadVisibility === 'paid') {
      const price = parseFloat(uploadPrice);
      if (!price || price <= 0) {
        showToast('请设置有效价格');
        return;
      }
      payload.price = price;
    }
    const res = await API.post('/archive/upload', payload);
    if (res.success) {
      showToast('上传成功');
      setShowUpload(false);
      setUploadName('');
      setUploadPassword('');
      setUploadPrice('');
      setUploadVisibility('private');
      loadFiles(activeTab);
    } else {
      showToast(res.message || '上传失败');
    }
  };

  const handleManualUpload = () => {
    if (!uploadName.trim()) {
      showToast('请输入文件名');
      return;
    }
    const typeMap = { document: 'doc', image: 'image', video: 'video' };
    const sizes = { document: 102400, image: 524288, video: 10485760 };
    handleUpload(
      uploadName.trim(),
      typeMap[uploadType] || 'doc',
      uploadType,
      sizes[uploadType] || 102400
    );
  };

  const handleFavorite = async (file) => {
    const res = await API.post(`/archive/files/${file.id}/favorite`);
    if (res.success) {
      showToast(res.data?.is_favorite ? '已收藏' : '已取消收藏');
      loadFiles(activeTab);
    }
  };

  const handleDelete = async (file) => {
    const res = await API.post(`/archive/files/${file.id}/delete`, {});
    if (res.success) {
      showToast('已删除');
      setShowActionSheet(null);
      loadFiles(activeTab);
    } else {
      showToast(res.message || '删除失败');
    }
  };

  const handleChangeVisibility = async (file, visibility, extra = {}) => {
    const payload = { visibility, ...extra };
    const res = await API.post(`/archive/files/${file.id}/visibility`, payload);
    if (res.success) {
      const label = visibility === 'public' ? '公开' :
        visibility === 'password' ? '密码访问' :
        visibility === 'paid' ? '付费下载' :
        visibility === 'friends' ? '朋友可见' : '私有';
      showToast(`已设为${label}`);
      setShowVisibilitySheet(null);
      setVisibilityPassword('');
      setVisibilityPrice('');
      loadFiles(activeTab);
    } else {
      showToast(res.message || '设置失败');
    }
  };

  const handleOpen = (file) => {
    showToast(`正在打开 ${file.name}`);
    setShowActionSheet(null);
  };

  const handleDownload = (file) => {
    showToast(`正在下载 ${file.name}`);
    setShowActionSheet(null);
  };

  return (
    <PageWrapper>
      {/* Header with back */}
      <div style={{
        background: 'linear-gradient(135deg, #165DFF 0%, #4080FF 100%)',
        padding: '16px 16px 20px',
        color: '#fff',
      }}>
        <div className="flex items-center justify-between">
          <div className="flex items-center" style={{ gap: 12 }}>
            <div
              style={{
                width: 32, height: 32, borderRadius: '50%',
                background: 'rgba(255,255,255,0.2)', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 18,
              }}
              onClick={() => navigate('home')}
            >
              ‹
            </div>
            <div style={{ fontSize: 18, fontWeight: 700 }}>我的存档</div>
          </div>
          <div
            className="flex items-center justify-center"
            style={{
              width: 32, height: 32, borderRadius: '50%',
              background: 'rgba(255,255,255,0.2)', cursor: 'pointer',
              fontSize: 18,
            }}
            onClick={() => setShowUpload(true)}
          >
            <span style={{ lineHeight: 1 }}>+</span>
          </div>
        </div>
        <div style={{ fontSize: 12, opacity: 0.85, marginTop: 4 }}>
          您的云端文件存档空间，永久保存
        </div>
      </div>

      {/* Tabs */}
      <div style={{
        display: 'flex',
        background: 'var(--bg-card)',
        borderBottom: '1px solid var(--border)',
        position: 'sticky',
        top: 0,
        zIndex: 5,
        overflowX: 'auto',
      }}>
        {tabs.map(tab => (
          <div
            key={tab.id}
            style={{
              padding: '12px 16px',
              fontSize: 13,
              color: activeTab === tab.id ? 'var(--primary)' : 'var(--text-secondary)',
              fontWeight: activeTab === tab.id ? 600 : 400,
              borderBottom: activeTab === tab.id ? '2px solid var(--primary)' : '2px solid transparent',
              cursor: 'pointer',
              whiteSpace: 'nowrap',
              flexShrink: 0,
            }}
            onClick={() => setActiveTab(tab.id)}
          >
            {tab.label}
          </div>
        ))}
      </div>

      {/* File List */}
      <div style={{ padding: 12 }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-tertiary)' }}>
            加载中...
          </div>
        ) : files.length === 0 ? (
          <div style={{ padding: '60px 20px', textAlign: 'center', color: 'var(--text-tertiary)' }}>
            <div style={{ fontSize: 48, marginBottom: 12 }}>📁</div>
            <div style={{ fontSize: 14, marginBottom: 4 }}>暂无文件</div>
            <div style={{ fontSize: 12, opacity: 0.7 }}>点击右上角 + 上传文件</div>
          </div>
        ) : (
          files.map(file => {
            const iconInfo = getFileIcon(file.type);
            return (
              <div
                key={file.id}
                className="card card-shadow"
                style={{ marginBottom: 10, padding: 12 }}
              >
                <div className="flex items-center gap-12">
                  <div style={{
                    width: 44, height: 44, borderRadius: 10,
                    background: iconInfo.bg, color: iconInfo.color,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 22, flexShrink: 0,
                  }}>
                    {iconInfo.icon}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontSize: 14, fontWeight: 500,
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                      marginBottom: 4,
                    }}>
                      {file.name}
                      <span style={{
                        fontSize: 10, padding: '1px 6px',
                        background: file.visibility === 'public' ? 'var(--primary-light)' :
                          file.visibility === 'password' ? '#FEF3C7' :
                          file.visibility === 'paid' ? '#FEE2E2' :
                          file.visibility === 'friends' ? '#DBEAFE' :
                          '#E5E7EB',
                        color: file.visibility === 'public' ? 'var(--primary)' :
                          file.visibility === 'password' ? '#D97706' :
                          file.visibility === 'paid' ? '#DC2626' :
                          file.visibility === 'friends' ? '#2563EB' :
                          '#6B7280',
                        borderRadius: 4, marginLeft: 6, verticalAlign: 'middle',
                        fontWeight: file.visibility === 'paid' ? 600 : 400,
                      }}>
                        {file.visibility === 'public' ? '公开' :
                         file.visibility === 'password' ? '🔒 密码' :
                         file.visibility === 'paid' ? `¥${(file.price||0).toFixed(2)} 付费` :
                         file.visibility === 'friends' ? '👥 朋友' : '私有'}
                      </span>
                    </div>
                    <div className="flex items-center gap-12" style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>
                      <span>{typeNameMap[file.category] || file.category}</span>
                      <span>{formatSize(file.size)}</span>
                      <span>{file.upload_time?.slice(0, 16).replace('T', ' ')}</span>
                    </div>
                  </div>
                  <div
                    style={{
                      padding: '6px 10px', cursor: 'pointer',
                      fontSize: 18, color: file.is_favorite ? '#FFB300' : 'var(--text-placeholder)',
                    }}
                    onClick={(e) => { e.stopPropagation(); handleFavorite(file); }}
                  >
                    {file.is_favorite ? '★' : '☆'}
                  </div>
                  <div
                    style={{
                      padding: '6px 10px', cursor: 'pointer',
                      fontSize: 18, color: 'var(--text-secondary)',
                    }}
                    onClick={(e) => { e.stopPropagation(); setShowActionSheet(file); }}
                  >
                    ⋮
                  </div>
                </div>
              </div>
            );
          })
        )}
      </div>

      {/* Upload Sheet */}
      <BottomSheet show={showUpload} onClose={() => setShowUpload(false)} title="上传文件">
        <div style={{ padding: '4px 0 16px' }}>
          {/* Type selector */}
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 8 }}>文件类型</div>
            <div className="flex gap-8">
              {[
                { id: 'document', label: '文档', icon: '📄' },
                { id: 'image', label: '图片', icon: '🖼️' },
                { id: 'video', label: '视频', icon: '🎬' },
              ].map(opt => (
                <div
                  key={opt.id}
                  style={{
                    flex: 1, padding: '12px 8px', textAlign: 'center',
                    borderRadius: 8, cursor: 'pointer',
                    background: uploadType === opt.id ? 'var(--primary-light)' : 'var(--bg-page)',
                    border: uploadType === opt.id ? '1px solid var(--primary)' : '1px solid var(--border)',
                  }}
                  onClick={() => setUploadType(opt.id)}
                >
                  <div style={{ fontSize: 22, marginBottom: 4 }}>{opt.icon}</div>
                  <div style={{ fontSize: 12, color: uploadType === opt.id ? 'var(--primary)' : 'var(--text-secondary)' }}>
                    {opt.label}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Visibility selector */}
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 8 }}>查看权限</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { id: 'private', label: '私有', desc: '仅自己可见，不在广场展示', icon: '🔐' },
                { id: 'friends', label: '朋友可见', desc: '仅互相关注的好友可见', icon: '👥' },
                { id: 'public', label: '公开', desc: '所有人可见，出现在公开广场', icon: '🌍' },
                { id: 'password', label: '密码访问', desc: '广场可见文件名，需密码打开', icon: '🔒' },
                { id: 'paid', label: '付费下载', desc: '广场可见，需支付后下载', icon: '💰' },
              ].map(opt => (
                <div
                  key={opt.id}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '10px 12px', borderRadius: 8, cursor: 'pointer',
                    background: uploadVisibility === opt.id ? 'var(--primary-light)' : 'var(--bg-page)',
                    border: uploadVisibility === opt.id ? '1px solid var(--primary)' : '1px solid var(--border)',
                  }}
                  onClick={() => setUploadVisibility(opt.id)}
                >
                  <div style={{ fontSize: 18 }}>{opt.icon}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-primary)' }}>{opt.label}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>{opt.desc}</div>
                  </div>
                  <div style={{
                    width: 16, height: 16, borderRadius: '50%',
                    border: `2px solid ${uploadVisibility === opt.id ? 'var(--primary)' : 'var(--border)'}`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    {uploadVisibility === opt.id && <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--primary)' }}></div>}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {uploadVisibility === 'password' && (
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 8 }}>设置访问密码</div>
              <input
                className="input"
                type="password"
                placeholder="请输入访问密码"
                value={uploadPassword}
                onChange={(e) => setUploadPassword(e.target.value)}
              />
            </div>
          )}

          {uploadVisibility === 'paid' && (
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 8 }}>设置价格（元）</div>
              <input
                className="input"
                type="number"
                step="0.01"
                min="0.01"
                placeholder="请输入价格，例如 5.00"
                value={uploadPrice}
                onChange={(e) => setUploadPrice(e.target.value)}
              />
            </div>
          )}

          {/* File name input */}
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 8 }}>文件名</div>
            <input
              className="input"
              placeholder="请输入文件名"
              value={uploadName}
              onChange={(e) => setUploadName(e.target.value)}
            />
          </div>

          {/* Real file upload */}
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 8 }}>选择本地文件</div>
            <div
              className="card"
              style={{
                textAlign: 'center', padding: '20px 16px', cursor: 'pointer',
                border: '1px dashed var(--border)', background: 'var(--bg-page)',
              }}
              onClick={() => fileInputRef.current?.click()}
            >
              <div style={{ fontSize: 28, marginBottom: 8 }}>📤</div>
              <div style={{ fontSize: 13, color: 'var(--primary)' }}>点击选择文件</div>
              <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 4 }}>
                支持文档、图片、视频格式
              </div>
            </div>
            <input
              ref={fileInputRef}
              type="file"
              style={{ display: 'none' }}
              onChange={handleFileSelect}
            />
          </div>

          <button
            className="btn btn-primary btn-block"
            onClick={handleManualUpload}
          >
            确认上传
          </button>
        </div>
      </BottomSheet>

      {/* Action Sheet */}
      <BottomSheet
        show={!!showActionSheet}
        onClose={() => setShowActionSheet(null)}
        title={showActionSheet?.name || '文件操作'}
      >
        <div style={{ padding: '4px 0 16px' }}>
          <div
            className="sheet-action"
            onClick={() => handleOpen(showActionSheet)}
          >
            打开文件
          </div>
          <div
            className="sheet-action"
            onClick={() => handleDownload(showActionSheet)}
          >
            下载文件
          </div>
          <div
            className="sheet-action"
            onClick={() => {
              if (showActionSheet) handleFavorite(showActionSheet);
              setShowActionSheet(null);
            }}
          >
            {showActionSheet?.is_favorite ? '取消收藏' : '收藏文件'}
          </div>
          <div
            className="sheet-action"
            onClick={() => {
              setShowVisibilitySheet(showActionSheet);
              setShowActionSheet(null);
              setVisibilityPassword('');
            }}
          >
            修改权限
          </div>
          <div
            className="sheet-action sheet-action-danger"
            onClick={() => handleDelete(showActionSheet)}
          >
            删除文件
          </div>
        </div>
      {/* Visibility Sheet */}
      <BottomSheet
        show={!!showVisibilitySheet}
        onClose={() => { setShowVisibilitySheet(null); setVisibilityPassword(''); }}
        title="修改文件权限"
      >
        <div style={{ padding: '4px 0 16px' }}>
          <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 8, padding: '0 4px' }}>
            {showVisibilitySheet?.name}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
            {[
              { id: 'public', label: '公开', desc: '所有人可见，出现在公开广场', icon: '🌍' },
              { id: 'friends', label: '朋友可见', desc: '仅互相关注的好友可见', icon: '👥' },
              { id: 'password', label: '密码访问', desc: '广场可见文件名，需密码打开', icon: '🔒' },
              { id: 'paid', label: '付费下载', desc: '广场可见，需支付后下载', icon: '💰' },
              { id: 'private', label: '私有', desc: '仅自己可见，不在广场展示', icon: '🔐' },
            ].map(opt => (
              <div
                key={opt.id}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '10px 12px', borderRadius: 8, cursor: 'pointer',
                  background: showVisibilitySheet?.visibility === opt.id ? 'var(--primary-light)' : 'var(--bg-page)',
                  border: showVisibilitySheet?.visibility === opt.id ? '1px solid var(--primary)' : '1px solid var(--border)',
                }}
                onClick={() => {
                  if (opt.id === 'password') {
                    const updated = { ...showVisibilitySheet, visibility: 'password' };
                    setShowVisibilitySheet(updated);
                  } else if (opt.id === 'paid') {
                    const updated = { ...showVisibilitySheet, visibility: 'paid' };
                    setShowVisibilitySheet(updated);
                  } else {
                    handleChangeVisibility(showVisibilitySheet, opt.id);
                  }
                }}
              >
                <div style={{ fontSize: 18 }}>{opt.icon}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-primary)' }}>{opt.label}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>{opt.desc}</div>
                </div>
                <div style={{
                  width: 16, height: 16, borderRadius: '50%',
                  border: `2px solid ${showVisibilitySheet?.visibility === opt.id ? 'var(--primary)' : 'var(--border)'}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {showVisibilitySheet?.visibility === opt.id && <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--primary)' }}></div>}
                </div>
              </div>
            ))}
          </div>
          {showVisibilitySheet?.visibility === 'password' && (
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 8 }}>设置访问密码</div>
              <input
                className="input"
                type="password"
                placeholder="请输入访问密码"
                value={visibilityPassword}
                onChange={(e) => setVisibilityPassword(e.target.value)}
              />
              <button
                className="btn btn-primary btn-block"
                style={{ marginTop: 12 }}
                onClick={() => handleChangeVisibility(showVisibilitySheet, 'password', { password: visibilityPassword })}
              >
                确认设置密码
              </button>
            </div>
          )}
          {showVisibilitySheet?.visibility === 'paid' && (
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 8 }}>设置价格（元）</div>
              <input
                className="input"
                type="number"
                step="0.01"
                min="0.01"
                placeholder="请输入价格，例如 5.00"
                value={visibilityPrice}
                onChange={(e) => setVisibilityPrice(e.target.value)}
              />
              <button
                className="btn btn-primary btn-block"
                style={{ marginTop: 12 }}
                onClick={() => handleChangeVisibility(showVisibilitySheet, 'paid', { price: visibilityPrice })}
              >
                确认设置价格
              </button>
            </div>
          )}
        </div>
      </BottomSheet>
    </PageWrapper>
  );
}

Object.assign(window, { MyArchivePage });
