'use client';

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlus } from '@fortawesome/free-solid-svg-icons';
import { Checkbox } from '@/components/ui/checkbox';
import type { RankConfigItem } from '@/types/response/donation/rankConfig';
import { PER_PAGE_OPTIONS } from '@/constants/donation';
import { RANK_PERIODS, RANK_THEMES } from '../constants';

type Props = {
	items: RankConfigItem[];
	loading: boolean;
	saving: boolean;
	checkedIDs: Set<number>;
	setCheckedIDs: React.Dispatch<React.SetStateAction<Set<number>>>;
	page: number;
	setPage: React.Dispatch<React.SetStateAction<number>>;
	perPage: number;
	setPerPage: React.Dispatch<React.SetStateAction<number>>;
	onNew: () => void;
	onEdit: (item: RankConfigItem) => void;
	onBatchDelete: () => void;
};

export default function RankListPanel({
	items,
	loading,
	saving,
	checkedIDs,
	setCheckedIDs,
	page,
	setPage,
	perPage,
	setPerPage,
	onNew,
	onEdit,
	onBatchDelete
}: Props) {
	// ── 페이징 ───────────────────────────────────────
	const totalPages = Math.max(1, Math.ceil(items.length / perPage));
	const pagedItems = items.slice((page - 1) * perPage, page * perPage);

	const handlePerPageChange = (value: number) => {
		setPerPage(value);
		setPage(1);
	};

	// ── 전체선택 ─────────────────────────────────────
	const visibleIDs = pagedItems.map(i => i.id);
	const checkedCount = visibleIDs.filter(id => checkedIDs.has(id)).length;
	const allChecked = pagedItems.length > 0 && checkedCount === visibleIDs.length;
	const isIndeterminate = checkedCount > 0 && checkedCount < visibleIDs.length;

	const handleSelectAll = () => {
		setCheckedIDs(prev => {
			const next = new Set(prev);
			if (allChecked) {
				visibleIDs.forEach(id => next.delete(id));
			} else {
				visibleIDs.forEach(id => next.add(id));
			}
			return next;
		});
	};

	const handleToggleCheck = (id: number) => {
		setCheckedIDs(prev => {
			const next = new Set(prev);
			if (next.has(id)) {
				next.delete(id);
			} else {
				next.add(id);
			}
			return next;
		});
	};

	return (
		<div className="rank-config__list-panel">
			<div className="rank-config__toolbar">
				<div className="rank-config__toolbar-left">
					<span className="rank-config__count">총 {items.length}개</span>
					{checkedIDs.size > 0 && (
						<span className="rank-config__count">({checkedIDs.size}개 선택)</span>
					)}
				</div>
				<div className="rank-config__toolbar-right">
					<select
						value={perPage}
						onChange={e => handlePerPageChange(Number(e.target.value))}
						className="rank-config__per-page"
						title="보여질 개수"
					>
						{PER_PAGE_OPTIONS.map(n => (
							<option key={n} value={n}>{n}개씩</option>
						))}
					</select>
					<button type="button" className="rank-config__btn" onClick={onNew}>
						<FontAwesomeIcon icon={faPlus} />
						추가
					</button>
					<button
						type="button"
						className="rank-config__btn rank-config__btn--danger"
						onClick={onBatchDelete}
						disabled={checkedIDs.size === 0 || saving}
					>
						삭제
					</button>
				</div>
			</div>

			<div className="rank-config__table-wrap">
				{loading ? (
					<div className="rank-config__empty">준비 중...</div>
				) : items.length === 0 ? (
					<div className="rank-config__empty">등록된 순위 설정이 없습니다.</div>
				) : (
					<table className="rank-config__table">
						<thead>
							<tr>
								<th className="rank-config__th--check">
									<Checkbox
										checked={allChecked} indeterminate={isIndeterminate}
										onCheckedChange={handleSelectAll}
										aria-label="전체선택"
									/>
								</th>
								<th>제목</th>
								<th>기간</th>
								<th>테마</th>
								<th>최대인원</th>
								<th>금액표시</th>
								<th>활성</th>
								<th>비고</th>
							</tr>
						</thead>
						<tbody>
							{pagedItems.map(item => {
								const isChecked = checkedIDs.has(item.id);
								return (
									<tr
										key={item.id}
										className={isChecked ? 'rank-config__row--checked' : ''}
									>
										<td className="rank-config__td--check">
											<Checkbox
												checked={isChecked}
												onCheckedChange={() => handleToggleCheck(item.id)}
												aria-label={`${item.id} 선택`}
											/>
										</td>
										<td>{item.title}</td>
										<td>{RANK_PERIODS.find(p => p.value === item.period)?.label ?? item.period}</td>
										<td>{RANK_THEMES.find(t => t.value === item.theme)?.label ?? item.theme}</td>
										<td>{item.maxRankCount}명</td>
										<td>
											<span className={`rank-config__status-badge rank-config__status-badge--${item.isShowAmount ? 'active' : 'inactive'}`}>
												{item.isShowAmount ? '표시' : '숨김'}
											</span>
										</td>
										<td>
											<span className={`rank-config__status-badge rank-config__status-badge--${item.isActive ? 'active' : 'inactive'}`}>
												{item.isActive ? '활성' : '비활성'}
											</span>
										</td>
										<td>
											<button
												type="button"
												className="rank-config__btn rank-config__btn--sm"
												onClick={() => onEdit(item)}
												disabled={isChecked}
											>
												수정
											</button>
										</td>
									</tr>
								);
							})}
						</tbody>
					</table>
				)}
			</div>

			{totalPages > 1 && (
				<div className="rank-config__pagination">
					<button
						type="button"
						className="rank-config__page-btn"
						disabled={page <= 1}
						onClick={() => setPage(p => p - 1)}
					>
						◀
					</button>
					{Array.from({ length: totalPages }, (_, i) => i + 1).map(p => (
						<button
							key={p}
							type="button"
							className={`rank-config__page-btn${p === page ? ' rank-config__page-btn--active' : ''}`}
							onClick={() => setPage(p)}
						>
							{p}
						</button>
					))}
					<button
						type="button"
						className="rank-config__page-btn"
						disabled={page >= totalPages}
						onClick={() => setPage(p => p + 1)}
					>
						▶
					</button>
				</div>
			)}
		</div>
	);
}