'use client';

import { useState, type CSSProperties } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlus } from '@fortawesome/free-solid-svg-icons';
import { Checkbox } from '@/components/ui/checkbox';
import { fetchApi } from '@/lib/utils/client';
import { useStudioContext } from '@/app/studio/context';
import { useGoalConfigContext } from '../context';
import type { GoalConfigItem } from '@/types/response/donation/goalConfig';
import { PER_PAGE_OPTIONS } from '@/constants/donation';
import { GOAL_STYLES, formatPeriod } 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 { channelID } = useStudioContext();
	const { setItems } = useGoalConfigContext();
	const [togglingIDs, setTogglingIDs] = useState<Set<number>>(new Set());

	// ── 활성/비활성 토글 ─────────────────────────────
	const handleToggleActive = async (item: GoalConfigItem) => {
		if (!channelID || togglingIDs.has(item.id)) {
			return;
		}

		const next = !item.isActive;

		setTogglingIDs(prev => {
			const s = new Set(prev);
			s.add(item.id);
			return s;
		});

		setItems(prev => prev.map(x => x.id === item.id ? { ...x, isActive: next } : x));

		try {
			const res = await fetchApi<{ id: number; isActive: boolean }>(
				`/api/studio/donation/goal/config/${item.id}/active`,
				{
					method: 'PATCH',
					body: { channelID, isActive: next },
					silent: true
				}
			);

			if (!res.success) {
				setItems(prev => prev.map(x => x.id === item.id ? { ...x, isActive: item.isActive } : x));
				alert(res.message || '활성 상태 변경에 실패했습니다.');
			} else if (res.data && res.data.isActive !== next) {
				setItems(prev => prev.map(x => x.id === item.id ? { ...x, isActive: res.data!.isActive } : x));
			}
		} catch (err) {
			setItems(prev => prev.map(x => x.id === item.id ? { ...x, isActive: item.isActive } : x));
			alert(err instanceof Error ? err.message : '활성 상태 변경에 실패했습니다.');
		} finally {
			setTogglingIDs(prev => {
				const s = new Set(prev);
				s.delete(item.id);
				return s;
			});
		}
	};

	// ── 페이징 ───────────────────────────────────────
	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={{ '--mini-bar-bg': item.barBackgroundColor } as CSSProperties}>
												<div
													className="goal-config__mini-bar-fill"
													style={{ '--mini-bar-percent': `${percent}%`, '--mini-bar-color': item.barColor } as CSSProperties}
												/>
												<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">
											{formatPeriod(item.period, item.startAt, item.endAt)}
										</td>
										<td>{GOAL_STYLES.find(s => s.value === item.style)?.label ?? item.style}</td>
										<td>
											<button
												type="button"
												role="switch"
												aria-checked={item.isActive}
												aria-busy={togglingIDs.has(item.id)}
												aria-label={`${item.title || `#${item.id}`} 활성 상태 ${item.isActive ? '끄기' : '켜기'}`}
												className={`goal-config__active-toggle${item.isActive ? ' goal-config__active-toggle--on' : ''}${togglingIDs.has(item.id) ? ' goal-config__active-toggle--busy' : ''}`}
												onClick={() => handleToggleActive(item)}
												disabled={togglingIDs.has(item.id) || saving}
												title={item.isActive ? '비활성화' : '활성화'}
											>
												<span className="goal-config__active-toggle-knob" aria-hidden="true" />
											</button>
										</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>
	);
}