'use client';

import { useState, useEffect, useMemo } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCircleInfo } from '@fortawesome/free-solid-svg-icons';
import { fetchApi } from '@/lib/utils/client';
import type { WithholdingTaxSummaryResponse } from '@/types/response/settlement/tax';
import { MONTH_NAMES, TAX_GUIDE_ITEMS } from '../constants';
import Loading from '@/app/component/Loading';

export default function SettlementTaxPage() {
	const currentYear = new Date().getFullYear();
	const [loading, setLoading] = useState(true);
	const [year, setYear] = useState(currentYear);
	const [data, setData] = useState<WithholdingTaxSummaryResponse|null>(null);

	const yearOptions = useMemo(() => {
		const years: number[] = [];
		for (let y = currentYear; y >= currentYear - 4; y--) {
			years.push(y);
		}
		return years;
	}, [currentYear]);

	useEffect(() => {
		setLoading(true);
		fetchApi<WithholdingTaxSummaryResponse>(`/api/studio/settlement/tax?year=${year}`)
			.then(res => {
				if (res.data) {
					setData(res.data);
				}
			})
			.catch(() => {})
			.finally(() => setLoading(false));
	}, [year]);

	return (
		<div className="studio-page settlement">
			<div className="studio-page__header">
				<h1 className="studio-page__title">원천징수 내역</h1>
			</div>

			{/* 연도 선택 */}
			<div className="settlement__year-select">
				<label htmlFor="year-select">연도</label>
				<select
					id="year-select"
					value={year}
					onChange={e => setYear(Number(e.target.value))}
				>
					{yearOptions.map(y => (
						<option key={y} value={y}>{y}년</option>
					))}
				</select>
			</div>

			{loading && <Loading />}

			{!loading && data && (
				<>
					{/* 연간 요약 카드 */}
					<div className="settlement__cards">
						<div className="settlement__card">
							<span className="settlement__card-label">총 지급액</span>
							<div className="settlement__card-value">
								{data.annualSummary.totalGrossAmount.toLocaleString()}원
							</div>
						</div>
						<div className="settlement__card">
							<span className="settlement__card-label">소득세 (3%)</span>
							<div className="settlement__card-value settlement__card-value--danger">
								-{data.annualSummary.totalIncomeTax.toLocaleString()}원
							</div>
						</div>
						<div className="settlement__card">
							<span className="settlement__card-label">지방소득세 (0.3%)</span>
							<div className="settlement__card-value settlement__card-value--danger">
								-{data.annualSummary.totalLocalTax.toLocaleString()}원
							</div>
						</div>
						<div className="settlement__card">
							<span className="settlement__card-label">실수령액</span>
							<div className="settlement__card-value settlement__card-value--primary">
								{data.annualSummary.totalNetAmount.toLocaleString()}원
							</div>
						</div>
					</div>

					{/* 월별 상세 */}
					<h2 className="settlement__section-title">월별 상세</h2>
					<div className="settlement__table-wrap">
						<table className="settlement__table">
							<thead>
								<tr>
									<th>월</th>
									<th style={{ textAlign: 'right' }}>지급액</th>
									<th style={{ textAlign: 'right' }}>소득세</th>
									<th style={{ textAlign: 'right' }}>지방소득세</th>
									<th style={{ textAlign: 'right' }}>실수령액</th>
									<th style={{ textAlign: 'right' }}>건수</th>
								</tr>
							</thead>
							<tbody>
								{data.monthlyList.length > 0 ? (
									data.monthlyList.map(row => (
										<tr key={row.month}>
											<td>{MONTH_NAMES[row.month - 1]}</td>
											<td style={{ textAlign: 'right' }}>
												{row.grossAmount.toLocaleString()}원
											</td>
											<td style={{ textAlign: 'right' }}>
												<span className="settlement__amount--minus">
													-{row.incomeTax.toLocaleString()}원
												</span>
											</td>
											<td style={{ textAlign: 'right' }}>
												<span className="settlement__amount--minus">
													-{row.localTax.toLocaleString()}원
												</span>
											</td>
											<td style={{ textAlign: 'right' }}>
												<span className="settlement__amount--plus">
													{row.netAmount.toLocaleString()}원
												</span>
											</td>
											<td style={{ textAlign: 'right' }}>{row.paymentCount}건</td>
										</tr>
									))
								) : (
									<tr>
										<td colSpan={6} className="settlement__empty">
											해당 연도의 원천징수 내역이 없습니다.
										</td>
									</tr>
								)}
							</tbody>
						</table>
					</div>

					{/* 종합소득세 신고 안내 */}
					<div className="settlement__guide">
						<div className="settlement__guide-title">
							<FontAwesomeIcon icon={faCircleInfo} />
							종합소득세 신고 안내
						</div>
						<ul className="settlement__guide-list">
							{TAX_GUIDE_ITEMS.map((item, i) => (
								<li key={i}>{item}</li>
							))}
						</ul>
					</div>
				</>
			)}
		</div>
	);
}