import { ExpenseProvisionCard, ExpenseProvisionCreate } from '@/components';
import { BankOutlined, PlusOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import {
	Button,
	Collapse,
	Divider,
	Empty,
	Space,
	Statistic,
	Typography,
} from 'antd';
import { useState } from 'react';

const { Text } = Typography;

interface IExpenseProvisionListProps {
	expenseRecord?: BusinessAPI.ExpenseRecordVO;
	onChange?: (expenseRecord: BusinessAPI.ExpenseRecordVO) => void;
}

export default function ExpenseProvisionList(
	props: IExpenseProvisionListProps,
) {
	const { expenseRecord, onChange } = props;

	// 按 dealerName 分组
	const groupByDealer = (provisions?: BusinessAPI.ExpenseProvision[]) => {
		if (!provisions || provisions.length === 0) return {};

		return provisions.reduce(
			(groups, item) => {
				const dealerName = item.dealerName || '未分组客户';
				if (!groups[dealerName]) {
					groups[dealerName] = [];
				}
				groups[dealerName].push(item);
				return groups;
			},
			{} as Record<string, BusinessAPI.ExpenseProvision[]>,
		);
	};

	// 获取分组后的数据
	const dealerGroups = expenseRecord
		? groupByDealer(expenseRecord.expenseProvisionList)
		: {};

	// 计算每个客户的总计
	const getDealerTotal = (vehicles: BusinessAPI.ExpenseProvision[]) => {
		return vehicles.reduce((sum, item) => sum + item.provisionAmount, 0);
	};

	const [visible, setVisible] = useState(false);

	// 管理每个客户分组的展开状态
	const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());

	// 折叠面板配置
	const collapseItems = Object.entries(dealerGroups).map(
		([dealerName, expenseProvisions]) => {
			const dealerTotal = getDealerTotal(expenseProvisions);

			return {
				key: dealerName,
				label: (
					<div
						style={{
							display: 'flex',
							justifyContent: 'space-between',
							alignItems: 'center',
							width: '100%',
						}}
					>
						<Space>
							<div
								style={{
									display: 'flex',
									alignItems: 'center',
									justifyContent: 'center',
									width: '32px',
									height: '32px',
									borderRadius: '50%',
									background: 'rgba(24, 144, 255, 0.1)',
									color: '#1890ff',
								}}
							>
								<BankOutlined />
							</div>
							<div>
								<div style={{ fontSize: '14px', fontWeight: 500 }}>
									{dealerName} ({expenseProvisions.length}车)
								</div>
								<Text type="secondary" style={{ fontSize: '12px' }}>
									总计提: {dealerTotal.toLocaleString()}元
								</Text>
							</div>
						</Space>
					</div>
				),
				children: (
					<div
						style={{
							background: '#fafafa',
							padding: '12px',
							borderRadius: '6px',
						}}
					>
						<div style={{ marginBottom: '12px' }}>
							<Text
								type="secondary"
								style={{
									fontSize: '12px',
									marginBottom: '8px',
									display: 'block',
								}}
							>
								车次明细:
							</Text>
							{expenseProvisions.map((expenseProvision, index) => (
								<ExpenseProvisionCard
									key={expenseProvision.expenseProvisionId}
									expenseProvision={expenseProvision}
									onUpdate={(updatedProvision) => {
										onChange?.({
											...expenseRecord!,
											expenseProvisionList: expenseProvisions.map((item) =>
												item.expenseProvisionId ===
												updatedProvision.expenseProvisionId
													? updatedProvision
													: item,
											),
										});
									}}
									onDelete={() => {
										onChange?.({
											...expenseRecord!,
											expenseProvisionList: expenseProvisions.filter(
												(item) =>
													item.expenseProvisionId !==
													expenseProvision.expenseProvisionId,
											),
										});
									}}
									index={index}
								/>
							))}
						</div>
						<Divider style={{ margin: '12px 0' }} />
						<Space direction="vertical" size={0}>
							<Text type="secondary" style={{ fontSize: '12px' }}>
								该客户合计:
							</Text>
							<Text strong style={{ color: '#1890ff', fontSize: '16px' }}>
								{dealerTotal.toLocaleString()}元
							</Text>
						</Space>
					</div>
				),
			};
		},
	);

	return (
		<ProCard
			style={{ marginBottom: '12px' }}
			title={'计提汇总'}
			extra={
				<Button
					type="primary"
					size="middle"
					block
					icon={<PlusOutlined />}
					onClick={() => setVisible(true)}
				>
					添加计提车次
				</Button>
			}
		>
			{expenseRecord?.expenseProvisionList?.length === 0 ? (
				<Empty
					description="暂无计提数据"
					image={Empty.PRESENTED_IMAGE_SIMPLE}
				/>
			) : (
				<Collapse
					expandIconPosition="end"
					items={collapseItems}
					ghost
					activeKey={Array.from(expandedGroups)}
					onChange={(keys) => {
						setExpandedGroups(new Set(keys as string[]));
					}}
				/>
			)}

			<Divider />

			{/* 总计区域 */}
			<Statistic
				title="计提总金额"
				value={expenseRecord?.totalProvision || 0}
				precision={2}
				prefix="¥"
				valueStyle={{ color: '#1890ff', fontSize: '20px', fontWeight: 600 }}
			/>

			<Divider />

			<ExpenseProvisionCreate
				visible={visible}
				onClose={() => setVisible(false)}
				onFinish={(expenseProvision) => {
					onChange?.({
						...expenseRecord!,
						expenseProvisionList: [
							...(expenseRecord?.expenseProvisionList || []),
							expenseProvision,
						],
					});
				}}
			/>
		</ProCard>
	);
}
