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

const columns = (showPreviewModal, showEditModal, showDeleteDialog, showApproveDialog) => [
    {
        title: 'ID',
        dataIndex: 'user_id',
        key: 'user_id',
        width: '5%',
        hidden: 'true',
    },
    {
        title: 'Username',
        dataIndex: 'username',
        key: 'username',
        width: '12%',
    },
    {
        title: 'Nama Lengkap',
        dataIndex: 'fullname',
        key: 'fullname',
        width: '15%',
    },
    {
        title: 'Nomor WA',
        dataIndex: 'whatsapp_number',
        key: 'whatsapp_number',
        width: '12%',
    },
    {
        title: 'Level',
        dataIndex: 'level',
        key: 'level',
        width: '8%',
        align: 'center',
    },
    {
        title: 'Nama Role',
        dataIndex: 'role_name',
        key: 'role_name',
        width: '12%',
        render: (_, { role_name }) => (
            <>
                {role_name === 'administrator' && (
                    <Tag color={'purple'} key={'role'}>
                        Administrator
                    </Tag>
                )}
                {role_name === 'operator' && (
                    <Tag color={'blue'} key={'role'}>
                        Operator
                    </Tag>
                )}
                {role_name === 'engineer' && (
                    <Tag color={'cyan'} key={'role'}>
                        Engineer
                    </Tag>
                )}
                {role_name === 'guest' && (
                    <Tag color={'default'} key={'role'}>
                        Guest
                    </Tag>
                )}
            </>
        ),
    },
    {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
        width: '10%',
        align: 'center',
        render: (_, { status }) => (
            <>
                {status === 'active' && (
                    <Tag color={'green'} key={'status'}>
                        Active
                    </Tag>
                )}
                {status === 'pending' && (
                    <Tag color={'orange'} key={'status'}>
                        Pending
                    </Tag>
                )}
                {status === 'inactive' && (
                    <Tag color={'default'} key={'status'}>
                        Inactive
                    </Tag>
                )}
                {status === 'rejected' && (
                    <Tag color={'red'} key={'status'}>
                        Rejected
                    </Tag>
                )}
            </>
        ),
    },
    {
        title: 'Aksi',
        key: 'aksi',
        align: 'center',
        width: '15%',
        render: (_, record) => (
            <Space>
                <Button
                    type="text"
                    style={{ borderColor: '#1890ff' }}
                    icon={<EyeOutlined style={{ color: '#1890ff' }} />}
                    onClick={() => showPreviewModal(record)}
                />
                {record.status === 'pending' && (
                    <Button
                        type="text"
                        style={{ borderColor: '#52c41a' }}
                        icon={<CheckOutlined style={{ color: '#52c41a' }} />}
                        onClick={() => showApproveDialog(record)}
                    />
                )}
                <Button
                    type="text"
                    style={{ borderColor: '#faad14' }}
                    icon={<EditOutlined style={{ color: '#faad14' }} />}
                    onClick={() => showEditModal(record)}
                />
                <Button
                    type="text"
                    danger
                    style={{ borderColor: 'red' }}
                    icon={<DeleteOutlined />}
                    onClick={() => showDeleteDialog(record)}
                />
            </Space>
        ),
    },
];

const ListUser = memo(function ListUser(props) {
    const [showFilter, setShowFilter] = useState(false);
    const [trigerFilter, setTrigerFilter] = useState(false);

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

    const navigate = useNavigate();

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

    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 showApproveDialog = (param) => {
        NotifConfirmDialog({
            icon: 'question',
            title: 'Konfirmasi Approve User',
            message: 'Apakah anda yakin approve user "' + param.fullname + '" ?',
            onConfirm: () => handleApprove(param.user_id),
            onCancel: () => props.setSelectedData(null),
        });
    };

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

    const handleApprove = async (user_id) => {
        // TODO: Implement approve user API call
        NotifAlert({
            icon: 'info',
            title: 'Info',
            message: 'Approve user akan diimplementasikan dengan API',
        });
        // const response = await approveUser(user_id);
        // if (response.statusCode == 200) {
        //     NotifAlert({
        //         icon: 'success',
        //         title: 'Berhasil',
        //         message: 'User berhasil diapprove.',
        //     });
        //     doFilter();
        // }
    };

    const handleDelete = async (user_id) => {
        const response = await deleteUser(user_id);

        if (response.statusCode == 200) {
            NotifAlert({
                icon: 'success',
                title: 'Berhasil',
                message: 'User "' + response.data.fullname + '" berhasil dihapus.',
            });
            doFilter();
        } else {
            NotifOk({
                icon: 'error',
                title: 'Gagal',
                message: 'Gagal Menghapus User',
            });
        }
    };

    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 user by username, nama, or role..."
                                    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 User
                                        </Button>
                                    </ConfigProvider>
                                </Space>
                            </Col>
                        </Row>
                    </Col>
                    <Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginTop: '16px' }}>
                        <TableList
                            getData={getAllUser}
                            queryParams={formDataFilter}
                            columns={columns(
                                showPreviewModal,
                                showEditModal,
                                showDeleteDialog,
                                showApproveDialog
                            )}
                            triger={trigerFilter}
                        />
                    </Col>
                </Row>
            </Card>
        </React.Fragment>
    );
});

export default ListUser;
