import React, { useContext, useEffect, useRef, useState } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { FilterMatchMode } from "primereact/api";
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
import { InputText } from "primereact/inputtext";
import { InputTextarea } from "primereact/inputtextarea";
import { Button } from "primereact/button";
import { Dialog } from "primereact/dialog";
import { Dropdown } from "primereact/dropdown";
import { classNames } from "primereact/utils";
import { useForm, Controller } from "react-hook-form";
import axios from "axios";
import { Toast } from "primereact/toast";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { authUser } from "@/Components/AuthProvider";

const providerTypeOptions = [
    { label: "Bank", value: "bank" },
    { label: "Person", value: "person" },
    { label: "Company", value: "company" },
];

export default function LoanProvider({ auth }) {
    const { permission } = useContext(authUser);
    const [status, setStatus] = useState("create");
    const [visible, setVisible] = useState(false);
    const [loanProviders, setLoanProviders] = useState([]);
    const [currentId, setid] = useState(null);
    const [loading, setLoading] = useState(false);
    const [totalRecords, setTotalRecords] = useState(0);
    const [lazyParams, setLazyParams] = useState({
        first: 0,
        rows: 10,
        page: 0,
        search: "",
    });
    const searchTimeout = useRef(null);
    const [filters, setFilters] = useState({
        global: { value: null, matchMode: FilterMatchMode.CONTAINS },
        name: { value: null, matchMode: FilterMatchMode.STARTS_WITH },
    });
    const [globalFilterValue, setGlobalFilterValue] = useState("");
    const defaultValues = {
        provider_type: "",
        name: "",
        mobile: "",
        address: "",
        notes: "",
    };
    const toast = useRef(null);
    const {
        control,
        formState: { errors },
        handleSubmit,
        reset,
        setError,
    } = useForm({ defaultValues });

    const fetchLoanProviders = (params = lazyParams) => {
        setLoading(true);
        axios
            .get(route("loan-provider.view"), {
                params: {
                    rows: params.rows,
                    page: params.page ?? Math.floor(params.first / params.rows),
                    search: params.search || "",
                },
            })
            .then((res) => {
                setLoanProviders(res.data.loanProviders || []);
                setTotalRecords(
                    res.data.totalRecords ??
                        (res.data.loanProviders
                            ? res.data.loanProviders.length
                            : 0)
                );
            })
            .catch(() => {
                setLoanProviders([]);
                setTotalRecords(0);
            })
            .finally(() => setLoading(false));
    };

    useEffect(() => {
        fetchLoanProviders();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const onPage = (event) => {
        const params = {
            ...lazyParams,
            first: event.first,
            rows: event.rows,
            page: event.page,
        };
        setLazyParams(params);
        fetchLoanProviders(params);
    };

    const onGlobalFilterChange = (e) => {
        const value = e.target.value;
        let _filters = { ...filters };

        _filters["global"].value = value;
        setFilters(_filters);
        setGlobalFilterValue(value);

        if (searchTimeout.current) {
            clearTimeout(searchTimeout.current);
        }

        searchTimeout.current = setTimeout(() => {
            const params = {
                ...lazyParams,
                first: 0,
                page: 0,
                search: value,
            };
            setLazyParams(params);
            fetchLoanProviders(params);
        }, 400);
    };

    const renderHeader = () => {
        return (
            <div
                className={`w-100% flex ${
                    permission.includes("loan_provider_create")
                        ? "justify-between"
                        : "justify-end"
                } `}
            >
                {permission.includes("loan_provider_create") && (
                    <Button
                        type="button"
                        icon={<span className="pi pi-plus text-sm pr-1" />}
                        label="Add"
                        onClick={() => {
                            setVisible(true);
                            setStatus("create");
                            reset(defaultValues);
                        }}
                        className="p-button-success h-[41px]  text-[14px] "
                    />
                )}

                <span className="p-input-icon-left h-10 ">
                    <i className="pi pi-search" />
                    <InputText
                        className="h-[41px] w-48"
                        value={globalFilterValue}
                        onChange={onGlobalFilterChange}
                        placeholder="Search"
                    />
                </span>
            </div>
        );
    };
    const header = renderHeader();

    const footerContent = (
        <div className="flex justify-end">
            <Button
                label="Cancel"
                icon="pi pi-times"
                onClick={() => {
                    setVisible(false);
                    reset(defaultValues);
                }}
                className="p-button-text w-13 text-sm"
            />
            <Button
                label="Save"
                icon="pi pi-check"
                onClick={() =>
                    status === "create"
                        ? handleSubmit(onSubmit)()
                        : handleSubmit(HandelUpdate)()
                }
                className="p-button-text w-13 text-sm"
            />
        </div>
    );

    const getFormErrorMessage = (name) => {
        return (
            errors[name] && (
                <small className="p-error">{errors[name].message}</small>
            )
        );
    };

    const onSubmit = (data) => {
        axios
            .post(route("loan-provider.store"), data)
            .then((response) => {
                toast.current.show({
                    severity: "success",
                    summary: response.data.success,
                    detail: "Data inserted",
                    life: 3000,
                    className: "custom-toast-class",
                });
                setVisible(false);
                reset(defaultValues);
                const params = { ...lazyParams, first: 0, page: 0 };
                setLazyParams(params);
                fetchLoanProviders(params);
            })
            .catch((error) => {
                let errors = error.response.data.errors;
                Object.keys(errors).forEach((field) => {
                    setError(field, {
                        type: "manual",
                        message: errors[field][0],
                    });
                });
            });
    };

    const handelEdit = (rowData) => {
        reset({
            provider_type: rowData.provider_type,
            name: rowData.name,
            mobile: rowData.mobile,
            address: rowData.address,
            notes: rowData.notes,
        });
        setid(rowData.id);
        setStatus("update");
        setVisible(true);
    };

    const handelDelete = (event) => {
        const id = event.currentTarget.getAttribute("data-id");
        confirmPopup({
            target: event.currentTarget,
            message: "Do you want to delete this record?",
            icon: "pi pi-info-circle",
            acceptClassName: "p-button-danger",
            accept() {
                axios
                    .delete(route("loan-provider.destroy", id), {
                        params: {
                            rows: lazyParams.rows,
                            page: lazyParams.page,
                            search: lazyParams.search,
                        },
                    })
                    .then((response) => {
                        fetchLoanProviders(lazyParams);

                        toast.current.show({
                            severity: "info",
                            summary: "Confirmed",
                            detail: response.data.success,
                            life: 3000,
                        });
                    })
                    .catch((error) => {
                        toast.current.show({
                            severity: "warn",
                            summary: "Rejected",
                            detail: error.response?.data?.error,
                            life: 3000,
                        });
                    });
            },
            reject() {
                toast.current.show({
                    severity: "warn",
                    summary: "Rejected",
                    detail: "You have rejected",
                    life: 3000,
                });
            },
        });
    };

    const HandelUpdate = (data) => {
        axios
            .put(route("loan-provider.update", currentId), data)
            .then((response) => {
                toast.current.show({
                    severity: "success",
                    summary: response.data.success,
                    detail: "Data updated",
                    life: 3000,
                    className: "custom-toast-class",
                });
                setVisible(false);
                reset(defaultValues);
                fetchLoanProviders(lazyParams);
            })
            .catch((error) => {
                let errors = error.response.data.errors;
                Object.keys(errors).forEach((field) => {
                    setError(field, {
                        type: "manual",
                        message: errors[field][0],
                    });
                });
            });
    };

    const providerTypeTemplate = (rowData) => {
        const label =
            providerTypeOptions.find((opt) => opt.value === rowData.provider_type)
                ?.label || "";
        return <span className="capitalize">{label}</span>;
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Loan Providers
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        Home - Loan Providers
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            <div className="card">
                <DataTable
                    className="defulattable"
                    value={loanProviders}
                    paginator
                    lazy
                    loading={loading}
                    showGridlines
                    rows={lazyParams.rows}
                    first={lazyParams.first}
                    rowsPerPageOptions={[10, 20, 50]}
                    totalRecords={totalRecords}
                    onPage={onPage}
                    dataKey="id"
                    header={header}
                    filters={filters}
                    emptyMessage="No loan provider found."
                >
                    <Column
                        field="provider_type"
                        header="Provider Type"
                        body={providerTypeTemplate}
                    />
                    <Column field="name" header="Name" />
                    <Column field="mobile" header="Mobile" />
                    <Column field="address" header="Address" />
                    <Column field="notes" header="Notes" />

                    <Column
                        header="Action"
                        body={(rowData) => (
                            <>
                                <ConfirmPopup />
                                {permission.includes("loan_provider_edit") && (
                                    <Button
                                        icon="pi pi-pencil"
                                        onClick={() => {
                                            handelEdit(rowData);
                                        }}
                                        className="p-button-rounded p-button-success mr-2 px-3 py-2  w-10 h-10 font-medium"
                                    />
                                )}
                                {permission.includes("loan_provider_delete") && (
                                    <Button
                                        icon="pi pi-trash"
                                        data-id={rowData.id}
                                        onClick={handelDelete}
                                        className="p-button-rounded p-button-warning px-3 py-2  w-10 h-10  font-medium"
                                    />
                                )}
                            </>
                        )}
                        className="p-button-rounded p-button-success mr-2 px-3 py-2  w-10 h-10 font-medium"
                        bodyClassName="text-center"
                        style={{ minWidth: "14rem" }}
                    />
                </DataTable>
            </div>

            <Dialog
                header={() => (status == "create" ? "Create" : "Update")}
                visible={visible}
                style={{ width: "500px" }}
                onHide={() => {
                    setVisible(false);
                    reset(defaultValues);
                }}
                footer={footerContent}
            >
                <form className="p-fluid" method="POST">
                    <div className="field mt-5">
                        <label
                            htmlFor="provider_type"
                            className={classNames({
                                "p-error": errors.provider_type,
                            })}
                        >
                            Provider Type<span className="text-red-500">*</span>
                        </label>
                        <span className="p-float-label">
                            <Controller
                                name="provider_type"
                                control={control}
                                rules={{ required: "Provider type is required." }}
                                render={({ field, fieldState }) => (
                                    <Dropdown
                                        id={field.name}
                                        {...field}
                                        options={providerTypeOptions}
                                        optionLabel="label"
                                        optionValue="value"
                                        placeholder="Select provider type"
                                        className={
                                            classNames({
                                                "p-invalid": fieldState.invalid,
                                            }) + ` w-full`
                                        }
                                    />
                                )}
                            />
                        </span>
                        {getFormErrorMessage("provider_type")}
                    </div>

                    <div className="field mt-5">
                        <label
                            htmlFor="name"
                            className={classNames({ "p-error": errors.name })}
                        >
                            Name<span className="text-red-500">*</span>
                        </label>
                        <span className="p-float-label">
                            <Controller
                                name="name"
                                control={control}
                                rules={{ required: "Name is required." }}
                                render={({ field, fieldState }) => (
                                    <InputText
                                        id={field.name}
                                        {...field}
                                        className={
                                            classNames({
                                                "p-invalid": fieldState.invalid,
                                            }) + ` h-11 w-full block`
                                        }
                                        placeholder="Provider name"
                                    />
                                )}
                            />
                        </span>
                        {getFormErrorMessage("name")}
                    </div>

                    <div className="field mt-5">
                        <label
                            htmlFor="mobile"
                            className={classNames({ "p-error": errors.mobile })}
                        >
                            Mobile
                        </label>
                        <span className="p-float-label">
                            <Controller
                                name="mobile"
                                control={control}
                                render={({ field, fieldState }) => (
                                    <InputText
                                        id={field.name}
                                        {...field}
                                        className={
                                            classNames({
                                                "p-invalid": fieldState.invalid,
                                            }) + ` h-11 w-full block`
                                        }
                                        placeholder="Mobile number"
                                    />
                                )}
                            />
                        </span>
                        {getFormErrorMessage("mobile")}
                    </div>

                    <div className="field mt-5">
                        <label
                            htmlFor="address"
                            className={classNames({ "p-error": errors.address })}
                        >
                            Address
                        </label>
                        <span className="p-float-label">
                            <Controller
                                name="address"
                                control={control}
                                render={({ field, fieldState }) => (
                                    <InputText
                                        id={field.name}
                                        {...field}
                                        className={
                                            classNames({
                                                "p-invalid": fieldState.invalid,
                                            }) + ` h-11 w-full block`
                                        }
                                        placeholder="Address"
                                    />
                                )}
                            />
                        </span>
                        {getFormErrorMessage("address")}
                    </div>

                    <div className="field mt-5">
                        <label
                            htmlFor="notes"
                            className={classNames({ "p-error": errors.notes })}
                        >
                            Notes
                        </label>
                        <span className="p-float-label">
                            <Controller
                                name="notes"
                                control={control}
                                render={({ field, fieldState }) => (
                                    <InputTextarea
                                        id={field.name}
                                        {...field}
                                        rows={3}
                                        className={
                                            classNames({
                                                "p-invalid": fieldState.invalid,
                                            }) + ` w-full`
                                        }
                                        placeholder="Notes"
                                    />
                                )}
                            />
                        </span>
                        {getFormErrorMessage("notes")}
                    </div>
                </form>
            </Dialog>
        </AuthenticatedLayout>
    );
}
