import { Role } from '@/types';
import { Save } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { Modal } from 'react-bootstrap';
import { ButtonSubmit } from '../costum/button_submit';

export const useModalRole = ({ onSubmit }: { onSubmit?: (role: Role) => void }) => {
    const [showModal, setShowModal] = useState(false);
    const [role, setRole] = useState<Role>();

    const open = () => {
        setShowModal(true);
    };

    const close = () => {
        setShowModal(false);
    };

    const clear = () => {
        setRole(undefined);
    };

    const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        setRole((prev) => ({
            ...prev,
            [e.target.name]: e.target.value.toUpperCase(),
        }));
    }, []);

    const handleSubmit = useCallback(
        (e: React.FormEvent) => {
            e.preventDefault();
            if (onSubmit && role) {
                onSubmit(role);
            }
        },
        [onSubmit, role],
    );

    const modal = useMemo(() => {
        return (
            <Modal show={showModal} onHide={close} onExited={clear}>
                <Modal.Header closeButton>
                    <h5 className="m-0">Data Role</h5>
                </Modal.Header>
                <Modal.Body>
                    <form onSubmit={handleSubmit}>
                        <div className="row mb-2">
                            <label className="col-form-label col-md-4">Nama Role</label>
                            <div className="col-md-8">
                                <input className="form-control" autoFocus name="nama" value={role?.nama || ''} onChange={handleChange} />
                            </div>
                        </div>
                    </form>
                </Modal.Body>
                <Modal.Footer>
                    <button className="btn btn-primary" onClick={close}>
                        Tutup
                    </button>
                    <ButtonSubmit
                        disable={!role?.nama}
                        className="btn-success text-white"
                        icon={<Save size={18} />}
                        onClick={async () => {
                            if (onSubmit && role) {
                                await onSubmit(role);
                            }
                        }}
                    >
                        Simpan
                    </ButtonSubmit>
                </Modal.Footer>
            </Modal>
        );
    }, [handleChange, handleSubmit, onSubmit, role, showModal]);

    return { modal, open, close };
};
