import { InfoSubTitle, UserDefaultTable, UserInfoTable, UserTableWrapper } from '../../styles/ModuleComponents';
import { useTranslation } from 'react-i18next';
import { useEffect, useState } from 'react';
import { TableSkeleton } from '../Skeleton/TableSkeleton';
import { UserMyhomeView } from '../../apis';
import { SelectInput } from '../../styles/Components';

const UserMyHomeInfo = ({ userInfo }) => {
	const { t } = useTranslation();

	const [dataList, setDataList] = useState();
	const [loading, setLoading] = useState(true);
	const [selectedHome, setSelectedHome] = useState('');

	useEffect(() => {
		if(userInfo && Object.keys(userInfo).length > 0) {
			fetchData();
		}
	}, []);

	const fetchData = async () => {
		const token = sessionStorage.getItem('token');
		await UserMyhomeView(token, userInfo.guid).then(data => {
			setDataList(data);
			if (data.myhome_info && data.myhome_info.length > 0) {
				setSelectedHome(data.myhome_info[0].myhome_guid);
			}
			setLoading(false);
		});
	};

	const handleHomeChange = (e) => {
		setSelectedHome(e.target.value);
	};

	return (
		loading ? <TableSkeleton count={15}/> :
			dataList &&
			<>
				<UserInfoTable $maxwidth="700px">
					<tbody>
					<tr>
						<th>마이 홈명</th>
						<SelectInput onChange={handleHomeChange} value={selectedHome}>
							{dataList.myhome_info && dataList.myhome_info.map((data, index) => (
								<option key={index} value={data.myhome_guid}>
									{data.myhome_name}
								</option>
							))}
						</SelectInput>
					</tr>
					</tbody>
				</UserInfoTable>
				<InfoSubTitle top='30px'>배치 소품</InfoSubTitle>
				<UserTableWrapper>
					<UserDefaultTable>
						<thead>
						<tr>
							<th width="80">no.</th>
							<th width="120">아이템ID</th>
							<th width="50%">아이템명</th>
						</tr>
						</thead>
						<tbody>
						{dataList.myhome_info.find(home => home.myhome_guid === selectedHome)?.prop_list?.map((el, idx) => (
							<tr key={idx}>
								<td>{idx + 1}</td>
								<td>{el.item_id}</td>
								<td>{el.item_name}</td>
							</tr>
						))}
						{(!dataList.myhome_info.find(home => home.myhome_guid === selectedHome)?.prop_list ||
							dataList.myhome_info.find(home => home.myhome_guid === selectedHome)?.prop_list.length === 0) && (
							<tr>
								<td colSpan="3" style={{textAlign: 'center'}}>{t('TABLE_DATA_NOT_FOUND')}</td>
							</tr>
						)}
						</tbody>
					</UserDefaultTable>
				</UserTableWrapper>
			</>
	);
};

export default UserMyHomeInfo;


