'use client';

import './style.scss';
import Link from 'next/link';
import Image from 'next/image';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faGoogle } from '@fortawesome/free-brands-svg-icons';
import useAuth from '@/hooks/useAuth';
import { fetchApi, getDateTime, stripHtmlTags } from '@/lib/utils/client';
import { SnsLinkItem, SnsListResponse } from '@/types/sns';
import NavTabs from '../navTabs';
import { FEATURE_CHANNEL } from '@/constants/features';

type ProviderMeta = {
	provider: 'Google' | 'Naver' | 'Kakao';
	label: string;
	enabled: boolean;
};

const PROVIDERS: ProviderMeta[] = [
	{ provider: 'Google', label: 'Google', enabled: true },
	{ provider: 'Naver', label: 'Naver', enabled: false },
	{ provider: 'Kakao', label: 'Kakao', enabled: false }
];

export default function Profile()
{
	const { member } = useAuth();
	const [snsItems, setSnsItems] = useState<SnsLinkItem[]>([]);

	const loadSnsItems = useCallback(async () => {
		try {
			const res = await fetchApi<SnsListResponse>('/api/mypage/sns', { silent: true });
			if (res.data) {
				setSnsItems(res.data.items);
			}
		} catch {
			// silent
		}
	}, []);

	useEffect(() => {
		if (!member) {
			return;
		}
		loadSnsItems();
	}, [member, loadSnsItems]);

	const snsItemMap = useMemo(() => {
		const map = new Map<string, SnsLinkItem>();
		snsItems.forEach((item) => map.set(item.provider, item));
		return map;
	}, [snsItems]);

	if (!member) {
		return null;
	}

	return (
		<>
		<NavTabs />

		<div id="profile">
			<h1>내 정보</h1>
			<div className="grid grid-cols-1 xl:grid-cols-2 gap-3">
				<table className="table-auto">
					<caption>등록 정보</caption>
					<colgroup>
						<col className="w-[clamp(80px,30%,200px)]"/>
						<col/>
					</colgroup>
					<tbody>
						<tr>
							<th>사용자 ID</th>
							<td colSpan={2}>{member?.sid}</td>
						</tr>
						<tr>
							<th>이메일</th>
							<td>{member?.email}</td>
							<td>
								<Link href="/change-email" className="btn btn-default">이메일 변경</Link>
							</td>
						</tr>
						<tr>
							<th>별명</th>
							<td>{member?.name || '-'}</td>
							<td>
								<Link href="/change-name" className="btn btn-default">별명 변경</Link>
							</td>
						</tr>
						<tr>
							<th>본인인증</th>
							<td>{member?.isAuthCertified ? '인증 완료' : '-'}</td>
							<td></td>
						</tr>
						<tr>
							<th>SNS 연동</th>
							<td>
								<div className="profile__sns-logos" aria-label="SNS 연동 상태">
									{PROVIDERS.map((meta) => {
										const item = snsItemMap.get(meta.provider);
										const connected = item?.connected ?? false;
										const stateText = !meta.enabled
											? `${meta.label} 준비중`
											: (connected ? `${meta.label} 연동됨` : `${meta.label} 미연동`);

										return (
											<span
												key={meta.provider}
												className={`profile__sns-logo profile__sns-logo--${meta.provider.toLowerCase()}${connected ? ' profile__sns-logo--connected' : ' profile__sns-logo--inactive'}${meta.enabled ? '' : ' profile__sns-logo--disabled'}`}
												title={stateText}
												aria-label={stateText}
											>
												{meta.provider === 'Google' && <FontAwesomeIcon icon={faGoogle} />}
												{meta.provider === 'Naver' && <span className="profile__sns-logo-text">N</span>}
												{meta.provider === 'Kakao' && <span className="profile__sns-logo-text">K</span>}
											</span>
										);
									})}
								</div>
							</td>
							<td>
								<Link href="/sns-link" className="btn btn-default">SNS 관리</Link>
							</td>
						</tr>
						<tr>
							<th>회원가입 일시</th>
							<td colSpan={2}>{getDateTime(member.createdAt)}</td>
						</tr>
						<tr>
							<th>마지막 로그인 일시</th>
							<td colSpan={2}>{getDateTime(member.lastLoginAt)}</td>
						</tr>
						<tr>
							<th>알림 수신</th>
							<td>
								<div className="flex items-center gap-4 flex-wrap">
									<label className="flex items-center gap-2 text-gray-700">
										<input type="checkbox" checked={member.memberApprove.isReceiveSMS} readOnly disabled className="accent-gray-500 cursor-not-allowed" />
										SMS
									</label>

									<label className="flex items-center gap-2 text-gray-700">
										<input type="checkbox" checked={member.memberApprove.isReceiveEmail} readOnly disabled className="accent-gray-500 cursor-not-allowed" />
										메일
									</label>

									<label className="flex items-center gap-2 text-gray-700">
										<input type="checkbox" checked={member.memberApprove.isReceiveNote} readOnly disabled className="accent-gray-500 cursor-not-allowed" />
										쪽지
									</label>
								</div>
							</td>
							<td>
								<Link href="/change-approve" className="btn btn-default">수신 설정</Link>
							</td>
						</tr>
					</tbody>
				</table>

				<table className="mt-3 xl:mt-0 table-auto">
					<caption>활동 정보</caption>
					<colgroup>
						<col className="w-full min-w-[80px] max-w-[30%]"/>
						<col width="*"/>
						<col width="*"/>
					</colgroup>
					<tbody>
						<tr>
							<th>회원 사진</th>
							<td>
								{member?.thumb ?
								(<Image src={member?.thumb} alt="회원 사진" width={64} height={64} className="object-cover" unoptimized={true} />) : '-'}
							</td>
							<td>
								<Link href="/change-thumb" className="btn btn-default">사진 변경</Link>
							</td>
						</tr>
						<tr>
							<th>회원 등급</th>
							<td></td>
							<td></td>
						</tr>
						<tr>
							<th>한마디</th>
							<td colSpan={2}>
								<div className="grid grid-cols-[1fr_auto] gap-2 items-center">
									<span className="truncate">{member?.summary || '-'}</span>
									<Link href="/change-summary" className="btn btn-default">한마디 변경</Link>
								</div>
							</td>
						</tr>
						<tr>
							<th>자기소개</th>
							<td colSpan={2}>
								<div className="grid grid-cols-[1fr_auto] gap-2 items-center">
									<span className="truncate">{stripHtmlTags(member.intro) || '-'}</span>
									<Link href="/change-intro" className="btn btn-default">자기소개 변경</Link>
								</div>
							</td>
						</tr>
						<tr>
							<th>경험치</th>
							<td colSpan={2}>{member?.memberStats.exp}</td>
						</tr>
						<tr>
							<th>작성 게시글</th>
							<td colSpan={2}>{member?.memberStats.postCount}</td>
						</tr>
						<tr>
							<th>작성 댓글</th>
							<td colSpan={2}>{member?.memberStats.commentCount}</td>
						</tr>
						<tr>
							<th>팔로워</th>
							<td colSpan={2}>{member?.memberStats.followerCount ?? 0}</td>
						</tr>
						<tr>
							<th>팔로잉</th>
							<td colSpan={2}>{member?.memberStats.followingCount ?? 0}</td>
						</tr>
					</tbody>
				</table>

				{/* 채널 기능 OFF 시 스튜디오 진입 링크 미노출 */}
				{FEATURE_CHANNEL && (
					<Link href='/studio' className='text-sky-600 hover:text-red-600 hover:underline'>채널 관리</Link>
				)}
			</div>

			<br />

			<dl>
				<dt>회원님의 개인정보는 안전하게 보호됩니다.</dt>
				<dd>※ 의심스러운 활동이 감지되면 즉시 비밀번호를 변경하세요.</dd>
				<dd>※ 보안을 위해 비밀번호를 주기적으로 변경하는 것이 좋습니다.</dd>
				<dd>※ 자동 로그인 기능을 사용하면, 로그인 상태가 유지됩니다.</dd>
				<dd>※ 공용 컴퓨터에서는 자동 로그인을 사용하지 않는 것이 좋습니다.  </dd>
			</dl>
		</div>
		</>
	);
}
