import React, { useState, useEffect, Fragment } from 'react';
import styled from 'styled-components';

import { Title, ButtonGroupWrapper, } from '../../styles/Components';
import Modal from '../common/modal/Modal';
import { MenuBannerModify } from '../../apis';

import { authList } from '../../store/authList';
import { useRecoilValue } from 'recoil';
import { authType, commonStatus } from '../../assets/data';
import { convertKTCDate } from '../../utils';
import { useLoading } from '../../context/LoadingProvider';
import { useAlert } from '../../context/AlertProvider';
import { alertTypes, languageNames } from '../../assets/data/types';
import { Image as AntImage } from 'antd';
import { AntButton, DetailLayout } from '../common';

function renderImageContent(imageData) {
	if (!imageData) {
		return <NoImagePlaceholder>이미지가 없습니다</NoImagePlaceholder>;
	}

	return (
		<>
			<ImageWrapper>
				<AntImage
					src={imageData.title}
					alt={`${imageData.language} 배너 이미지`}
					style={{ width: '100%', maxHeight: '300px', objectFit: 'contain' }}
					placeholder={
						<AntImage
							preview={false}
							src={imageData.title}
							width={300}
						/>
					}
					// preview={{
					// 	mask: '미리보기',
					// 	maskClassName: 'custom-mask',
					// }}
					fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpA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yNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=="
				/>
			</ImageWrapper>
			{imageData.content &&
			<ImageUrlInfo>
				<UrlLink
					href={imageData.content}
					target="_blank"
					rel="noopener noreferrer"
				>
					{imageData.content}
				</UrlLink>
			</ImageUrlInfo>
			}
		</>
	);
}

const MenuBannerDetailModal = ({ detailView, handleDetailView, content, setDetailData }) => {
	const userInfo = useRecoilValue(authList);
	const token = sessionStorage.getItem('token');
	const {withLoading} = useLoading();
	const {showModal, showToast} = useAlert();

	const id = content && content.id;
	const updateAuth = userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.menuBannerUpdate);

	const [time, setTime] = useState({
		start_hour: '00',
		start_min: '00',
		end_hour: '00',
		end_min: '00',
	});	//시간 정보

	const [resultData, setResultData] = useState(initData);
	const [activeLanguage, setActiveLanguage] = useState('KO');

	const [tabItems, setTabItems] = useState([]);

	useEffect(() => {
		if(content){
			// console.log(content);
			const start_dt_KTC = convertKTCDate(content.start_dt);
			const end_dt_KTC = convertKTCDate(content.end_dt);

			setResultData({
				id: content.id,
				title: content.title,
				start_dt: start_dt_KTC,
				end_dt: end_dt_KTC,
				status: content.status,
				order_id: content.order_id,
				is_link: content.is_link,
				image_list: content.image_list,
			});

			setTime({ ...time,
				start_hour: String(start_dt_KTC.getHours()).padStart(2, '0'),
				start_min: String(start_dt_KTC.getMinutes()).padStart(2, '0'),
				end_hour: String(end_dt_KTC.getHours()).padStart(2, '0'),
				end_min: String(end_dt_KTC.getMinutes()).padStart(2, '0')
			});
		}

	}, [content]);

	useEffect(() => {
		if (content && content.image_list) {

			// 첫 번째 언어를 활성 언어로 설정
			if (content.image_list && content.image_list.length > 0) {
				setActiveLanguage(content.image_list[0].language);
			}

			// 동적으로 탭 아이템 생성
			const newTabItems = content.image_list ? content.image_list.map(imageData => ({
				key: imageData.language,
				label: languageNames[imageData.language] || imageData.language,
				children: (
					<ImageContainer>
						{renderImageContent(imageData)}
					</ImageContainer>
				)
			})) : [];

			setTabItems(newTabItems);
		}
	}, [content]);


	// 확인 버튼 후 다 초기화
	const handleReset = () => {
	};

	const checkCondition = () => {
		return (
			(resultData.start_dt.length !== 0) &&
			(resultData.end_dt.length !== 0) &&
			resultData.title !== '' &&
			resultData.order_id !== ''
		);
	};

	// 탭 변경 핸들러
	const handleTabChange = (key) => {
		setActiveLanguage(key);
	};

	const handleSubmit = async (type, param = null) => {
		switch (type) {
			case "submit":
				if (!checkCondition()) return;

				// console.log(resultData);
				showModal('MENU_BANNER_UPDATE_SAVE', {
					type: alertTypes.confirm,
					onConfirm: () => handleSubmit('updateConfirm')
				});
				break;
			case "updateConfirm":
				withLoading( async () => {
					return await MenuBannerModify(token, id, resultData);
				}).then(result => {
					if(result.result === 'ERROR'){
						showToast(result.data.message, {
							type: alertTypes.error
						});
					}else if(result.result === 'SUCCESS'){
						showToast('UPDATE_COMPLETED', {type: alertTypes.success, duration: 4000});
					}
				}).catch(error => {
					showToast('API_FAIL', {type: alertTypes.error});
				}).finally(() => {
					handleDetailView();
				});
				break;
		}
	}

	const isView = (fieldName) => {
		if (fieldName === 'editButton') {
			// updateAuth가 없거나 FINISH 상태면 수정 버튼 숨김
			return !updateAuth || content?.status === commonStatus.finish;
		}

		if (!updateAuth) return false;

		if(content.status === commonStatus.wait){
			return true;
		}else if(content.status === commonStatus.running){
			switch(fieldName){
				case 'order_id':
				case 'end_dt':
					return true;
				default:
					return false;
			}
		}else{
			return false;
		}
	}

	const itemGroups = [
		{
			items: [
				{
					row: 0,
					col: 0,
					colSpan: 2,
					type: 'text',
					key: 'title',
					label: '제목',
					disabled: !isView('title'),
					width: '250px',
				},
				{
					row: 0,
					col: 2,
					colSpan: 2,
					type: 'number',
					key: 'order_id',
					label: '순서',
					disabled: !isView('order_id'),
					width: '100px',
					min: 0,
				},
				{
					row: 1,
					col: 0,
					colSpan: 2,
					type: 'status',
					key: 'status',
					label: '상태',
					value: resultData.status,
				},
				{
					row: 2,
					col: 0,
					colSpan: 2,
					type: 'date',
					key: 'start_dt',
					label: '시작일',
					disabled: !isView('start_dt'),
					format: 'YYYY-MM-DD HH:mm',
					width: '250px',
					showTime: true
				},
				{
					row: 2,
					col: 2,
					colSpan: 2,
					type: 'date',
					key: 'end_dt',
					label: '종료일',
					disabled: !isView('end_dt'),
					format: 'YYYY-MM-DD HH:mm',
					width: '250px',
					showTime: true
				},
				{
					row: 3,
					col: 0,
					colSpan: 4,
					type: 'tab',
					key: 'languageTabs',
					tabItems: tabItems,
					activeKey: activeLanguage,
					onTabChange: handleTabChange
				},
			]
		}
	];

	return (
		<>
			<Modal min="960px" $view={detailView}>
				<Title $align="center">배너 상세 정보</Title>
				<DetailLayout
					itemGroups={itemGroups}
					formData={resultData}
					onChange={setResultData}
					disabled={!updateAuth}
					columnCount={4}
				/>
				<ButtonGroupWrapper $justify="flex-end" $gap="10px" $paddingTop="20px">
					<AntButton
						text="확인"
						theme="line"
						name="확인버튼"
						onClick={() => {
							handleDetailView();
							handleReset();
							setDetailData('');
						}}
					/>
					{!isView('editButton') && (
						<AntButton
							type="submit"
							text="수정"
							id="수정버튼"
							theme={checkCondition() ? 'primary' : 'disable'}
							onClick={() => handleSubmit('submit')}
						/>
					)}
				</ButtonGroupWrapper>
			</Modal>
		</>
	);
};

export default MenuBannerDetailModal;

const initData = {
	title: '',
	is_link: false,
	start_dt: '',
	end_dt: '',
	image_list: [
		{ language: 'KO', content: '', title: '' },
		{ language: 'EN', content: '', title: '' },
		{ language: 'JA', content: '', title: '' },
	]
}

const ImageContainer = styled.div`
    padding: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    width: 100%;
    max-width: 700px;
    margin: 0 auto;
`;

const ImageWrapper = styled.div`
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    width: 100%;
    text-align: center;
`;

const ImageUrlInfo = styled.div`
    margin-top: 16px;
    padding: 12px;
    background-color: #f5f5f5;
    border-radius: 6px;
    font-size: 14px;
    word-break: break-all;
    width: 100%;
`;

const UrlLink = styled.a`
  color: #1890ff;
  text-decoration: underline;
  cursor: pointer;
  &:hover {
    opacity: 0.8;
  }
`;

const NoImagePlaceholder = styled.div`
    width: 100%;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f0f2f5;
    color: #8c8c8c;
    border-radius: 8px;
`;

