import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Typography, Tag, Space, Spin, Button, Empty, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { getAllSparepart } from '../../../../api/sparepart';
import { addSparepartToBrand, removeSparepartFromBrand } from '../../../../api/master-brand';
import CustomSparepartCard from './CustomSparepartCard';

const { Text, Title } = Typography;

const SparepartCardSelect = ({
    selectedSparepartIds = [],
    onSparepartChange,
    isLoading: externalLoading = false,
    isReadOnly = false,
    brandId = null
}) => {
    const [spareparts, setSpareparts] = useState([]);
    const [loading, setLoading] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');

    useEffect(() => {
        loadSpareparts();
    }, []);

    const loadSpareparts = async () => {
        setLoading(true);
        try {
            const params = new URLSearchParams();
            params.set('limit', '1000'); // Get all spareparts

            const response = await getAllSparepart(params);
            if (response && (response.statusCode === 200 || response.data)) {
                const sparepartData = response.data?.data || response.data || [];
                setSpareparts(sparepartData);
            } else {
                // For demo purposes, use mock data if API fails
                setSpareparts([
                    { 
                        sparepart_id: 1, 
                        sparepart_name: 'Compressor Oil Filter', 
                        sparepart_description: 'Oil filter for compressor',
                        sparepart_foto: null,
                        sparepart_code: 'SP-001',
                        sparepart_merk: 'Brand A',
                        sparepart_model: 'Model X'
                    },
                    { 
                        sparepart_id: 2, 
                        sparepart_name: 'Air Intake Filter', 
                        sparepart_description: 'Air intake filter',
                        sparepart_foto: null,
                        sparepart_code: 'SP-002',
                        sparepart_merk: 'Brand B',
                        sparepart_model: 'Model Y'
                    },
                    { 
                        sparepart_id: 3, 
                        sparepart_name: 'Cooling Fan Motor', 
                        sparepart_description: 'Motor for cooling fan',
                        sparepart_foto: null,
                        sparepart_code: 'SP-003',
                        sparepart_merk: 'Brand C',
                        sparepart_model: 'Model Z'
                    },
                ]);
            }
        } catch (error) {
            // Default mock data
            setSpareparts([
                { 
                    sparepart_id: 1, 
                    sparepart_name: 'Compressor Oil Filter', 
                    sparepart_description: 'Oil filter for compressor',
                    sparepart_foto: null,
                    sparepart_code: 'SP-001',
                    sparepart_merk: 'Brand A',
                    sparepart_model: 'Model X'
                },
                { 
                    sparepart_id: 2, 
                    sparepart_name: 'Air Intake Filter', 
                    sparepart_description: 'Air intake filter',
                    sparepart_foto: null,
                    sparepart_code: 'SP-002',
                    sparepart_merk: 'Brand B',
                    sparepart_model: 'Model Y'
                },
                { 
                    sparepart_id: 3, 
                    sparepart_name: 'Cooling Fan Motor', 
                    sparepart_description: 'Motor for cooling fan',
                    sparepart_foto: null,
                    sparepart_code: 'SP-003',
                    sparepart_merk: 'Brand C',
                    sparepart_model: 'Model Z'
                },
            ]);
        } finally {
            setLoading(false);
        }
    };

    const filteredSpareparts = spareparts.filter(sp => 
        sp.sparepart_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        sp.sparepart_code.toLowerCase().includes(searchTerm.toLowerCase()) ||
        sp.sparepart_merk?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        sp.sparepart_model?.toLowerCase().includes(searchTerm.toLowerCase())
    );

    const handleSparepartToggle = async (sparepartId) => {
        if (isReadOnly) return;

        const isCurrentlySelected = selectedSparepartIds.includes(sparepartId);

        // If brandId is provided, save immediately to database
        if (brandId) {
            try {
                setLoading(true);

                if (isCurrentlySelected) {
                    // Remove from database
                    await removeSparepartFromBrand(brandId, sparepartId);
                    message.success('Sparepart removed from brand successfully');
                } else {
                    // Add to database
                    await addSparepartToBrand(brandId, sparepartId);
                    message.success('Sparepart added to brand successfully');
                }

                // Update local state
                const newSelectedIds = isCurrentlySelected
                    ? selectedSparepartIds.filter(id => id !== sparepartId)
                    : [...selectedSparepartIds, sparepartId];

                onSparepartChange(newSelectedIds);
            } catch (error) {
                message.error(error.message || 'Failed to update sparepart');
            } finally {
                setLoading(false);
            }
        } else {
            // If no brandId (add mode), just update local state
            const newSelectedIds = isCurrentlySelected
                ? selectedSparepartIds.filter(id => id !== sparepartId)
                : [...selectedSparepartIds, sparepartId];

            onSparepartChange(newSelectedIds);
        }
    };

    const isSelected = (sparepartId) => selectedSparepartIds.includes(sparepartId);

    const combinedLoading = loading || externalLoading;

    return (
        <div>
            <div style={{ marginBottom: 16 }}>
                <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                    <Title level={5} style={{ margin: 0 }}>
                        Select Spareparts
                    </Title>
                    <div style={{ position: 'relative', width: '200px' }}>
                        <input
                            type="text"
                            placeholder="Search spareparts..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            style={{
                                padding: '8px 30px 8px 12px',
                                border: '1px solid #d9d9d9',
                                borderRadius: '6px',
                                width: '100%'
                            }}
                        />
                        <SearchOutlined 
                            style={{ 
                                position: 'absolute', 
                                right: '10px', 
                                top: '50%', 
                                transform: 'translateY(-50%)',
                                color: '#bfbfbf' 
                            }} 
                        />
                    </div>
                </Space>
            </div>

            {combinedLoading ? (
                <div style={{ textAlign: 'center', padding: '40px' }}>
                    <Spin size="large" />
                </div>
            ) : filteredSpareparts.length === 0 ? (
                <Empty 
                    description="No spareparts found" 
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                />
            ) : (
                <Row gutter={[16, 16]}>
                    {filteredSpareparts.map(sparepart => (
                        <Col xs={24} sm={12} md={12} lg={12} key={sparepart.sparepart_id}>
                            <CustomSparepartCard
                                sparepart={sparepart}
                                isSelected={isSelected(sparepart.sparepart_id)}
                                isReadOnly={isReadOnly}
                                showPreview={true}
                                showDelete={true}
                                onCardClick={() => handleSparepartToggle(sparepart.sparepart_id)}
                                onDelete={() => {
                                    // When delete button is clicked, remove from selection
                                    const newSelectedIds = selectedSparepartIds.filter(id => id !== sparepart.sparepart_id);
                                    onSparepartChange(newSelectedIds);

                                    // Also remove from database if brandId exists
                                    if (brandId) {
                                        removeSparepartFromBrand(brandId, sparepart.sparepart_id)
                                            .then(() => message.success('Sparepart removed successfully'))
                                            .catch(error => message.error(error.message || 'Failed to remove sparepart'));
                                    }
                                }}
                            />
                        </Col>
                    ))}
                </Row>
            )}
            
            {selectedSparepartIds.length > 0 && (
                <div style={{ marginTop: 16 }}>
                    <Text strong>Selected Spareparts: </Text>
                    <Space wrap>
                        {selectedSparepartIds.map(id => {
                            const sparepart = spareparts.find(sp => sp.sparepart_id === id);
                            return sparepart ? (
                                <Tag key={id} color="green">
                                    {sparepart.sparepart_name} (ID: {id})
                                </Tag>
                            ) : (
                                <Tag key={id} color="green">
                                    Sparepart ID: {id}
                                </Tag>
                            );
                        })}
                    </Space>
                </div>
            )}
        </div>
    );
};

export default SparepartCardSelect;