import { saveProfil } from '@/api/api_profil';
import { alertError, alertSuccess } from '@/components/costum/alert';
import { ButtonSubmit } from '@/components/costum/button_submit';
import PageHeader from '@/components/costum/page_header';
import { ProfilModel } from '@/types';
import { useProfil } from '@/useQuery/query';
import { usePage } from '@inertiajs/react';
import { ImagePlus, Save, Trash } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Spinner } from 'react-bootstrap';
import { Link } from 'react-router';

export default function SetuPProfil() {
    const { token } = usePage().props;
    const detailProfil = useProfil();

    const [profil, setProfil] = useState<ProfilModel>();
    const [loadingData, setLoadingData] = useState<boolean>(true);

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

    const saveDataProfil = async () => {
        const response = await saveProfil(profil!, token as string);
        const responseBody = await response.json();

        if (response.status == 201 || response.status == 200) {
            setProfil(responseBody);
            detailProfil.refetch();
            await alertSuccess('Profil berhasil disimpan');
            return;
        } else {
            alertError(responseBody.message);
        }
    };

    useEffect(() => {
        if (detailProfil.data) {
            setProfil(detailProfil.data);
        }
        setLoadingData(false);
    }, [detailProfil.data]);

    if (loadingData || detailProfil.isLoading) {
        return (
            <div className="p-3 text-center">
                <Spinner />
            </div>
        );
    }

    return (
        <>
            <div className="container" style={{ width: 1024 }}>
                <PageHeader
                    title="Profil"
                    breadcrumb={[
                        {
                            title: 'Pengaturan',
                            path: '/app/pengaturan',
                        },
                        {
                            title: 'Profil',
                            path: '/app/pengaturan/profil',
                        },
                    ]}
                />
                <div className="card shadow-lg rounded-4 mx-auto">
                    <div className="card-header bg-transparent py-3">
                        <h5 className="m-0">Setup Profil</h5>
                    </div>
                    <div className="card-body">
                        <div className="row">
                            <div className="col-md-9">
                                <div className="row mb-2">
                                    <label className="col-form-label col-md-3">Nama</label>
                                    <div className="col-md-9">
                                        <input
                                            className="form-control"
                                            placeholder="Nama Instansi"
                                            value={profil?.nama}
                                            name="nama"
                                            onChange={handleChange}
                                        />
                                    </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={profil?.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={profil?.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={profil?.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={profil?.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={profil?.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={profil?.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={profil?.kabupaten}
                                            name="kabupaten"
                                            onChange={handleChange}
                                        />
                                    </div>
                                </div>
                                <hr />
                                <div className="row mb-2">
                                    <label className="col-form-label col-md-3">Email</label>
                                    <div className="col-md-4">
                                        <input
                                            className="form-control"
                                            placeholder="Email"
                                            type="email"
                                            value={profil?.email}
                                            name="email"
                                            onChange={(e) => {
                                                setProfil({ ...profil, email: e.target.value.toLowerCase() });
                                            }}
                                        />
                                    </div>
                                    <label className="col-form-label col-md-1">Telp.</label>
                                    <div className="col-md-4">
                                        <input
                                            className="form-control"
                                            placeholder="Nomor Telp"
                                            value={profil?.nomor_telp}
                                            name="nomor_telp"
                                            onChange={handleChange}
                                        />
                                    </div>
                                </div>
                                <div className="row mb-2">
                                    <label className="col-form-label col-md-3">Website</label>
                                    <div className="col-md-4">
                                        <input
                                            className="form-control"
                                            placeholder="Website"
                                            value={profil?.website}
                                            name="website"
                                            onChange={(e) => {
                                                setProfil({ ...profil, website: e.target.value.toLowerCase() });
                                            }}
                                        />
                                    </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="logo">
                                        <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: `${profil?.logo == undefined ? '' : `url(${profil.logo})`}`,
                                                backgroundSize: 'cover',
                                                backgroundPosition: 'center',
                                            }}
                                        >
                                            {!profil?.logo && (
                                                <div className="d-flex flex-column gap-2 align-items-center">
                                                    <ImagePlus />
                                                    <span>Maks. 1MB</span>
                                                </div>
                                            )}
                                        </div>
                                    </label>
                                    <input
                                        id="logo"
                                        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') {
                                                        setProfil({ ...profil, logo: e.target.result });
                                                    }
                                                };
                                                reader.readAsDataURL(file);
                                            }
                                        }}
                                    />
                                </div>
                                {profil?.logo && (
                                    <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={() => {
                                                        setProfil({ ...profil, logo: undefined });
                                                    }}
                                                >
                                                    Hapus
                                                </ButtonSubmit>
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                    <div className="card-footer d-flex justify-content-between bg-transparent py-3">
                        <Link to={`/app/dashboard`} className='btn btn-danger'>Kembali</Link>
                        <ButtonSubmit className="btn-success" icon={<Save size={18} />} onClick={async () => await saveDataProfil()}>
                            Simpan
                        </ButtonSubmit>
                    </div>
                </div>
            </div>
        </>
    );
}
