import { CategoryTree, MaterialList } from '@/components';
import { business } from '@/services';
import { formatParam } from '@/utils/formatParam';
import { pagination } from '@/utils/pagination';
import {
	ActionType,
	ProColumns,
	ProTable,
	ProTableProps,
} from '@ant-design/pro-components';
import { Button, Image, message, Modal, ModalProps, Segmented } from 'antd';
import React, { useRef, useState } from 'react';
import useStyle from './style.style';

export interface MaterialLibraryModalProps extends ModalProps {
	/** 最大选择数量，默认 1 */
	maxCount?: number;
	/** 选择模式: radio-单选, checkbox-多选 */
	mode?: 'radio' | 'checkbox';
	/** 确认选择回调 */
	onFinish?: (materials: BusinessAPI.MaterialVO[]) => void;
	/** 初始已选中的素材列表 */
	initialSelectedMaterials?: BusinessAPI.MaterialVO[];
	/** 素材类型筛选: FILE_IMAGE-图片, FILE_VIDEO-视频 */
	materialType?: 'FILE_IMAGE' | 'FILE_VIDEO';
}

const MaterialLibraryModal: React.FC<MaterialLibraryModalProps> = ({
	open,
	onCancel,
	maxCount = 1,
	mode = 'radio',
	onFinish,
	initialSelectedMaterials = [],
	materialType,
	...rest
}) => {
	const { styles } = useStyle();
	const [selectedCategoryId, setSelectedCategoryId] = useState<
		string | undefined
	>();
	const [selectedCategoryName, setSelectedCategoryName] = useState<
		string | undefined
	>();
	const [selectedMaterials, setSelectedMaterials] = useState<
		BusinessAPI.MaterialVO[]
	>(initialSelectedMaterials);
	const [viewMode, setViewMode] = useState<'list' | 'image'>('image');
	const [materials, setMaterials] = useState<BusinessAPI.MaterialVO[]>([]);
	const actionRef = useRef<ActionType>();

	// 列表模式列配置
	const columns: ProColumns<BusinessAPI.MaterialVO>[] = [
		{
			title: '素材名称',
			dataIndex: 'name',
			ellipsis: true,
		},
		{
			title: '素材内容',
			dataIndex: 'url',
			render: (_, record) => {
				if (record.type === 'FILE_IMAGE' || record.type === 'FILE_VIDEO') {
					return (
						<Image
							width={40}
							height={40}
							src={record.url}
							style={{ objectFit: 'cover', borderRadius: 4 }}
							preview={{ src: record.url }}
						/>
					);
				}
				return '-';
			},
		},
		{
			title: '素材分类',
			dataIndex: ['categoryVO', 'name'],
		},
		{
			title: '创建时间',
			dataIndex: 'createdAt',
			valueType: 'dateTime',
		},
	];

	// 处理分类选择
	const handleCategorySelect = (categoryId?: string, categoryName?: string) => {
		setSelectedCategoryId(categoryId);
		setSelectedCategoryName(categoryName);
		// 刷新素材列表
		actionRef.current?.reload();
	};

	// 处理素材选择
	const handleMaterialSelect = (material: BusinessAPI.MaterialVO) => {
		const isSelected = selectedMaterials.some(
			(m) => m.materialId === material.materialId,
		);

		if (isSelected) {
			// 取消选择
			setSelectedMaterials((prev) =>
				prev.filter((m) => m.materialId !== material.materialId),
			);
		} else {
			// 选择素材
			if (mode === 'radio') {
				// 单选模式直接替换
				setSelectedMaterials([material]);
			} else {
				// 多选模式检查数量限制
				if (maxCount > 0 && selectedMaterials.length >= maxCount) {
					message.warning(`最多只能选择 ${maxCount} 个素材`);
					return;
				}
				setSelectedMaterials((prev) => [...prev, material]);
			}
		}
	};

	// 确认选择
	const handleOk = () => {
		if (selectedMaterials.length === 0 && maxCount > 0) {
			message.warning('请先选择素材');
			return;
		}
		onFinish?.(selectedMaterials);
		// 重置状态
		setSelectedMaterials([]);
		setSelectedCategoryId(undefined);
		setSelectedCategoryName(undefined);
	};

	// 关闭弹窗
	const handleClose = () => {
		setSelectedMaterials([]);
		setSelectedCategoryId(undefined);
		setSelectedCategoryName(undefined);
		onCancel?.({} as any);
	};

	// 图片预览渲染
	const renderImagePreview = () => {
		if (materials.length === 0) {
			return (
				<div className={styles.emptyTip}>
					<span>暂无素材，请选择其他分类或添加素材</span>
				</div>
			);
		}

		return (
			<div className={styles.imagePreview}>
				{materials.map((material) => {
					const isSelected = selectedMaterials.some(
						(m) => m.materialId === material.materialId,
					);
					return (
						<div
							key={material.materialId}
							className={`${styles.imageItem} ${isSelected ? styles.imageItemSelected : ''}`}
							onClick={() => handleMaterialSelect(material)}
						>
							<div className={styles.imageWrapper}>
								<Image
									src={material.url}
									alt={material.name}
									preview={{ src: material.url }}
									placeholder={
										<div className={styles.imagePlaceholder}>加载中...</div>
									}
								/>
							</div>
							<div className={styles.imageInfo}>
								<div className={styles.imageName}>{material.name}</div>
							</div>
							{isSelected && (
								<div className={styles.imageSelectedCheck}>
									{mode === 'radio'
										? '✓'
										: `${
												selectedMaterials.findIndex(
													(m) => m.materialId === material.materialId,
												) + 1
											}`}
								</div>
							)}
						</div>
					);
				})}
			</div>
		);
	};

	// 请求参数
	const request: ProTableProps<
		BusinessAPI.MaterialVO,
		BusinessAPI.MaterialPageQry
	>['request'] = async (params, sorter, filter) => {
		const searchParams: BusinessAPI.MaterialPageQry = {
			...formatParam<typeof params>(params, sorter, filter),
			categoryId: selectedCategoryId,
			type: materialType,
		};

		const { data, success, totalCount } = await business.material.pageMaterial({
			materialPageQry: searchParams,
		});

		// 保存素材数据用于图片预览
		if (data) {
			setMaterials(data as BusinessAPI.MaterialVO[]);
		}

		return {
			data: data || [],
			total: totalCount,
			success,
		};
	};

	return (
		<Modal
			title="素材库"
			open={open}
			onOk={handleOk}
			onCancel={handleClose}
			width={1200}
			destroyOnHidden
			{...rest}
			className={styles.materialModal}
		>
			<ProTable<BusinessAPI.MaterialVO, BusinessAPI.MaterialPageQry>
				actionRef={actionRef}
				rowKey="materialId"
				bordered={true}
				columns={columns}
				request={request}
				search={false}
				pagination={pagination()}
				size="small"
				className={styles.materialTable}
				rowClassName={(record) => {
					const isSelected = selectedMaterials.some(
						(m) => m.materialId === record.materialId,
					);
					return isSelected ? styles.rowSelected : '';
				}}
				onRow={(record) => ({
					onClick: () => handleMaterialSelect(record),
					style: { cursor: 'pointer' },
				})}
				toolBarRender={false}
				tableRender={(props, defaultDom, domList) => {
					return (
						<div className={styles.modalContent}>
							{/* 左侧分类树 */}
							<div className={styles.leftPanel}>
								<CategoryTree
									onCategorySelect={handleCategorySelect}
									selectedCategoryId={selectedCategoryId}
								/>
							</div>

							{/* 右侧素材内容 */}
							<div className={styles.rightPanel}>
								{/* 顶部工具栏 */}
								<div className={styles.toolbar}>
									<div className={styles.toolbarLeft}>
										<Segmented
											value={viewMode}
											onChange={(value) =>
												setViewMode(value as 'list' | 'image')
											}
											options={[
												{ label: '图片', value: 'image' },
												{ label: '列表', value: 'list' },
											]}
										/>
										{selectedCategoryName && (
											<span className={styles.currentCategory}>
												当前分类: <strong>{selectedCategoryName}</strong>
											</span>
										)}
									</div>
									<div className={styles.toolbarRight}>
										<MaterialList
											formType={'modal'}
											key={'create'}
											ghost={true}
											mode={'create'}
											search={false}
											onValueChange={() => actionRef.current?.reload()}
										/>
										{selectedMaterials.length > 0 && (
											<span className={styles.selectedCount}>
												已选择 {selectedMaterials.length}
												{maxCount > 0 && `/${maxCount}`} 个
											</span>
										)}
										{selectedMaterials.length > 0 && mode === 'checkbox' && (
											<Button
												size="small"
												onClick={() => setSelectedMaterials([])}
											>
												清空
											</Button>
										)}
									</div>
								</div>

								{/* 素材展示区域 */}
								<div className={styles.materialArea}>
									{viewMode === 'list' ? (
										defaultDom
									) : (
										<div className={styles.imageGridWrapper}>
											{renderImagePreview()}
											<div className={styles.paginationWrapper}>
												{domList.table}
											</div>
										</div>
									)}
								</div>
							</div>
						</div>
					);
				}}
			/>
		</Modal>
	);
};

export default MaterialLibraryModal;
