/**
 * 封面形象库页面
 * ============
 *
 * 管理用户上传的人物照片（抠图后）。
 * 上传图片 → 七牛云 → 火山引擎 MediaKit 抠图 → 保存到本地素材库。
 */

import { useState, useEffect, useRef, useCallback } from 'react';
import { useCoverAvatarStore } from '../../store';
import { usePointStore } from '../../store';
import { toast } from '../../store/uiStore';
import { useProgressStore } from '../../store/progressStore';
import Modal from '../../components/Modal/Modal';
import ConfirmModal from '../../components/Modal/ConfirmModal';
import RechargeModal from '../../components/RechargeModal/RechargeModal';
import './ContentManagement.css';

export default function CoverAvatarLibrary() {
  const [uploadModalOpen, setUploadModalOpen] = useState(false);
  const [uploadName, setUploadName] = useState('');
  const [selectedFile, setSelectedFile] = useState<File | null>(null);

  // 重命名状态
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editingName, setEditingName] = useState('');

  // 删除确认状态
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<{ id: string; name: string } | null>(null);

  // 积分不足弹窗
  const [showPointsModal, setShowPointsModal] = useState(false);
  const showRechargeModal = usePointStore((state) => state.showRechargeModal);
  const setShowRechargeModal = usePointStore((state) => state.setShowRechargeModal);
  const fetchBalance = usePointStore((state) => state.fetchBalance);

  const fileInputRef = useRef<HTMLInputElement>(null);

  const {
    coverAvatars,
    isLoading,
    loadCoverAvatars,
    addCoverAvatar,
    renameCoverAvatar,
    deleteCoverAvatar,
  } = useCoverAvatarStore();

  // 加载数据
  useEffect(() => {
    loadCoverAvatars();
  }, [loadCoverAvatars]);

  // 图片文件验证
  const validateImageFile = (file: File): { valid: boolean; error?: string } => {
    const maxSize = 20 * 1024 * 1024; // 20MB
    if (file.size > maxSize) {
      return { valid: false, error: `文件大小 ${(file.size / 1024 / 1024).toFixed(1)}MB，要求不超过 20MB` };
    }

    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    if (!allowedTypes.includes(file.type)) {
      return { valid: false, error: '仅支持 JPG、PNG、GIF、WebP 格式' };
    }

    return { valid: true };
  };

  // 文件选择
  const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) {return;}

    const validation = validateImageFile(file);
    if (!validation.valid) {
      toast.error(validation.error || '文件验证失败');
      e.target.value = '';
      return;
    }

    setSelectedFile(file);
    // 默认使用文件名（不含扩展名）作为名称
    if (!uploadName.trim()) {
      const nameWithoutExt = file.name.replace(/\.[^/.]+$/, '');
      setUploadName(nameWithoutExt);
    }
  }, [uploadName]);

  // 重置弹窗状态
  const resetUploadModal = useCallback(() => {
    setUploadModalOpen(false);
    setUploadName('');
    setSelectedFile(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  }, []);

  // 上传处理
  const handleUpload = useCallback(async () => {
    if (!uploadName.trim() || !selectedFile) {return;}

    // 前置积分检查
    await fetchBalance();
    const coverAvatarPoints = usePointStore.getState().getRule('cover_avatar')?.points || 10;
    const balance = usePointStore.getState().balance;
    if (balance < coverAvatarPoints) {
      setShowPointsModal(true);
      return;
    }

    const progress = useProgressStore.getState();
    setUploadModalOpen(false);

    progress.show('上传封面形象');
    try {
      progress.update('正在上传并抠图...');
      const avatar = await addCoverAvatar(selectedFile, uploadName.trim());
      progress.success('封面形象保存成功', 200);
      toast.success(`「${avatar.name}」已保存`);
    } catch (err) {
      const msg = err instanceof Error ? err.message : '上传失败';
      progress.error(msg);
      toast.error(msg);
    }

    setUploadName('');
    setSelectedFile(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  }, [uploadName, selectedFile, addCoverAvatar, fetchBalance]);

  // 删除处理
  const openDeleteModal = (id: string, name: string) => {
    setDeleteTarget({ id, name });
    setDeleteModalOpen(true);
  };

  const handleConfirmDelete = useCallback(async () => {
    if (!deleteTarget) {return;}
    try {
      await deleteCoverAvatar(deleteTarget.id);
      toast.success('已删除');
    } catch {
      toast.error('删除失败');
    } finally {
      setDeleteModalOpen(false);
      setDeleteTarget(null);
    }
  }, [deleteTarget, deleteCoverAvatar]);

  // 重命名
  const startRename = (id: string, currentName: string) => {
    setEditingId(id);
    setEditingName(currentName);
  };

  const cancelRename = () => {
    setEditingId(null);
    setEditingName('');
  };

  const confirmRename = useCallback(async () => {
    if (!editingId || !editingName.trim()) {
      cancelRename();
      return;
    }
    try {
      await renameCoverAvatar(editingId, editingName.trim());
      setEditingId(null);
      setEditingName('');
    } catch {
      toast.error('重命名失败');
    }
  }, [editingId, editingName, renameCoverAvatar]);

  return (
    <div className="content-page">
      {/* 页面标题和上传区域 */}
      <div className="voice-clone-wrapper">
        <div className="voice-clone-title-group">
          <h2>封面形象</h2>
          <p className="voice-clone-desc">上传人物照片，AI 自动抠图，用于封面设计叠加</p>
        </div>

        {/* 上传引导卡片 */}
        <div
          className="voice-upload-card"
          onClick={() => setUploadModalOpen(true)}
        >
          <div className="voice-upload-icon">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
              <circle cx="8.5" cy="8.5" r="1.5" />
              <polyline points="21 15 16 10 5 21" />
            </svg>
          </div>
          <div className="voice-upload-text">
            <span className="voice-upload-title">上传人物照片</span>
            <span className="voice-upload-hint">JPG / PNG / GIF / WebP，建议半身或全身照</span>
          </div>
          <div className="voice-upload-arrow">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <line x1="12" y1="19" x2="12" y2="5" />
              <polyline points="5 12 12 5 19 12" />
            </svg>
          </div>
        </div>
      </div>

      {/* 上传弹窗 */}
      <Modal
        open={uploadModalOpen}
        onClose={resetUploadModal}
        title=""
        width="480px"
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <label style={{ fontSize: 'var(--font-sm)', fontWeight: 500, marginBottom: 8, display: 'block' }}>
              形象名称
            </label>
            <input
              type="text"
              className="input"
              placeholder="例如：我的形象"
              value={uploadName}
              onChange={e => setUploadName(e.target.value)}
              style={{ width: '100%' }}
            />
          </div>

          <div>
            <label style={{ fontSize: 'var(--font-sm)', fontWeight: 500, marginBottom: 8, display: 'block' }}>
              选择图片
            </label>
            <div
              style={{
                border: '2px dashed var(--border-color)',
                borderRadius: 'var(--radius-md)',
                padding: 'var(--spacing-xl)',
                textAlign: 'center',
                cursor: 'pointer',
                transition: 'all var(--transition-fast)',
              }}
              onClick={() => fileInputRef.current?.click()}
              onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--primary)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-color)'; }}
            >
              <input
                ref={fileInputRef}
                type="file"
                accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                onChange={handleFileSelect}
                style={{ display: 'none' }}
              />
              {selectedFile ? (
                <div>
                  <div style={{ fontWeight: 500, fontSize: 'var(--font-sm)' }}>{selectedFile.name}</div>
                  <div style={{ fontSize: 'var(--font-xs)', color: 'var(--text-secondary)', marginTop: 4 }}>
                    {(selectedFile.size / 1024 / 1024).toFixed(2)} MB
                  </div>
                </div>
              ) : (
                <div style={{ color: 'var(--text-secondary)' }}>
                  <div style={{ fontSize: 'var(--font-sm)' }}>点击选择图片</div>
                  <div style={{ fontSize: 'var(--font-xs)', marginTop: 6, lineHeight: 1.6 }}>
                    支持 JPG / PNG / GIF / WebP，不超过 20MB
                  </div>
                </div>
              )}
            </div>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontSize: 'var(--font-xs)', color: 'var(--text-tertiary)' }}>
              每次上传消耗 <strong style={{ color: 'var(--primary)' }}>10</strong> 积分
            </span>
            <div style={{ display: 'flex', gap: 12 }}>
              <button className="btn btn-secondary" onClick={resetUploadModal}>取消</button>
              <button
                className="btn btn-primary"
                onClick={handleUpload}
                disabled={!uploadName.trim() || !selectedFile}
              >
                上传并抠图
              </button>
            </div>
          </div>
        </div>
      </Modal>

      {/* 封面形象列表 */}
      {isLoading ? (
        <p style={{ color: 'var(--text-secondary)' }}>加载中...</p>
      ) : coverAvatars.length === 0 ? (
        <div className="empty-state-page">
          <div className="empty-state-icon">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
              <circle cx="8.5" cy="8.5" r="1.5" />
              <polyline points="21 15 16 10 5 21" />
            </svg>
          </div>
          <p className="empty-state-title">暂无封面形象</p>
          <p className="empty-state-desc">上传一张人物照片，<br />AI 将自动抠图生成透明背景形象</p>
        </div>
      ) : (
        <div className="cover-avatar-grid">
          {coverAvatars.map(a => (
            <div key={a.id} className="works-card">
              {/* 图片预览 */}
              <div className="works-card-cover">
                <img
                  src={a.imageUrl}
                  alt={a.name}
                  className="works-card-poster"
                  loading="lazy"
                />
                {/* 悬停操作按钮 */}
                <div className="works-card-overlay" onClick={(e) => e.stopPropagation()}>
                  <button
                    className="works-card-action"
                    onClick={() => startRename(a.id, a.name)}
                    title="重命名"
                  >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z" /></svg>
                  </button>
                  <button
                    className="works-card-action delete"
                    onClick={() => openDeleteModal(a.id, a.name)}
                    title="删除"
                  >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="3 6 5 6 21 6" /><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2" /></svg>
                  </button>
                </div>
              </div>
              {/* 名称 */}
              <div className="works-card-info">
                {editingId === a.id ? (
                  <input
                    type="text"
                    className="works-card-rename-input"
                    value={editingName}
                    onChange={e => setEditingName(e.target.value)}
                    onKeyDown={e => {
                      if (e.key === 'Enter') {confirmRename();}
                      if (e.key === 'Escape') {cancelRename();}
                    }}
                    onBlur={confirmRename}
                    autoFocus
                  />
                ) : (
                  <div className="works-card-name" title={a.name}>{a.name}</div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 删除确认弹窗 */}
      <ConfirmModal
        open={deleteModalOpen}
        type="danger"
        title={<>确认删除形象 <strong>「{deleteTarget?.name}」</strong> 吗？</>}
        description="此操作不可撤销，形象将被永久删除"
        confirmText="确认删除"
        cancelText="取消"
        confirmButtonType="danger"
        onConfirm={handleConfirmDelete}
        onCancel={() => { setDeleteModalOpen(false); setDeleteTarget(null); }}
      />

      {/* 积分不足弹窗 */}
      <ConfirmModal
        open={showPointsModal}
        type="warning"
        title="积分不足"
        description={`每次上传封面形象消耗 10 积分，当前余额不足。请先充值后再尝试。`}
        confirmText="立即充值"
        cancelText="稍后再说"
        confirmButtonType="danger"
        onConfirm={() => { setShowPointsModal(false); setShowRechargeModal(true); }}
        onCancel={() => setShowPointsModal(false)}
        onClose={() => setShowPointsModal(false)}
      />
      <RechargeModal
        open={showRechargeModal}
        onClose={() => setShowRechargeModal(false)}
        onRechargeSuccess={() => { fetchBalance(); setShowPointsModal(false); }}
      />
    </div>
  );
}
