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: number[];
    onChange: (attributeId: number, values: number[]) => void;
}

const AttributeSelector: FC<AttributeSelectorProps> = ({ attribute, selectedValues, onChange }) => {
    const handleValueChange = (valueId: number, 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 isChecked = selectedValues.includes(value._id);

                    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(value._id, 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>
    );
};

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

// کامپوننت مدیریت تگ‌ها
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 }) => {
    const [formData, setFormData] = useState<Omit<CreateProductAttributeRequestType, 'productId'>>({
        attributes: [],
        description: '',
        metaDescription: '',
        tags: [],
        advantages: [],
        disAdvantages: []
    });

    useEffect(() => {
        if (initialData) {
            setFormData(prev => ({ ...prev, ...initialData }));
        }
    }, [initialData]);

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

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

    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 || [];

                        return (
                            <AttributeSelector
                                key={attribute._id}
                                attribute={attribute}
                                selectedValues={selectedValues}
                                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;
