import { type FC, useState, useEffect } from 'react';
import Button from '../../../components/Button';
import Input from '../../../components/Input';
import Textarea from '../../../components/Textarea';
import { useGetCategoryAttributes } from '../../category/hooks/useCategoryData';
import { type CreateProductAttributeRequestType } from '../types/Types';
import { type CategoryAttributeType } from '../../category/types/Types';
import { CloseCircle } from 'iconsax-react';

interface AttributeSelectorProps {
    attribute: CategoryAttributeType;
    selectedValues: string[];
    onChange: (attributeId: number, values: string[]) => void;
}

interface TextNumberInputProps {
    attribute: CategoryAttributeType;
    value: string;
    onChange: (attributeId: number, value: string) => void;
}

const AttributeSelector: FC<AttributeSelectorProps> = ({ attribute, selectedValues, onChange }) => {
    const handleValueChange = (valueId: string, checked: boolean) => {
        if (attribute.multiple) {
            // چند انتخابی - checkbox
            const newValues = checked
                ? [...selectedValues, valueId]
                : selectedValues.filter(id => id !== valueId);
            onChange(attribute._id, newValues);
        } else {
            // تک انتخابی - radio
            onChange(attribute._id, checked ? [valueId] : []);
        }
    };

    return (
        <div className="mb-6 p-4 border border-gray-200 rounded-lg bg-gray-50">
            <h3 className="text-sm font-semibold text-gray-800 mb-2">
                {attribute.title}
                {attribute.required && <span className="text-red-500 mr-1">*</span>}
            </h3>

            {attribute.hint && (
                <p className="text-xs text-gray-500 mb-3">{attribute.hint}</p>
            )}

            <div className="space-y-2">
                {attribute.values.map((value) => {
                    const valueIdStr = String(value._id);
                    const isChecked = selectedValues.includes(valueIdStr) || selectedValues.includes(value.text);

                    return (
                        <label key={value._id} className="flex items-center space-x-2 cursor-pointer">
                            <input
                                type={attribute.multiple ? "checkbox" : "radio"}
                                name={`attribute-${attribute._id}`}
                                checked={isChecked}
                                onChange={(e) => handleValueChange(valueIdStr, e.target.checked)}
                                className={`w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 focus:ring-2 ${attribute.multiple ? 'rounded' : 'rounded-full'
                                    }`}
                            />
                            <span className="text-sm text-gray-700">{value.text}</span>
                        </label>
                    );
                })}
            </div>
        </div>
    );
};

const TextNumberInput: FC<TextNumberInputProps> = ({ attribute, value, onChange }) => {
    if (attribute.type === 'boolean') {
        return (
            <div className="mb-6 p-4 border border-gray-200 rounded-lg bg-gray-50">
                <label className="block text-sm font-semibold text-gray-800 mb-2">
                    {attribute.title}
                    {attribute.required && <span className="text-red-500 mr-1">*</span>}
                </label>

                {attribute.hint && (
                    <p className="text-xs text-gray-500 mb-3">{attribute.hint}</p>
                )}

                <div className="flex items-center space-x-2">
                    <input
                        type="checkbox"
                        checked={value === 'true'}
                        onChange={(e) => onChange(attribute._id, e.target.checked ? 'true' : 'false')}
                        className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 focus:ring-2"
                    />
                    <span className="text-sm text-gray-700">بله</span>
                </div>
            </div>
        );
    }

    return (
        <div className="mb-6 p-4 border border-gray-200 rounded-lg bg-gray-50">
            <label className="block text-sm font-semibold text-gray-800 mb-2">
                {attribute.title}
                {attribute.required && <span className="text-red-500 mr-1">*</span>}
            </label>

            {attribute.hint && (
                <p className="text-xs text-gray-500 mb-3">{attribute.hint}</p>
            )}

            <Input
                type={attribute.type === 'number' ? 'number' : 'text'}
                value={value}
                onChange={(e) => onChange(attribute._id, e.target.value)}
                placeholder={`مقدار ${attribute.title} را وارد کنید`}
                className="w-full"
                required={attribute.required}
            />
        </div>
    );
};

interface Step2FormProps {
    onSubmit: (data: Omit<CreateProductAttributeRequestType, 'productId'>) => void;
    loading: boolean;
    onPrevious: () => void;
    categoryId?: string;
    initialData?: Partial<Omit<CreateProductAttributeRequestType, 'productId'>>;
    specifications?: Array<{ title: string; values: string[] }>;
}

interface AttributeWithValue {
    id: number;
    values: string[];
}

// کامپوننت مدیریت تگ‌ها
interface TagInputProps {
    tags: string[];
    onChange: (tags: string[]) => void;
    placeholder?: string;
}

const TagInput: FC<TagInputProps> = ({ tags, onChange, placeholder }) => {
    const [inputValue, setInputValue] = useState('');

    const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter' || e.key === ',') {
            e.preventDefault();
            const newTag = inputValue.trim();
            if (newTag && !tags.includes(newTag)) {
                onChange([...tags, newTag]);
                setInputValue('');
            }
        }
    };

    const removeTag = (tagToRemove: string) => {
        onChange(tags.filter(tag => tag !== tagToRemove));
    };

    return (
        <div className="space-y-2">
            <div className="flex flex-wrap gap-2 min-h-[40px] p-2 border border-gray-300 rounded-md focus-within:border-blue-500">
                {tags.map((tag, index) => (
                    <span
                        key={index}
                        className="inline-flex items-center gap-1 px-2 py-1 bg-blue-100 text-blue-800 text-sm rounded-full"
                    >
                        {tag}
                        <button
                            type="button"
                            onClick={() => removeTag(tag)}
                            className="hover:bg-blue-200 rounded-full p-0.5"
                        >
                            <CloseCircle size={14} color='red' />
                        </button>
                    </span>
                ))}
                <input
                    type="text"
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder={tags.length === 0 ? placeholder : ''}
                    className="flex-1 min-w-[120px] outline-none bg-transparent text-sm"
                />
            </div>
            <p className="text-xs text-gray-500">برای افزودن تگ، تایپ کنید و Enter یا کاما بزنید</p>
        </div>
    );
};

// کامپوننت مدیریت لیست مزایا/معایب
// interface ListInputProps {
//     items: string[];
//     onChange: (items: string[]) => void;
//     placeholder?: string;
//     label: string;
// }

// const ListInput: FC<ListInputProps> = ({ items, onChange, placeholder, label }) => {
//     const [inputValue, setInputValue] = useState('');

//     const addItem = () => {
//         const newItem = inputValue.trim();
//         if (newItem && !items.includes(newItem)) {
//             onChange([...items, newItem]);
//             setInputValue('');
//         }
//     };

//     const removeItem = (itemToRemove: string) => {
//         onChange(items.filter(item => item !== itemToRemove));
//     };

//     const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
//         if (e.key === 'Enter') {
//             e.preventDefault();
//             addItem();
//         }
//     };

//     return (
//         <div className="space-y-3">
//             <label className="block text-sm font-medium text-gray-700">{label}</label>
//             <div className="flex gap-2">
//                 <Input
//                     value={inputValue}
//                     onChange={(e) => setInputValue(e.target.value)}
//                     onKeyDown={handleKeyDown}
//                     placeholder={placeholder}
//                     className="flex-1"
//                 />
//                 <Button
//                     type="button"
//                     onClick={addItem}
//                     disabled={!inputValue.trim()}
//                     className="px-4 w-fit"
//                 >
//                     افزودن
//                 </Button>
//             </div>
//             {items.length > 0 && (
//                 <div className="space-y-2  flex flex-wrap gap-3 max-h-40 overflow-y-auto">
//                     {items.map((item, index) => (
//                         <div key={index} className="flex min-w-[30%] flex-1 h-10 items-center justify-between p-2 bg-gray-50 rounded-md">
//                             <span className="text-sm text-gray-700">{item}</span>
//                             <button
//                                 type="button"
//                                 onClick={() => removeItem(item)}
//                                 className="text-red-500 hover:text-red-700 p-1"
//                             >
//                                 <CloseCircle size={16} color='red' />
//                             </button>
//                         </div>
//                     ))}
//                     <div className='min-w-[30%] flex-1 px-2'></div>
//                     <div className='min-w-[30%] flex-1 px-2'></div>
//                 </div>
//             )}
//         </div>
//     );
// };

const Step2Form: FC<Step2FormProps> = ({ onSubmit, loading, onPrevious, categoryId, initialData, specifications }) => {
    const [formData, setFormData] = useState<Omit<CreateProductAttributeRequestType, 'productId'>>(() => ({
        attributes: (initialData?.attributes || []) as AttributeWithValue[],
        description: initialData?.description || '',
        metaDescription: initialData?.metaDescription || '',
        tags: initialData?.tags || [],
        // advantages: initialData?.advantages || [],
        // disAdvantages: initialData?.disAdvantages || []
        advantages: [],
        disAdvantages: []
    }));

    const { data: categoryAttributesData } = useGetCategoryAttributes(categoryId || '');

    // تبدیل specifications به attributes با استفاده از categoryAttributes
    useEffect(() => {
        if (specifications && categoryAttributesData?.results?.data?.category?.attributes) {
            const categoryAttrs = categoryAttributesData.results.data.category.attributes;
            const convertedAttributes: AttributeWithValue[] = [];

            specifications.forEach(spec => {
                // پیدا کردن attribute مربوطه از روی title
                const matchedAttr = categoryAttrs.find(attr => attr.title === spec.title);

                if (matchedAttr) {
                    // برای attributeهای انتخابی، باید value.text رو با spec.values مچ کنیم
                    if (matchedAttr.type === 'select') {
                        const matchedValueIds: string[] = [];

                        spec.values.forEach(specValue => {
                            const matchedValue = matchedAttr.values.find(v => v.text === specValue);
                            if (matchedValue) {
                                matchedValueIds.push(String(matchedValue._id));
                            }
                        });

                        if (matchedValueIds.length > 0) {
                            convertedAttributes.push({
                                id: matchedAttr._id,
                                values: matchedValueIds
                            });
                        }
                    } else {
                        // برای text، number، boolean مستقیماً مقدار رو استفاده می‌کنیم
                        convertedAttributes.push({
                            id: matchedAttr._id,
                            values: spec.values
                        });
                    }
                }
            });

            setFormData(prev => ({
                ...prev,
                attributes: convertedAttributes
            }));
        }
    }, [specifications, categoryAttributesData]);

    const handleAttributeChange = (attributeId: number, values: string[]) => {
        setFormData(prev => ({
            ...prev,
            attributes: prev.attributes.filter(attr => attr.id !== attributeId).concat({
                id: attributeId,
                values
            })
        }));
    };

    const handleTextNumberAttributeChange = (attributeId: number, value: string) => {
        setFormData(prev => ({
            ...prev,
            attributes: prev.attributes.filter(attr => attr.id !== attributeId).concat({
                id: attributeId,
                values: value ? [value] : []
            })
        }));
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        onSubmit(formData);
    };

    return (
        <form onSubmit={handleSubmit} className="space-y-6">
            {/* ویژگی‌های محصول */}
            {categoryAttributesData?.results?.data?.category?.attributes && (
                <div>
                    <h2 className="text-lg font-semibold text-gray-800 mb-4">ویژگی‌های محصول</h2>
                    {categoryAttributesData.results.data.category.attributes.map((attribute) => {
                        const selectedAttribute = formData.attributes.find(attr => attr.id === attribute._id);
                        const selectedValues = selectedAttribute?.values || [];
                        const attributeValue = selectedValues.length > 0 ? String(selectedValues[0]) : '';

                        // برای attributeهای text، number و boolean از TextNumberInput استفاده کن
                        if (attribute.type === 'text' || attribute.type === 'number' || attribute.type === 'boolean') {
                            return (
                                <TextNumberInput
                                    key={attribute._id}
                                    attribute={attribute}
                                    value={attributeValue}
                                    onChange={handleTextNumberAttributeChange}
                                />
                            );
                        }

                        // برای attributeهای انتخابی از AttributeSelector استفاده کن
                        return (
                            <AttributeSelector
                                key={attribute._id}
                                attribute={attribute}
                                selectedValues={selectedValues as string[]}
                                onChange={handleAttributeChange}
                            />
                        );
                    })}
                </div>
            )}

            <Textarea
                label="توضیحات"
                value={formData.description}
                onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                rows={4}
                required
            />

            <Textarea
                label="توضیحات متا"
                value={formData.metaDescription}
                onChange={(e) => setFormData(prev => ({ ...prev, metaDescription: e.target.value }))}
                rows={3}
                required
            />

            <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">تگ‌ها</label>
                <TagInput
                    tags={formData.tags}
                    onChange={(tags) => setFormData(prev => ({ ...prev, tags }))}
                    placeholder="تگ محصول را وارد کنید..."
                />
            </div>

            {/* <ListInput
                label="مزایا"
                items={formData.advantages}
                onChange={(advantages) => setFormData(prev => ({ ...prev, advantages }))}
                placeholder="مزیتی را وارد کنید..."
            />

            <ListInput
                label="معایب"
                items={formData.disAdvantages}
                onChange={(disAdvantages) => setFormData(prev => ({ ...prev, disAdvantages }))}
                placeholder="عیبی را وارد کنید..."
            /> */}

            <div className="flex gap-2 justify-between">
                <Button
                    type="button"
                    variant="outline"
                    onClick={onPrevious}
                >
                    مرحله قبلی
                </Button>
                <Button type="submit" isLoading={loading}>
                    مرحله بعدی
                </Button>
            </div>
        </form>
    );
};

export default Step2Form;
