import React, { memo, useState, useEffect } from 'react';
import { Button, Col, Row, Space, Input, ConfigProvider, Card, Tag, Spin, Modal, Form, Typography } from 'antd';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    SearchOutlined,
    EyeOutlined,
    SolutionOutlined,
    ToolOutlined,
} from '@ant-design/icons';
import { NotifAlert, NotifConfirmDialog, NotifOk } from '../../../../components/Global/ToastNotif';
import TableList from '../../../../components/Global/TableList';

const { Title } = Typography;

const columns = (onView, onEdit, onDelete) => [
    {
        title: 'No',
        key: 'no',
        width: '5%',
        align: 'center',
        render: (_, __, index) => index + 1,
    },
    {
        title: 'Error Code',
        dataIndex: 'error_code',
        key: 'error_code',
        width: '15%',
        render: (text, record) => (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                {record.path_icon && (
                    <img
                        src={record.path_icon}
                        alt="icon"
                        style={{ width: 24, height: 24, objectFit: 'cover' }}
                    />
                )}
                <span style={{
                    color: record.error_code_color || '#000000',
                    fontWeight: 'bold'
                }}>
                    {text}
                </span>
            </div>
        ),
    },
    {
        title: 'Error Name',
        dataIndex: 'error_code_name',
        key: 'error_code_name',
        width: '25%',
    },
    {
        title: 'Description',
        dataIndex: 'error_code_description',
        key: 'error_code_description',
        width: '20%',
        render: (text) => text || '-',
        ellipsis: true,
    },
    {
        title: 'Solutions',
        key: 'solutions_count',
        width: '10%',
        align: 'center',
        render: (_, record) => (
            <Tag color="blue">
                {record.solution ? record.solution.length : 0} Solutions
            </Tag>
        ),
    },
    {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
        width: '12%',
        align: 'center',
        render: (_, record) => {
            const statusColor = record.is_active ? 'green' : 'red';
            const statusText = record.is_active ? 'Active' : 'Inactive';

            // Show modification status if applicable
            if (record.status === 'new') {
                return (
                    <Space direction="vertical" size={2}>
                        <Tag color="blue" style={{ margin: 0 }}>NEW</Tag>
                        <Tag color={statusColor} style={{ margin: 0 }}>{statusText}</Tag>
                    </Space>
                );
            } else if (record.status === 'modified') {
                return (
                    <Space direction="vertical" size={2}>
                        <Tag color="orange" style={{ margin: 0 }}>MODIFIED</Tag>
                        <Tag color={statusColor} style={{ margin: 0 }}>{statusText}</Tag>
                    </Space>
                );
            } else if (record.status === 'deleted') {
                return (
                    <Space direction="vertical" size={2}>
                        <Tag color="red" style={{ margin: 0 }}>DELETED</Tag>
                        <Tag color="default" style={{ margin: 0 }}>Inactive</Tag>
                    </Space>
                );
            } else {
                return (
                    <Tag color={statusColor}>
                        {statusText}
                    </Tag>
                );
            }
        },
    },
    {
        title: 'Action',
        key: 'action',
        align: 'center',
        width: '15%',
        render: (_, record) => (
            <Space size="small">
                <Button
                    icon={<EyeOutlined />}
                    onClick={() => onView(record)}
                    size="small"
                    style={{
                        color: '#1890ff',
                        borderColor: '#1890ff',
                    }}
                    title="View Details"
                />
                <Button
                    icon={<EditOutlined />}
                    onClick={() => onEdit(record)}
                    size="small"
                    style={{
                        color: '#faad14',
                        borderColor: '#faad14',
                    }}
                    title="Edit Error Code"
                />
                <Button
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => onDelete(record)}
                    size="small"
                    title="Delete Error Code"
                />
            </Space>
        ),
    },
];

const ErrorCodeTable = memo(function ErrorCodeTable({
    errorCodes = [],
    loading = false,
    brandId,
    onAddErrorCode,
    onEditErrorCode,
    onDeleteErrorCode,
    onViewErrorCode,
    trigger,
}) {
    const [trigerFilter, setTrigerFilter] = useState(false);
    const [formDataFilter, setFormDataFilter] = useState({ search: '' });
    const [searchValue, setSearchValue] = useState('');

    // Trigger table refresh when parent component data changes
    useEffect(() => {
        if (trigger !== undefined) {
            setTrigerFilter(prev => !prev);
        }
    }, [trigger]);

    // Simulate API data for error codes
    const getErrorCodesData = async (params) => {
        console.log('📋 ErrorCodeTable getErrorCodesData called with:', params);
        console.log('📋 Available errorCodes:', errorCodes);

        // This would be your actual API call
        const filteredData = errorCodes.filter(code =>
            !params.search ||
            code.error_code.toLowerCase().includes(params.search.toLowerCase()) ||
            code.error_code_name.toLowerCase().includes(params.search.toLowerCase())
        );

        console.log('📋 Filtered result:', filteredData);

        return {
            data: filteredData,
            total: filteredData.length,
        };
    };

    const handleSearch = () => {
        setFormDataFilter({ search: searchValue });
        setTrigerFilter(prev => !prev);
    };

    const handleSearchClear = () => {
        setSearchValue('');
        setFormDataFilter({ search: '' });
        setTrigerFilter(prev => !prev);
    };

    
    
    return (
        <Card
            title="Error Codes"
            size="small"
        >
            <Row>
                <Col xs={24}>
                    <Row justify="space-between" align="middle" gutter={[8, 8]}>
                        <Col xs={24} sm={24} md={16} lg={18}>
                            <Input.Search
                                placeholder="Search error code..."
                                value={searchValue}
                                onChange={(e) => {
                                    const value = e.target.value;
                                    setSearchValue(value);
                                    if (value === '') {
                                        setFormDataFilter({ search: '' });
                                        setTrigerFilter(prev => !prev);
                                    }
                                }}
                                onSearch={handleSearch}
                                allowClear={{
                                    clearIcon: <span onClick={handleSearchClear}>✕</span>,
                                }}
                                enterButton={
                                    <Button
                                        type="primary"
                                        icon={<SearchOutlined />}
                                        style={{
                                            backgroundColor: '#23A55A',
                                            borderColor: '#23A55A',
                                        }}
                                    >
                                        Search
                                    </Button>
                                }
                                size="large"
                                style={{ marginBottom: 16 }}
                            />
                        </Col>
                        <Col>
                            <ConfigProvider
                                theme={{
                                    token: { colorBgContainer: '#E9F6EF' },
                                    components: {
                                        Button: {
                                            defaultBg: 'white',
                                            defaultColor: '#23A55A',
                                            defaultBorderColor: '#23A55A',
                                            defaultHoverColor: '#23A55A',
                                            defaultHoverBorderColor: '#23A55A',
                                        },
                                    },
                                }}
                            >
                                <Button
                                    icon={<PlusOutlined />}
                                    onClick={onAddErrorCode}
                                    size="large"
                                >
                                    Add Error Code
                                </Button>
                            </ConfigProvider>
                        </Col>
                    </Row>
                </Col>
                <Col xs={24}>
                    <TableList
                        mobile
                        cardColor={'#42AAFF'}
                        header={'error_code_name'}
                        showPreviewModal={onViewErrorCode}
                        showEditModal={onEditErrorCode}
                        showDeleteDialog={onDeleteErrorCode}
                        getData={getErrorCodesData}
                        queryParams={formDataFilter}
                        columns={columns(
                            onViewErrorCode,
                            onEditErrorCode,
                            onDeleteErrorCode
                        )}
                        triger={trigerFilter}
                        loading={loading}
                    />
                </Col>
            </Row>
        </Card>
    );
});

export default ErrorCodeTable;