import { memo, useEffect, useState } from 'react';
import { styled } from 'styled-components';
import { TextInput, InputLabel, SelectInput } from '../../styles/Components';
import { logDomain, opInputType } from '../../assets/data/options';

const TextInputWithHelp = memo(({ helpText, ...props }) => {
	return (
		<TextInputWrapper>
			<TextInput {...props} />
			{helpText && <HelpText>{helpText}</HelpText>}
		</TextInputWrapper>
	);
});

const SearchFilter = ({ value = [], onChange }) => {
	const [filters, setFilters] = useState(value || []);
	const [filterSections, setFilterSections] = useState([{ field_name: '', field_type: 'String', value: '' }]);
	const [isOpen, setIsOpen] = useState(false);

	useEffect(() => {
		setFilters(value || []);
	}, [value]);

	const handleInputChange = (index, field, inputValue) => {
		const updatedSections = [...filterSections];
		updatedSections[index] = { ...updatedSections[index], [field]: inputValue };
		setFilterSections(updatedSections);
	};

	const handleAddFilter = (index) => {
		const filterToAdd = filterSections[index];

		// Only add if both field_name and value are provided
		if (filterToAdd.field_name && filterToAdd.value && filterToAdd.field_type) {
			const updatedFilters = [...filters, { field_name: filterToAdd.field_name, field_type: filterToAdd.field_type, value: filterToAdd.value }];
			setFilters(updatedFilters);
			onChange({ target: { value: updatedFilters } });

			// Reset this section
			const updatedSections = [...filterSections];
			updatedSections[index] = { field_name: '', field_type: 'String', value: '' };
			setFilterSections(updatedSections);
		}
	};

	const handleAddFilterSection = () => {
		setFilterSections([...filterSections, { field_name: '', field_type: 'String', value: '' }]);
	};

	const handleRemoveFilterSection = (index) => {
		if (filterSections.length > 1) {
			const updatedSections = filterSections.filter((_, i) => i !== index);
			setFilterSections(updatedSections);
		}
	};

	const handleRemoveFilter = (index) => {
		const updatedFilters = filters.filter((_, i) => i !== index);
		setFilters(updatedFilters);
		onChange({ target: { value: updatedFilters } });
	};

	const toggleFilters = () => {
		setIsOpen(!isOpen);
	};



	return (
		<FilterWrapper>
			<FilterToggle onClick={toggleFilters}>
				필터 {isOpen ? '▲' : '▼'}
			</FilterToggle>

			{isOpen && (
				<>

					{filters.length > 0 && (
						<FilterSection>
							{filters.map((filter, index) => (
								<FilterItem key={index}>
									<FilterName>{filter.field_name}:</FilterName>
									<FilterValue>{filter.value}</FilterValue>
									<RemoveButton onClick={() => handleRemoveFilter(index)}>×</RemoveButton>
								</FilterItem>
							))}
						</FilterSection>
					)}

					{filterSections.map((section, index) => (
						<FilterInputSection key={index}>
							<InputLabel>속성 이름</InputLabel>
							<TextInput
								type="text"
								width="150px"
								placeholder="속성 이름 입력"
								value={section.field_name}
								onChange={(e) => handleInputChange(index, 'field_name', e.target.value)}
							/>

							<InputLabel>속성 유형</InputLabel>
							<SelectInput
								value={section.field_type}
								onChange={(e) => handleInputChange(index, 'field_type', e.target.value)}
							>
								{opInputType.map((data, index) => (
									<option key={index} value={data.value}>
										{data.name}
									</option>
								))}
							</SelectInput>

							<InputLabel>속성 값</InputLabel>
							<TextInputWithHelp
								type="text"
								width="300px"
								placeholder="속성 값 입력"
								value={section.value}
								onChange={(e) => handleInputChange(index, 'value', e.target.value)}
								helpText="여러개의 값 예시> (1011|1012|1013)"
							/>

							<AddButton onClick={() => handleAddFilter(index)}>추가</AddButton>

							{filterSections.length > 1 && (
								<RemoveButton onClick={() => handleRemoveFilterSection(index)}>×</RemoveButton>
							)}
						</FilterInputSection>
					))}

					{/*<AddFilterButton onClick={handleAddFilterSection}>*/}
					{/*	필터 추가*/}
					{/*</AddFilterButton>*/}
				</>
			)}
		</FilterWrapper>
	);
};

export default SearchFilter;

const TextInputWrapper = styled.div`
    position: relative;
    display: inline-block;
`;

const HelpText = styled.div`
    font-size: 11px;
    color: #888;
    position: absolute;
    left: 0;
    width: 100%;
    text-align: left;
    padding-top: 2px;
    line-height: 1.2;
    white-space: nowrap;
`;

const FilterWrapper = styled.div`
    width: 100%;
    margin-bottom: 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    overflow: hidden;
`;

const FilterToggle = styled.div`
    width: 100%;
    padding: 10px 15px;
    cursor: pointer;
    font-weight: 500;
    border-bottom: 1px solid #ddd;
    display: flex;
    justify-content: space-between;
    align-items: center;

    &:hover {
        background: #e5e5e5;
    }
`;

const FilterSection = styled.div`
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin: 15px;
`;

const FilterItem = styled.div`
    display: flex;
    align-items: center;
    background: #f0f0f0;
    border-radius: 4px;
    padding: 6px 10px;
    font-size: 13px;
`;

const FilterName = styled.span`
    font-weight: 500;
    margin-right: 5px;
`;

const FilterValue = styled.span`
    color: #333;
`;

const RemoveButton = styled.button.attrs({
	type: 'button'
})`
    background: none;
    border: none;
    color: #888;
    font-size: 16px;
    cursor: pointer;
    margin-left: 8px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
        color: #ff4d4f;
    }
`;

const AddButton = styled.button.attrs({
	type: 'button'
})`
    background: #1890ff;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 6px 12px;
    cursor: pointer;
    font-size: 13px;

    &:hover {
        background: #40a9ff;
    }
`;

const FilterInputSection = styled.div`
    display: flex;
    padding: 15px;
    margin: 0 15px 15px;
    border-radius: 6px;
    gap: 10px;
    align-items: center;

    ${TextInput} {
        margin-right: 5px;
    }
`;

const AddFilterButton = styled.button.attrs({
	type: 'button'
})`
    border: 1px dashed #ccc;
    border-radius: 4px;
    padding: 8px 15px;
    margin: 0 15px 15px;
    cursor: pointer;
    font-size: 13px;
    width: calc(100% - 30px);
    text-align: center;

    &:hover {
        background: #e5e5e5;
    }
`;