import React, { memo, useState, useEffect } from 'react';
import { Space, ConfigProvider, Button, Row, Col, Card, Input } from 'antd';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    EyeOutlined,
    SearchOutlined,
} from '@ant-design/icons';
import { NotifAlert, NotifConfirmDialog } from '../../../components/Global/ToastNotif';
import { useNavigate } from 'react-router-dom';
import TableList from '../../../components/Global/TableList';

// Dummy data
const initialRolesData = [
    {
        role_id: 1,
        role_name: 'Administrator',
        role_level: 1,
        role_description: 'tes administrator',
    },
    {
        role_id: 2,
        role_name: 'Operator',
        role_level: 2,
        role_description: 'tes operator',
    },
    {
        role_id: 3,
        role_name: 'Engineer',
        role_level: 2,
        role_description: 'tes engineer',
    },
    {
        role_id: 4,
        role_name: 'Operator',
        role_level: 3,
        role_description: 'tes operator',
    },
    {
        role_id: 5,
        role_name: 'Administrator',
        role_level: 1,
        role_description: 'tes administrator',
    },
    {
        role_id: 6,
        role_name: 'Guest',
        role_level: 3,
        role_description: 'tes guest',
    },
    {
        role_id: 7,
        role_name: 'Engineering',
        role_level: 2,
        role_description: 'tes engineering',
    },
];

const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
    {
        title: 'No',
        key: 'no',
        width: '5%',
        align: 'center',
        render: (_, __, index) => index + 1,
    },
    {
        title: 'Nama Role',
        dataIndex: 'role_name',
        key: 'role_name',
        width: '20%',
    },
    {
        title: 'Level',
        dataIndex: 'role_level',
        key: 'role_level',
        width: '10%',
        align: 'center',
    },
    {
        title: 'Deskripsi',
        dataIndex: 'role_description',
        key: 'role_description',
        width: '40%',
    },
    {
        title: 'Aksi',
        key: 'aksi',
        align: 'center',
        width: '15%',
        render: (_, record) => (
            <Space>
                <Button
                    icon={<EyeOutlined />}
                    onClick={() => showPreviewModal(record)}
                    style={{
                        color: '#1890ff',
                        borderColor: '#1890ff',
                    }}
                />
                <Button
                    icon={<EditOutlined />}
                    onClick={() => showEditModal(record)}
                    style={{
                        color: '#faad14',
                        borderColor: '#faad14',
                    }}
                />
                <Button
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => showDeleteDialog(record)}
                    style={{
                        borderColor: '#ff4d4f',
                    }}
                />
            </Space>
        ),
    },
];

const ListRole = memo(function ListRole(props) {
    const [showFilter, setShowFilter] = useState(false);
    const [trigerFilter, setTrigerFilter] = useState(false);
    const [rolesData, setRolesData] = useState(initialRolesData);

    const defaultFilter = { search: '' };
    const [formDataFilter, setFormDataFilter] = useState(defaultFilter);
    const [searchValue, setSearchValue] = useState('');

    const navigate = useNavigate();

    // Dummy data function to simulate API call
    const getAllRole = async (params) => {
        // Simulate API delay
        await new Promise((resolve) => setTimeout(resolve, 300));

        // Extract URLSearchParams
        const searchParam = params.get('search') || '';
        const page = parseInt(params.get('page')) || 1;
        const limit = parseInt(params.get('limit')) || 10;

        console.log('getAllRole called with:', { searchParam, page, limit });

        // Filter by search
        let filteredRoles = rolesData;
        if (searchParam) {
            const searchLower = searchParam.toLowerCase();
            filteredRoles = rolesData.filter(
                (role) =>
                    role.role_name.toLowerCase().includes(searchLower) ||
                    role.role_description.toLowerCase().includes(searchLower) ||
                    role.role_level.toString().includes(searchLower)
            );
        }

        // Pagination logic
        const totalData = filteredRoles.length;
        const totalPages = Math.ceil(totalData / limit);
        const startIndex = (page - 1) * limit;
        const endIndex = startIndex + limit;
        const paginatedData = filteredRoles.slice(startIndex, endIndex);

        return {
            status: 200,
            statusCode: 200,
            data: {
                data: paginatedData,
                total: totalData,
                paging: {
                    page: page,
                    limit: limit,
                    total: totalData,
                    page_total: totalPages,
                },
            },
        };
    };

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (token) {
            if (props.actionMode == 'list') {
                setFormDataFilter(defaultFilter);
                doFilter();
            }
        } else {
            navigate('/signin');
        }
    }, [props.actionMode, rolesData]);

    const toggleFilter = () => {
        setFormDataFilter(defaultFilter);
        setShowFilter((prev) => !prev);
    };

    const doFilter = () => {
        setTrigerFilter((prev) => !prev);
    };

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

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

    const showPreviewModal = (param) => {
        props.setSelectedData(param);
        props.setActionMode('preview');
    };

    const showEditModal = (param = null) => {
        props.setSelectedData(param);
        props.setActionMode('edit');
    };

    const showAddModal = (param = null) => {
        props.setSelectedData(param);
        props.setActionMode('add');
    };

    const showDeleteDialog = (param) => {
        NotifConfirmDialog({
            icon: 'question',
            title: 'Konfirmasi',
            message: 'Apakah anda yakin hapus data "' + param.role_name + '" ?',
            onConfirm: () => handleDelete(param.role_id),
            onCancel: () => props.setSelectedData(null),
        });
    };

    const handleDelete = async (role_id) => {
        // Find role name before deleting
        const roleToDelete = rolesData.find((role) => role.role_id === role_id);

        // Simulate delete API call
        await new Promise((resolve) => setTimeout(resolve, 300));

        // Remove from state
        const updatedRoles = rolesData.filter((role) => role.role_id !== role_id);
        setRolesData(updatedRoles);

        NotifAlert({
            icon: 'success',
            title: 'Berhasil',
            message: `Data Role "${roleToDelete?.role_name || ''}" berhasil dihapus.`,
        });
    };

    return (
        <React.Fragment>
            <Card>
                <Row>
                    <Col xs={24}>
                        <Row justify="space-between" align="middle" gutter={[8, 8]}>
                            <Col xs={24} sm={24} md={12} lg={12}>
                                <Input.Search
                                    placeholder="Search role by name, level, or description..."
                                    value={searchValue}
                                    onChange={(e) => {
                                        const value = e.target.value;
                                        setSearchValue(value);
                                        // Auto search when clearing by backspace/delete
                                        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"
                                />
                            </Col>
                            <Col>
                                <Space wrap size="small">
                                    <ConfigProvider
                                        theme={{
                                            token: { colorBgContainer: '#E9F6EF' },
                                            components: {
                                                Button: {
                                                    defaultBg: 'white',
                                                    defaultColor: '#23A55A',
                                                    defaultBorderColor: '#23A55A',
                                                    defaultHoverColor: '#23A55A',
                                                    defaultHoverBorderColor: '#23A55A',
                                                },
                                            },
                                        }}
                                    >
                                        <Button
                                            icon={<PlusOutlined />}
                                            onClick={() => showAddModal()}
                                            size="large"
                                        >
                                            Tambah Data
                                        </Button>
                                    </ConfigProvider>
                                </Space>
                            </Col>
                        </Row>
                    </Col>
                    <Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginTop: '16px' }}>
                        <TableList
                            getData={getAllRole}
                            queryParams={formDataFilter}
                            columns={columns(showPreviewModal, showEditModal, showDeleteDialog)}
                            triger={trigerFilter}
                        />
                    </Col>
                </Row>
            </Card>
        </React.Fragment>
    );
});

export default ListRole;
