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, approveUser } from '../../../api/user';
import TableList from '../../../components/Global/TableList';
import Swal from 'sweetalert2';

const columns = (showPreviewModal, showEditModal, showDeleteDialog, showApproveDialog) => [
    {
        title: 'ID',
        dataIndex: 'user_id',
        key: 'user_id',
        width: '5%',
        hidden: 'true',
    },
    {
        title: 'Username',
        dataIndex: 'user_name',
        key: 'user_name',
        width: '12%',
    },
    {
        title: 'Nama Lengkap',
        dataIndex: 'user_fullname',
        key: 'user_fullname',
        width: '15%',
    },
    {
        title: 'Nomor WA',
        dataIndex: 'user_phone',
        key: 'user_phone',
        width: '12%',
    },
    {
        title: 'Level',
        dataIndex: 'role_level',
        key: 'role_level',
        width: '8%',
        align: 'center',
        render: (role_level) => role_level || '-',
    },
    {
        title: 'Nama Role',
        dataIndex: 'role_name',
        key: 'role_name',
        width: '12%',
        render: (_, { role_name }) => {
            if (!role_name) return <Tag color={'default'}>Belum Ada Role</Tag>;
            return (
                <>
                    {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 Approval',
        dataIndex: 'is_approve',
        key: 'is_approve',
        width: '10%',
        align: 'center',
        render: (_, { is_approve, is_active }) => {
            // Status approval
            if (is_approve === false || is_approve === 0) {
                return (
                    <Tag color={'orange'} key={'status'}>
                        Pending Approval
                    </Tag>
                );
            }
            // Jika sudah approve, cek active/inactive
            if (is_active === true || is_active === 1) {
                return (
                    <Tag color={'green'} key={'status'}>
                        Active
                    </Tag>
                );
            }
            return (
                <Tag color={'default'} key={'status'}>
                    Inactive
                </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.is_approve === false || record.is_approve === 0) && (
                    <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 && props.actionMode == 'list') {
            setFormDataFilter(defaultFilter);
            doFilter();
        } else if (!token) {
            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) => {
        Swal.fire({
            icon: 'question',
            title: 'Konfirmasi Approve User',
            text: 'Apakah anda yakin approve user "' + param.user_fullname + '" ?',
            showCancelButton: true,
            cancelButtonColor: '#d33',
            cancelButtonText: 'Batal',
            confirmButtonColor: '#23A55A',
            confirmButtonText: 'Approve',
            reverseButtons: true,
        }).then((result) => {
            if (result.isConfirmed) {
                handleApprove(param.user_id);
            } else if (result.dismiss) {
                props.setSelectedData(null);
            }
        });
    };

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

    const handleApprove = async (user_id) => {
        const response = await approveUser(user_id);
        if (response.statusCode == 200) {
            NotifAlert({
                icon: 'success',
                title: 'Berhasil',
                message: 'User berhasil diapprove.',
            });
            doFilter();
        } else {
            NotifOk({
                icon: 'error',
                title: 'Gagal',
                message: 'Gagal Approve User',
            });
        }
    };

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

        if (response.statusCode == 200) {
            NotifAlert({
                icon: 'success',
                title: 'Berhasil',
                message: 'User "' + response.data.user_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;
