'use client';

import { useState, useEffect, useMemo } from 'react';
import Link from 'next/link';
import { fetchApi, getDateTime } from '@/lib/utils/client';
import type { WalletWithdrawResponse } from '@/types/response/wallet/withdraw';
import { LoginLogType } from '@/constants/common';
import { PERIOD_TABS, WITHDRAW_STATUS_MAP, WITHHOLDING_TAX_RATE, MIN_WITHDRAW_AMOUNT } from '../constants';
import Loading from '@/app/component/Loading';
import Pagination from '@/app/component/Pagination';

export default function WalletWithdrawPage() {
	const [loading, setLoading] = useState(true);
	const [submitting, setSubmitting] = useState(false);
	const [page, setPage] = useState(1);
	const [period, setPeriod] = useState<LoginLogType>(LoginLogType.Month);
	const [data, setData] = useState<WalletWithdrawResponse>({
		total: 0,
		withdrawableBalance: 0,
		accounts: [],
		list: [],
	});
	const [amount, setAmount] = useState('');
	const [selectedAccountID, setSelectedAccountID] = useState<number>(0);

	const numericAmount = useMemo(() => {
		const n = parseInt(amount, 10);
		return isNaN(n) ? 0 : n;
	}, [amount]);

	const withholdingTax = useMemo(() => Math.floor(numericAmount * WITHHOLDING_TAX_RATE), [numericAmount]);
	const netAmount = useMemo(() => numericAmount - withholdingTax, [numericAmount, withholdingTax]);

	const canSubmit = useMemo(() => {
		return (
			selectedAccountID > 0 &&
			numericAmount >= MIN_WITHDRAW_AMOUNT &&
			numericAmount <= data.withdrawableBalance &&
			!submitting
		);
	}, [selectedAccountID, numericAmount, data.withdrawableBalance, submitting]);

	useEffect(() => {
		setLoading(true);
		fetchApi<WalletWithdrawResponse>(`/api/studio/wallet/withdraw?period=${period}&page=${page}&perPage=20`)
			.then(res => {
				if (res.data) {
					setData(res.data);
					// 계좌가 1개면 자동 선택
					if (res.data.accounts.length === 1 && selectedAccountID === 0) {
						setSelectedAccountID(res.data.accounts[0].id);
					}
				}
			})
			.catch(() => {})
			.finally(() => setLoading(false));
	}, [period, page]);

	useEffect(() => {
		setPage(1);
	}, [period]);

	const handleSubmit = async () => {
		if (!canSubmit) {
			return;
		}

		const selectedAccount = data.accounts.find(a => a.id === selectedAccountID);
		const confirmed = confirm(
			`출금 신청하시겠습니까?\n\n` +
			`입금 계좌: ${selectedAccount?.bankName} ${selectedAccount?.accountNumber}\n` +
			`신청 금액: ${numericAmount.toLocaleString()}원\n` +
			`원천징수(3.3%): -${withholdingTax.toLocaleString()}원\n` +
			`실수령액: ${netAmount.toLocaleString()}원`
		);

		if (!confirmed) {
			return;
		}

		setSubmitting(true);
		try {
			await fetchApi('/api/studio/wallet/withdraw', {
				method: 'POST',
				body: { accountID: selectedAccountID, amount: numericAmount },
			});
			alert('출금 신청이 완료되었습니다.');
			setAmount('');
			// 목록 새로고침
			const res = await fetchApi<WalletWithdrawResponse>(`/api/studio/wallet/withdraw?period=${period}&page=1&perPage=20`);
			if (res.data) {
				setData(res.data);
			}
			setPage(1);
		} catch (err: unknown) {
			alert(err instanceof Error ? err.message : '출금 신청에 실패했습니다.');
		} finally {
			setSubmitting(false);
		}
	};

	const getStatus = (status: string) => WITHDRAW_STATUS_MAP[status] ?? { label: status, cls: '' };

	return (
		<div className="studio-page wallet">
			<div className="studio-page__header">
				<h1 className="studio-page__title">출금</h1>
			</div>

			{loading && <Loading />}

			{/* Withdraw Form */}
			<div className="wallet__withdraw-form">
				<div className="wallet__withdraw-balance">
					{data.withdrawableBalance.toLocaleString()}원
					<small>(M) 출금 가능</small>
				</div>

				{/* 계좌 미등록 경고 */}
				{data.accounts.length === 0 && (
					<div className="wallet__withdraw-warning">
						계좌가 등록되지 않았습니다.
						<Link href="/studio/settlement/account">계좌 등록하기</Link>
					</div>
				)}

				{/* 계좌 선택 */}
				{data.accounts.length > 0 && (
					<div className="wallet__withdraw-field">
						<label htmlFor="withdraw-account">입금 계좌</label>
						<select
							id="withdraw-account"
							className="wallet__withdraw-select"
							value={selectedAccountID}
							onChange={e => setSelectedAccountID(Number(e.target.value))}
						>
							{data.accounts.length > 1 && (
								<option value={0}>계좌를 선택하세요</option>
							)}
							{data.accounts.map(acc => (
								<option key={acc.id} value={acc.id}>
									{acc.bankName} {acc.accountNumber} ({acc.accountHolder})
								</option>
							))}
						</select>
						<Link href="/studio/settlement/account" className="wallet__withdraw-account-link">계좌 관리</Link>
					</div>
				)}

				{/* 금액 입력 */}
				<div className="wallet__withdraw-field">
					<label htmlFor="withdraw-amount">출금 금액</label>
					<input
						id="withdraw-amount"
						type="text"
						inputMode="numeric"
						className="wallet__withdraw-input"
						placeholder={`최소 ${MIN_WITHDRAW_AMOUNT.toLocaleString()}원`}
						value={amount}
						onChange={e => setAmount(e.target.value.replace(/\D/g, ''))}
						disabled={data.accounts.length === 0}
					/>
				</div>

				{/* 차감 프리뷰 */}
				{numericAmount > 0 && (
					<div className="wallet__withdraw-preview">
						<div className="wallet__withdraw-row">
							<span>신청 금액</span>
							<span>{numericAmount.toLocaleString()}원</span>
						</div>
						<div className="wallet__withdraw-row">
							<span>원천징수 (3.3%)</span>
							<span className="wallet__amount--minus">-{withholdingTax.toLocaleString()}원</span>
						</div>
						<div className="wallet__withdraw-total">
							<span>실수령액</span>
							<span>{netAmount.toLocaleString()}원</span>
						</div>
					</div>
				)}

				{/* 안내사항 */}
				<ul className="wallet__withdraw-info">
					<li>최소 출금 금액: {MIN_WITHDRAW_AMOUNT.toLocaleString()}원</li>
					<li>원천징수 3.3% (소득세 3% + 지방소득세 0.3%)</li>
					<li>매월 10일까지 신청 시 당월 말 입금</li>
				</ul>

				{/* 제출 */}
				<button
					type="button"
					className="wallet__withdraw-submit"
					disabled={!canSubmit}
					onClick={handleSubmit}
				>
					{submitting ? '신청 중...' : '출금 신청'}
				</button>
			</div>

			{/* Withdraw History */}
			<h2 className="wallet__section-title">출금 내역</h2>

			<div className="wallet__header">
				<div className="wallet__summary">합계: {data.total}건</div>
				<div className="wallet__tabs">
					{PERIOD_TABS.map((tab) => (
						<button
							type="button"
							key={tab.value}
							className={period === tab.value ? 'active' : ''}
							onClick={() => setPeriod(tab.value)}
						>
							{tab.label}
						</button>
					))}
				</div>
			</div>

			<div className="wallet__table-wrap">
				<table className="wallet__table">
					<thead>
						<tr>
							<th>신청일</th>
							<th style={{ textAlign: 'right' }}>신청 금액</th>
							<th style={{ textAlign: 'right' }}>원천징수</th>
							<th style={{ textAlign: 'right' }}>실수령액</th>
							<th>계좌</th>
							<th>상태</th>
						</tr>
					</thead>
					<tbody>
						{data.list.length > 0 ? (
							data.list.map((row) => {
								const st = getStatus(row.status);
								return (
									<tr key={row.id}>
										<td>{getDateTime(row.requestedAt)}</td>
										<td style={{ textAlign: 'right' }}>{row.requestedAmount.toLocaleString()}원</td>
										<td style={{ textAlign: 'right' }}>
											<span className="wallet__amount--minus">-{row.withholdingTax.toLocaleString()}원</span>
										</td>
										<td style={{ textAlign: 'right' }}>
											<span className="wallet__amount--plus">{row.netAmount.toLocaleString()}원</span>
										</td>
										<td>{row.bankName} {row.accountNumber}</td>
										<td><span className={st.cls}>{st.label}</span></td>
									</tr>
								);
							})
						) : (
							<tr>
								<td colSpan={6} className="wallet__empty">출금 내역이 없습니다.</td>
							</tr>
						)}
					</tbody>
				</table>
			</div>

			{data.total > 0 && (
				<Pagination total={data.total} page={page} perPage={20} onChange={setPage} />
			)}
		</div>
	);
}