import { saveAnggota } from '@/api/api_anggota';
import { formatDate } from '@/helper';
import { Anggota } from '@/types';
import { useDetailAnggota } from '@/useQuery/query';
import { ImagePlus, Save, Trash, X } from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Modal } from 'react-bootstrap';
import { alertError, alertSuccess } from '../../../components/costum/alert';
import { ButtonSubmit } from '../../../components/costum/button_submit';
import { SelectAgama } from '../../../components/costum/SelectAgama';
import { SelectPenghasilan } from '../../../components/costum/SelectPenghasilan';
import { SelectStatusMarital } from '../../../components/costum/SelectStatusMarital';
import { usePage } from '@inertiajs/react';

export const useModalDetailAnggota = ({ onSubmit }: { onSubmit?: (user: Anggota) => boolean | Promise<boolean> }) => {
    const { token } = usePage().props;
    const [showModal, setShowModal] = useState(false);
    const [validasi, setValidasi] = useState<boolean>(false);
    const [loading, setLoading] = useState<boolean>(false);

    const [anggota, setAnggota] = useState<Anggota>();

    const detailAnggota = useDetailAnggota(anggota?.id);

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

    const saveDataAnggota = useCallback(async () => {
        const response = await saveAnggota(anggota!, token as string);
        const responseBody = await response.json();
        console.log(anggota);

        if (response.status == 201 || response.status == 200) {
            setAnggota({ ...responseBody, tgl_lahir: formatDate(responseBody.tgl_lahir) });
            if (onSubmit) onSubmit(responseBody);
            detailAnggota.refetch();
            await alertSuccess('Data berhasil disimpan');
            return;
        } else {
            alertError(responseBody.message);
        }
    }, [anggota, detailAnggota, onSubmit, token]);

    const open = (id?: string) => {
        setShowModal(true);
        if (id) {
            setAnggota({ id: id });
            detailAnggota.refetch();
        }
    };

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

    const clear = () => {
        setAnggota(undefined);
        setValidasi(false);
        setLoading(false);
    };

    useEffect(() => {
        if (detailAnggota.data) {
            setAnggota({ ...detailAnggota.data, tgl_lahir: formatDate(detailAnggota.data.tgl_lahir) });
        }
    }, [detailAnggota.data]);

    console.log(anggota);

    const modal = useMemo(() => {
        return (
            <>
                <Modal show={showModal} onHide={close} onExited={clear} size="xl" centered dialogClassName="modal-xl">
                    <Modal.Header closeButton>
                        <h5 className="mb-0">Detail Anggota</h5>
                    </Modal.Header>
                    <Modal.Body>
                        <div className="row">
                            <div className="col-md-12 col-sm-12 col-lg-9">
                                <div className="row">
                                    <div className="col-md-12">
                                        <div className="row">
                                            <div className="col-md-12 col-lg-12">
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3">Anggota ID</label>
                                                    <div className="col-md-3">
                                                        <input className="form-control" placeholder="ID" readOnly value={anggota?.id} />
                                                    </div>
                                                    <label className="col-form-label col-md-3">NIK / Nomor KTP</label>
                                                    <div className="col-md-3">
                                                        <input
                                                            className="form-control"
                                                            placeholder="NIK"
                                                            maxLength={16}
                                                            minLength={16}
                                                            name="nik"
                                                            value={anggota?.nik}
                                                            onChange={handleChange}
                                                        />
                                                    </div>
                                                </div>
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3">Nama Lengkap</label>
                                                    <div className="col-md-9">
                                                        <input
                                                            className="form-control"
                                                            placeholder="Nama Lengkap"
                                                            value={anggota?.nama_lengkap}
                                                            name="nama_lengkap"
                                                            onChange={handleChange}
                                                        />
                                                    </div>
                                                </div>
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3">Tempat, Tgl Lahir</label>
                                                    <div className="col-md-6">
                                                        <div className="input-group">
                                                            <input
                                                                className="form-control border-end-0"
                                                                placeholder="Tempat Lahir"
                                                                value={anggota?.tempat_lahir}
                                                                name="tempat_lahir"
                                                                onChange={handleChange}
                                                            />
                                                            <span className="input-group-text border-end-0 bg-white">,</span>
                                                            <input
                                                                type="date"
                                                                className="form-control border-start-0 text-center"
                                                                value={anggota?.tgl_lahir}
                                                                name="tgl_lahir"
                                                                onChange={handleChange}
                                                            />
                                                        </div>
                                                    </div>
                                                    <div className="col-md-3">
                                                        <select
                                                            className="form-select"
                                                            value={detailAnggota.data?.jenis_kelamin}
                                                            name="jenis_kelamin"
                                                            onChange={(e) => setAnggota({ ...anggota, jenis_kelamin: e.target.value })}
                                                        >
                                                            <option value={''} className="text-muted">
                                                                Jenis Kelamin
                                                            </option>
                                                            <option value={'L'}>LAKI-LAKI</option>
                                                            <option value={'P'}>PEREMPUAN</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <hr />
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3">Alamat</label>
                                                    <div className="col-md-9">
                                                        <input
                                                            className="form-control"
                                                            placeholder="Alamat"
                                                            value={anggota?.alamat}
                                                            name="alamat"
                                                            onChange={handleChange}
                                                        />
                                                    </div>
                                                </div>
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3" />
                                                    <div className="col-md-2">
                                                        <div className="input-group">
                                                            <span className="input-group-text bg-white border-end-0">RT</span>
                                                            <input
                                                                className="form-control border-start-0 text-center"
                                                                placeholder="______"
                                                                value={anggota?.rt}
                                                                name="rt"
                                                                onChange={handleChange}
                                                            />
                                                        </div>
                                                    </div>
                                                    <div className="col-md-2">
                                                        <div className="input-group">
                                                            <span className="input-group-text bg-white border-end-0">RW</span>
                                                            <input
                                                                className="form-control border-start-0 text-center"
                                                                placeholder="______"
                                                                value={anggota?.rw}
                                                                name="rw"
                                                                onChange={handleChange}
                                                            />
                                                        </div>
                                                    </div>
                                                    <div className="col-md-3">
                                                        <div className="input-group">
                                                            <span className="input-group-text bg-white border-end-0">Kode Pos</span>
                                                            <input
                                                                className="form-control border-start-0 text-center"
                                                                placeholder="_________"
                                                                value={anggota?.kode_pos}
                                                                name="kode_pos"
                                                                onChange={handleChange}
                                                            />
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3">Kelurahan</label>
                                                    <div className="col-md-4">
                                                        <input
                                                            className="form-control"
                                                            placeholder="Kelurahan"
                                                            value={anggota?.kelurahan}
                                                            name="kelurahan"
                                                            onChange={handleChange}
                                                        />
                                                    </div>
                                                    <label className="col-form-label col-md-1">Kec.</label>
                                                    <div className="col-md-4">
                                                        <input
                                                            className="form-control"
                                                            placeholder="Kecamatan"
                                                            value={anggota?.kecamatan}
                                                            name="kecamatan"
                                                            onChange={handleChange}
                                                        />
                                                    </div>
                                                </div>
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3">Kota/Kabupaten</label>
                                                    <div className="col-md-4">
                                                        <input
                                                            className="form-control"
                                                            placeholder="Kota/Kabupaten"
                                                            value={anggota?.kabupaten}
                                                            name="kabupaten"
                                                            onChange={handleChange}
                                                        />
                                                    </div>
                                                    <label className="col-form-label col-md-1">Telp.</label>
                                                    <div className="col-md-4">
                                                        <input
                                                            className="form-control"
                                                            placeholder="Nomor Telp/HP"
                                                            value={anggota?.nomor_telp}
                                                            name="nomor_telp"
                                                            onChange={handleChange}
                                                        />
                                                    </div>
                                                </div>
                                                <hr />
                                            </div>
                                            <div className="col-md-12 col-lg-12">
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3">Agama</label>
                                                    <div className="col-md-4 col-lg-5 col-sm-6">
                                                        <SelectAgama
                                                            onChange={(val) => setAnggota({ ...anggota, agama: parseInt(val) })}
                                                            value={anggota?.agama?.toString() ?? ''}
                                                        />
                                                    </div>
                                                </div>
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3">Status Marital</label>
                                                    <div className="col-md-4 col-lg-5 col-sm-6">
                                                        <SelectStatusMarital
                                                            onChange={(val) => setAnggota({ ...anggota, status_marital: parseInt(val) })}
                                                            value={anggota?.status_marital?.toString()}
                                                        />
                                                    </div>
                                                </div>
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3">Ibu Kandung</label>
                                                    <div className="col-md-4 col-lg-5">
                                                        <input
                                                            className="form-control"
                                                            placeholder="Ibu Kandung"
                                                            value={anggota?.ibu_kandung}
                                                            name="ibu_kandung"
                                                            onChange={handleChange}
                                                        />
                                                    </div>
                                                </div>
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3">Pekerjaan</label>
                                                    <div className="col-md-9">
                                                        <div className="input-group">
                                                            <input
                                                                className="form-control"
                                                                placeholder="Pekerjaan"
                                                                value={anggota?.pekerjaan}
                                                                name="pekerjaan"
                                                                onChange={handleChange}
                                                            />
                                                            <span className="input-group-text">Lokasi</span>
                                                            <input
                                                                className="form-control"
                                                                placeholder="Lokasi Bekerja"
                                                                value={anggota?.lokasi_kerja}
                                                                name="lokasi_kerja"
                                                                onChange={handleChange}
                                                            />
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className="row mb-2">
                                                    <label className="col-form-label col-md-3">Penghasilan</label>
                                                    <div className="col-md-6">
                                                        <SelectPenghasilan
                                                            menuPlacement="top"
                                                            onChange={(val) => setAnggota({ ...anggota, penghasilan: val })}
                                                            value={anggota?.penghasilan}
                                                        />
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="col-md-12">
                                        <div className="row">
                                            <div className="col-md-12" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="col-md-4 col-sm-12 col-lg-3">
                                <div className="row">
                                    <label className="col-form-label col-md-12">
                                        <span>Foto (Maks. 1MB)</span>
                                    </label>
                                </div>
                                <div className="row mb-3">
                                    <label className="col-form-label text-center" htmlFor="foto">
                                        <div
                                            className="d-flex flex-column gap-2 justify-content-center align-items-center"
                                            style={{
                                                borderRadius: 8,
                                                aspectRatio: '1 / 1',
                                                cursor: 'pointer',
                                                border: '1px solid rgb(187, 187, 187)',
                                                backgroundImage: `${anggota?.foto == undefined ? '' : `url(${anggota.foto})`}`,
                                                backgroundSize: 'cover',
                                                backgroundPosition: 'center',
                                            }}
                                        >
                                            {!anggota?.foto && (
                                                <div className="d-flex flex-column gap-2 align-items-center">
                                                    <ImagePlus />
                                                    <span>Maks. 1MB</span>
                                                </div>
                                            )}
                                        </div>
                                    </label>
                                    <input
                                        id="foto"
                                        type="file"
                                        accept="image/png, image/gif, image/jpeg"
                                        style={{ display: 'none' }}
                                        onChange={(input) => {
                                            const files = input.target.files;
                                            if (files && files.length !== 0) {
                                                const file = files[0];
                                                if (file.size > 1000000) {
                                                    alertError('Ukuran foto maksimal 1MB');
                                                    return;
                                                }
                                                const reader = new FileReader();
                                                reader.onload = function (e) {
                                                    if (e.target && typeof e.target.result === 'string') {
                                                        setAnggota({ ...anggota, foto: e.target.result });
                                                    }
                                                };
                                                reader.readAsDataURL(file);
                                            }
                                        }}
                                    />
                                </div>
                                <div className="row mb-2">
                                    <div className="col-md-12">
                                        <div className="d-flex">
                                            <ButtonSubmit
                                                icon={<Trash size={18} />}
                                                className="btn-danger d-flex gap-1 justify-content-center flex-grow-1"
                                                onClick={() => {
                                                    setAnggota({ ...anggota, foto: undefined });
                                                }}
                                            >
                                                Hapus
                                            </ButtonSubmit>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </Modal.Body>
                    <Modal.Footer className="justify-content-between d-flex">
                        <button onClick={close} className="btn btn-danger align-items-center d-flex gap-2">
                            <X size={18} />
                            Tutup
                        </button>
                        <ButtonSubmit
                            className="btn btn-success"
                            icon={<Save size={18} />}
                            disable={validasi || loading}
                            onClick={async () => {
                                await saveDataAnggota();
                            }}
                        >
                            Simpan
                        </ButtonSubmit>
                    </Modal.Footer>
                </Modal>
            </>
        );
    }, [anggota, detailAnggota.data?.jenis_kelamin, handleChange, loading, saveDataAnggota, showModal, validasi]);

    return { modal, open, close };
};
