import React, { useState } from 'react';
import { Form, Card, Typography, Divider, Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import SparepartField from './SparepartField';

const { Text } = Typography;

const SparepartForm = ({
    sparepartForm,
    sparepartFields,
    onAddSparepartField,
    onRemoveSparepartField,
    isReadOnly = false,
    spareparts = [],
    onSparepartChange
}) => {
    const [sparepartList, setSparepartList] = useState([]);

    const handleSparepartChange = (list) => {
        setSparepartList(list);
        if (onSparepartChange) {
            onSparepartChange(list);
        }
    };

    return (
        <div>
            <Form
                form={sparepartForm}
                layout="vertical"
                initialValues={{
                    sparepart_status_0: true,
                }}
            >
                <Divider orientation="left">Sparepart Items</Divider>

                {sparepartFields.map((field, index) => (
                    <SparepartField
                        key={field.key}
                        fieldKey={field.key}
                        fieldName={field.name}
                        index={index}
                        sparepartStatus={field.status}
                        onRemove={() => onRemoveSparepartField(field.key)}
                        isReadOnly={isReadOnly}
                        canRemove={sparepartFields.length > 1}
                        spareparts={sparepartList}
                        onSparepartChange={handleSparepartChange}
                    />
                ))}

                {!isReadOnly && (
                    <>
                        <Form.Item>
                            <Button
                                type="dashed"
                                onClick={onAddSparepartField}
                                icon={<PlusOutlined />}
                                style={{ width: '100%' }}
                            >
                                + Add Sparepart
                            </Button>
                        </Form.Item>
                        <div style={{ marginTop: 16 }}>
                            <Text type="secondary">
                                * Sparepart is optional and can be added for each error code if needed.
                            </Text>
                        </div>
                    </>
                )}
            </Form>
        </div>
    );
};

export default SparepartForm;