import { useState } from 'react';

interface Meta {
    id: number;
    key: string;
    amount: number;
}

interface MetaFormProps {
    meta: Meta[];
    setMeta: React.Dispatch<React.SetStateAction<Meta[]>>;
    order_status: string;
}

const MetaForm: React.FC<MetaFormProps> = ({ meta, setMeta, order_status }) => {
    const selectMeta = ['point', 'extra_discount', 'unique_code', 'fee', 'tax', 'birthday_extra'];
    const addMeta = () => {
        let maxId = 0;
        maxId = meta?.length ? meta.reduce((max: number, character: any) => (character.id > max ? character.id : max), meta[0].id) : 0;

        setMeta([
            ...meta,
            {
                id: maxId + 1,
                key: '',
                amount: 0,
            },
        ]);
    };
    const removeMeta = (item: any = null) => {
        setMeta(meta.filter((d: any) => d.id !== item.id));
    };

    const changeMetaValue = (type: string, value: string, id: number) => {
        const updatedMeta = meta.map((metaItem) => {
            if (metaItem.id === id) {
                const updatedMeta = {
                    ...metaItem,
                    [type === 'key' ? 'key' : 'amount']: type === 'key' ? value : Number(value),
                };

                if (type === 'key' && value === '') {
                    updatedMeta.amount = 0; // Set amount to 0 if coupon_name is empty
                }

                return updatedMeta;
            }
            return metaItem;
        });

        setMeta(updatedMeta);
    };
    return (
        <>
            {meta.length > 0 && (
                <div className="m-2 rounded-md border border-white-light py-4 dark:border-[#1b2e4b]">
                    <div className="ms-4">
                        <label htmlFor="shipping_method" className="mb-0 font-bold uppercase ltr:mr-2 rtl:ml-2">
                            Meta Item
                        </label>
                    </div>

                    {meta.map((item: any) => (
                        <div className="ms-4 mt-2 " key={item.key}>
                            <div className="flex items-center">
                                <div className="mr-4  w-1/4">
                                    <label htmlFor="">meta name</label>
                                    <select
                                        id="key"
                                        name="meta"
                                        disabled={order_status !== 'Processing'}
                                        className={`form-select   ${meta.some((d) => d.id !== item.id && d.key === item.key) ? 'border-2 !border-rose-400' : ''}`}
                                        value={item.key}
                                        onChange={(e) => changeMetaValue('key', e.target.value, item.id)}
                                    >
                                        <option key="" value="">
                                            Select Meta
                                        </option>
                                        {selectMeta.map((i) => (
                                            <option key={i} value={i}>
                                                {i}
                                            </option>
                                        ))}
                                    </select>
                                </div>
                                <div className="mr-4">
                                    <label htmlFor="">meta amount</label>
                                    <input
                                        type="number"
                                        disabled={!item.key || order_status !== 'Processing'}
                                        className="form-input flex-1"
                                        value={item.amount}
                                        onChange={(e) => changeMetaValue('meta_amount', e.target.value, item.id)}
                                    />
                                </div>

                                <div>
                                    {order_status === 'Processing' && (
                                        <button className="mt-4" type="button" onClick={() => removeMeta(item)}>
                                            <svg
                                                xmlns="http://www.w3.org/2000/svg"
                                                width="20"
                                                height="20"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                            >
                                                <line x1="18" y1="6" x2="6" y2="18"></line>
                                                <line x1="6" y1="6" x2="18" y2="18"></line>
                                            </svg>
                                        </button>
                                    )}
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
            {order_status === 'Processing' && (
                <div className="m-4">
                    <button type="button" className="btn btn-outline-warning btn-sm mt-4" onClick={() => addMeta()}>
                        Add Meta
                    </button>
                </div>
            )}
        </>
    );
};
export default MetaForm;
