import { DetailMessage, TableStyle, TableWrapper } from '../../../styles/Components';
import { StatusLabel } from '../../../styles/ModuleComponents';
import { Button, CheckBox } from '../index';
import { convertKTC, getOptionsArray } from '../../../utils';
import { styled } from 'styled-components';
import { TableSkeleton } from '../../Skeleton/TableSkeleton';

const CaliTable = ({
						  columns,
						  data,
						  onSelectRow,
					      isRowSelected,
						  onAction,
						  refProp,
						loading = false
					  }) => {

	const renderCell = (column, item) => {
		const { type, id, option_name, format, action } = column;
		const value = item[id];

		const options = getOptionsArray(option_name);

		switch (type) {
			case 'text':
				return value;

			case 'date':
				return convertKTC(value);

			case 'status':
				const statusOption = options.find(opt => opt.value === value);
				return (
					<StatusWapper>
						<StatusLabel $status={value}>
							{statusOption ? statusOption.name : value}
						</StatusLabel>
					</StatusWapper>
				);

			case 'button':
				return (
					<Button
						theme="line"
						text={column.text || "액션"}
						handleClick={() => onAction(id, item)}
					/>
				);

			case 'checkbox':
				return (
					<CheckBox
						name={column.name || 'select'}
						id={item.id}
						setData={(e) => onSelectRow(e, item)}
						checked={isRowSelected(item.id)}
					/>
				);

			case 'option':
				const dataOption = options.find(opt => opt.value === value);
				return (
					dataOption ? dataOption.name : value
				);

			case "link":
				return (
					<DetailMessage onClick={() => onAction(action)}>
						{value.content.length > 20 ? value.content.slice(0, 20) + '...' : value.content || ''}
					</DetailMessage>
				);

			default:
				return value;
		}
	};

	return (
		loading ? <TableSkeleton count={15}/> :
		<TableWrapper>
			<TableStyle ref={refProp}>
				<caption></caption>
				<thead>
				<tr>
					{columns.map((column, index) => (
						<th key={index} width={column.width || 'auto'}>
							{column.title}
						</th>
					))}
				</tr>
				</thead>
				<tbody>
				{data?.map((item, rowIndex) => (
					<tr key={rowIndex}>
						{columns.map((column, colIndex) => (
							<td key={colIndex}>
								{renderCell(column, item)}
							</td>
						))}
					</tr>
				))}
				</tbody>
			</TableStyle>
		</TableWrapper>
	);
};

export default CaliTable;

const StatusWapper = styled.div`
    display: flex;
    gap: 0.35rem;
    align-items: center;
    justify-content: center;
`;