'use client';

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlus } from '@fortawesome/free-solid-svg-icons';
import { Checkbox } from '@/components/ui/checkbox';
import type { GoalConfigItem } from '@/types/response/donation/goalConfig';
import { PER_PAGE_OPTIONS } from '@/constants/donation';
import { GOAL_STYLES, formatDateTime } from '../types';

type Props = {
	items: GoalConfigItem[];
	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: GoalConfigItem) => void;
	onBatchDelete: () => void;
};

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

			<div className="goal-config__table-wrap">
				{loading ? (
					<div className="goal-config__empty">준비 중...</div>
				) : items.length === 0 ? (
					<div className="goal-config__empty">등록된 목표 설정이 없습니다.</div>
				) : (
					<table className="goal-config__table">
						<thead>
							<tr>
								<th className="goal-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>
								<th>비고</th>
							</tr>
						</thead>
						<tbody>
							{pagedItems.map(item => {
								const isChecked = checkedIDs.has(item.id);
								const percent = item.targetAmount > 0 ? Math.min((item.startAmount / item.targetAmount) * 100, 100) : 0;
								return (
									<tr
										key={item.id}
										className={isChecked ? 'goal-config__row--checked' : ''}
									>
										<td className="goal-config__td--check">
											<Checkbox
												checked={isChecked}
												onCheckedChange={() => handleToggleCheck(item.id)}
												aria-label={`${item.id} 선택`}
											/>
										</td>
										<td>{item.title}</td>
										<td className="goal-config__td--bar">
											<div className="goal-config__mini-bar" style={{ background: item.barBackgroundColor }}>
												<div
													className="goal-config__mini-bar-fill"
													style={{ width: `${percent}%`, background: item.barColor }}
												/>
												<span className="goal-config__mini-bar-text">
													{item.startAmount.toLocaleString()} / {item.targetAmount.toLocaleString()}
													{item.isShowPercent && ` (${Math.round(percent)}%)`}
												</span>
											</div>
										</td>
										<td>{item.startAmount.toLocaleString()}원</td>
										<td>{item.targetAmount.toLocaleString()}원</td>
										<td className="goal-config__td--date">
											{formatDateTime(item.startAt)} ~ {formatDateTime(item.endAt)}
										</td>
										<td>{GOAL_STYLES.find(s => s.value === item.style)?.label ?? item.style}</td>
										<td>
											<span className={`goal-config__status-badge goal-config__status-badge--${item.isActive ? 'active' : 'inactive'}`}>
												{item.isActive ? '활성' : '비활성'}
											</span>
										</td>
										<td>
											<button
												type="button"
												className="goal-config__btn goal-config__btn--sm"
												onClick={() => onEdit(item)}
												disabled={isChecked}
											>
												수정
											</button>
										</td>
									</tr>
								);
							})}
						</tbody>
					</table>
				)}
			</div>

			{totalPages > 1 && (
				<div className="goal-config__pagination">
					<button
						type="button"
						className="goal-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={`goal-config__page-btn${p === page ? ' goal-config__page-btn--active' : ''}`}
							onClick={() => setPage(p)}
						>
							{p}
						</button>
					))}
					<button
						type="button"
						className="goal-config__page-btn"
						disabled={page >= totalPages}
						onClick={() => setPage(p => p + 1)}
					>
						▶
					</button>
				</div>
			)}
		</div>
	);
}