import React 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 { Button } from "primereact/button";
import { useState } from "react";
import { Dialog } from "primereact/dialog";
import { Dropdown } from "primereact/dropdown";
import { classNames } from "primereact/utils";
import { useRef } from "react";
import { useForm, Controller } from "react-hook-form";
import axios from "axios";
import { Toast } from "primereact/toast";
import { useEffect } from "react";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { authUser } from "@/Components/AuthProvider";
import { useContext } from "react";
import { Calendar } from "primereact/calendar";
import { InputNumber } from "primereact/inputnumber";

export default function EmployeeSalary({ auth, salaries, employees: initialEmployees }) {
    const { permission } = useContext(authUser);
    const [modelstatus, setmodelStatus] = useState("create");
    const [modelShow, SetModelShow] = useState(false);

    const [showSalary, setSalary] = useState(salaries || []);
    const [employees, setEmployees] = useState(initialEmployees || []);
    const [showMessage, setShowMessage] = useState(false);
    const [formData, setFormData] = useState({});
    const [currentId, setid] = useState(null);
    const formSubmit = useRef(null);
    const [filters, setFilters] = useState({
        global: { value: null, matchMode: FilterMatchMode.CONTAINS },
    });
    const [globalFilterValue, setGlobalFilterValue] = useState("");
    const defaultValues = {
        employee_id: "",
        salary_month: new Date(),
        basic_salary: 0,
        allowance: 0,
        bonus: 0,
        deduction: 0,
        net_salary: 0,
        payment_date: new Date(),
        payment_status: "pending",
        remarks: "",
    };
    const toast = useRef(null);
    const {
        control,
        formState: { errors },
        handleSubmit,
        reset,
        setError,
        watch,
        setValue,
        register,
    } = useForm({ defaultValues });

    // Watch values for automatic calculation
    const basicSalary = watch("basic_salary") || 0;
    const allowance = watch("allowance") || 0;
    const bonus = watch("bonus") || 0;
    const deduction = watch("deduction") || 0;

    // Calculate net salary automatically
    useEffect(() => {
        const netSalary = Number(basicSalary) + Number(allowance) + Number(bonus) - Number(deduction);
        setValue("net_salary", netSalary);
    }, [basicSalary, allowance, bonus, deduction, setValue]);

    {
        /* Table Data Search */
    }
    const onGlobalFilterChange = (e) => {
        const value = e.target.value;
        let _filters = { ...filters };

        _filters["global"].value = value;

        setFilters(_filters);
        setGlobalFilterValue(value);
    };

    // Handle employee selection
    const handleEmployeeChange = (employeeId) => {
        const selectedEmployee = employees.find(emp => emp.id === employeeId);
        if (selectedEmployee) {
            setValue("basic_salary", selectedEmployee.basic_salary);
        }
    };

    {
        /* Table Header Component  */
    }
    const renderHeader = () => {
        return (
            <div
                className={`w-100% flex ${
                    permission.includes("employee_salary_create")
                        ? "justify-between"
                        : "justify-end"
                } `}
            >
                {permission.includes("employee_salary_create") && (
                    <Button
                        type="button"
                        icon={<span className="pi pi-plus text-sm pr-1" />}
                        label="Add"
                        onClick={() => {
                            SetModelShow(true);
                            setmodelStatus("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();
    
    {
        /* Model Footer Content  */
    }
    const footerContent = (
        <div className="flex justify-end">
            <Button
                label="Cancel"
                onClick={() => {
                    SetModelShow(false);
                }}
                icon="pi pi-times"
                className="p-button-text w-13 text-sm"
            />
            <Button
                label="Save"
                icon="pi pi-check"
                onClick={() => {
                    formSubmit.current.dispatchEvent(
                        new Event("submit", { bubbles: true, cancelable: true })
                    );
                }}
                autoFocus
                className="text-sm"
            />
        </div>
    );

    {
        /* Store Data  */
    }
    const onSubmit = (data) => {
        setFormData(data);
        setShowMessage(true);
        axios
            .post(route("employee-salary.store"), data)
            .then((response) => {
                toast.current.show({
                    severity: "success",
                    summary: response.data.success,
                    detail: "Salary Record Created",
                    life: 3000,
                });
                SetModelShow(false);
                reset(defaultValues);
                setSalary(response.data.salaries);
            })
            .catch((error) => {
                let errors = error.response.data.errors;
                Object.keys(errors).forEach((field) => {
                    setError(field, {
                        type: "manual",
                        message: errors[field][0],
                    });
                });
            });
    };
    
    {
        /* Edit Data  */
    }
    const handelEdit = (e) => {
        reset({
            employee_id: e.employee_id,
            salary_month: e.salary_month ? new Date(e.salary_month) : new Date(),
            basic_salary: e.basic_salary,
            allowance: e.allowance,
            bonus: e.bonus,
            deduction: e.deduction,
            net_salary: e.net_salary,
            payment_date: e.payment_date ? new Date(e.payment_date) : new Date(),
            payment_status: e.payment_status,
            remarks: e.remarks,
        });

        setid(e.id);
        setmodelStatus("edit");
        SetModelShow(true);
    };
    
    {
        /* Delete Data   */
    }
    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("employee-salary.destroy", id))
                    .then((response) => {
                        setSalary(response.data.salaries);

                        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,
                });
            },
        });
    };
    
    {
        /* Update Data   */
    }
    const HandelUpdate = (data) => {
        setFormData(data);
        setShowMessage(true);
        axios
            .put(route("employee-salary.update", currentId), data)
            .then((response) => {
                toast.current.show({
                    severity: "success",
                    summary: response.data.success,
                    detail: "Salary Record Updated",
                    life: 3000,
                });
                SetModelShow(false);
                reset(defaultValues);
                setSalary(response.data.salaries);
            })
            .catch((error) => {
                let errors = error.response.data.errors;
                Object.keys(errors).forEach((field) => {
                    setError(field, {
                        type: "manual",
                        message: errors[field][0],
                    });
                });
            });
    };

    const paymentStatusOptions = [
        { label: "Pending", value: "pending" },
        { label: "Paid", value: "paid" },
        { label: "Cancelled", value: "cancelled" },
    ];

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">Employee Salary</h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - Employee Salary
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card">
                <DataTable
                    className="defulattable"
                    value={showSalary}
                    paginator
                    showGridlines
                    rows={10}
                    dataKey="id"
                    header={header}
                    filters={filters}
                    emptyMessage="No salary record found."
                >
                    <Column 
                        field="employee_id" 
                        header="Employee" 
                        body={(rowData) => rowData.employee?.user?.name || '-'}
                        sortable 
                    />
                    <Column 
                        field="salary_month" 
                        header="Month" 
                        body={(rowData) => new Date(rowData.salary_month).toLocaleDateString('en-US', { year: 'numeric', month: 'long' })}
                        sortable 
                    />
                    <Column 
                        field="basic_salary" 
                        header="Basic Salary" 
                        body={(rowData) => `৳${parseFloat(rowData.basic_salary).toLocaleString()}`}
                    />
                    <Column 
                        field="net_salary" 
                        header="Net Salary" 
                        body={(rowData) => `৳${parseFloat(rowData.net_salary).toLocaleString()}`}
                    />
                    <Column 
                        field="payment_status" 
                        header="Status" 
                        body={(rowData) => (
                            <span className={`px-2 py-1 rounded text-xs font-medium ${
                                rowData.payment_status === 'paid' ? 'bg-green-100 text-green-800' :
                                rowData.payment_status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                                'bg-red-100 text-red-800'
                            }`}>
                                {rowData.payment_status.toUpperCase()}
                            </span>
                        )}
                    />
                    <Column 
                        field="payment_date" 
                        header="Payment Date" 
                        body={(rowData) => rowData.payment_date ? new Date(rowData.payment_date).toLocaleDateString() : '-'}
                    />

                    <Column
                        header="Action"
                        body={(rowData) => (
                            <>
                                {" "}
                                <ConfirmPopup />{" "}
                                {permission.includes("employee_salary_edit") && (
                                    <Button
                                        icon="pi pi-pencil"
                                        onClick={(e) => {
                                            handelEdit(rowData);
                                        }}
                                        className="p-button-rounded p-button-success mr-2 px-3 py-2  w-10 h-10 font-medium"
                                    />
                                )}
                                {permission.includes("employee_salary_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"
                                    />
                                )}
                            </>
                        )}
                        bodyClassName="text-center"
                        style={{ minWidth: "14rem" }}
                    />
                </DataTable>
            </div>
            {/* View Table End*/}

            {/* Create Model*/}
 <Dialog
    header={() => (modelstatus === "create" ? "Create Salary Record" : "Update Salary Record")}
    visible={modelShow}
    style={{ width: "90vw", maxWidth: "700px" }} // responsive width
    onHide={() => SetModelShow(false)}
    footer={footerContent}
>
    <form
        ref={formSubmit}
        onSubmit={modelstatus === "create" ? handleSubmit(onSubmit) : handleSubmit(HandelUpdate)}
        className="p-fluid"
        method="POST"
    >
        <div className="grid grid-cols-12 gap-4 mt-3">
            {/* Employee */}
            <div className="col-span-12 sm:col-span-6">
                <div className="p-float-label mt-4">
                    <Controller
                        name="employee_id"
                        control={control}
                        rules={{ required: "Employee is required" }}
                        render={({ field, fieldState }) => (
                            <Dropdown
                                id={field.name}
                                value={field.value}
                                onChange={(e) => {
                                    field.onChange(e.value);
                                    handleEmployeeChange(e.value);
                                }}
                                options={employees}
                                optionLabel="user.name"
                                optionValue="id"
                                filter
                                className={classNames({ "p-invalid": fieldState.invalid }) + " w-full"}
                                itemTemplate={(option) => (
                                    <div className="flex flex-col">
                                        <span className="font-bold">{option.user?.name}</span>
                                        <span className="text-xs text-gray-500">
                                            {option.employee_id} - {option.designation}
                                        </span>
                                    </div>
                                )}
                            />
                        )}
                    />
                    <label htmlFor="employee_id">Employee*</label>
                </div>
                {errors.employee_id && (
                    <small className="p-error block m-1">{errors.employee_id.message}</small>
                )}
            </div>

            {/* Salary Month */}
            <div className="col-span-12 sm:col-span-6">
                <div className="p-float-label mt-4">
                    <Controller
                        name="salary_month"
                        control={control}
                        rules={{ required: "Salary month is required" }}
                        render={({ field, fieldState }) => (
                            <Calendar
                                id={field.name}
                                value={field.value ? new Date(field.value) : null}
                                onChange={(e) => field.onChange(e.value)}
                                view="month"
                                dateFormat="MM yy"
                                className={classNames({ "p-invalid": fieldState.invalid }) + " w-full"}
                                showIcon
                            />
                        )}
                    />
                    <label htmlFor="salary_month">Salary Month*</label>
                </div>
                {errors.salary_month && (
                    <small className="p-error block m-1">{errors.salary_month.message}</small>
                )}
            </div>

            {/* Basic Salary */}
            <div className="col-span-12 sm:col-span-6">
                <div className="p-float-label mt-4">
                    <Controller
                        name="basic_salary"
                        control={control}
                        rules={{ required: "Basic salary is required" }}
                        render={({ field, fieldState }) => (
                            <InputNumber
                                id={field.name}
                                value={field.value}
                                onValueChange={(e) => field.onChange(e.value)}
                                mode="decimal"
                                minFractionDigits={2}
                                className={classNames({ "p-invalid": fieldState.invalid }) + " w-full"}
                            />
                        )}
                    />
                    <label htmlFor="basic_salary">Basic Salary*</label>
                </div>
                {errors.basic_salary && (
                    <small className="p-error block m-1">{errors.basic_salary.message}</small>
                )}
            </div>

            {/* Allowance */}
            <div className="col-span-12 sm:col-span-6">
                <div className="p-float-label mt-4">
                    <Controller
                        name="allowance"
                        control={control}
                        render={({ field }) => (
                            <InputNumber
                                id={field.name}
                                value={field.value}
                                onValueChange={(e) => field.onChange(e.value)}
                                mode="decimal"
                                minFractionDigits={2}
                                className="w-full"
                            />
                        )}
                    />
                    <label htmlFor="allowance">Allowance</label>
                </div>
            </div>

            {/* Bonus */}
            <div className="col-span-12 sm:col-span-6">
                <div className="p-float-label mt-4">
                    <Controller
                        name="bonus"
                        control={control}
                        render={({ field }) => (
                            <InputNumber
                                id={field.name}
                                value={field.value}
                                onValueChange={(e) => field.onChange(e.value)}
                                mode="decimal"
                                minFractionDigits={2}
                                className="w-full"
                            />
                        )}
                    />
                    <label htmlFor="bonus">Bonus</label>
                </div>
            </div>

            {/* Deduction */}
            <div className="col-span-12 sm:col-span-6">
                <div className="p-float-label mt-4">
                    <Controller
                        name="deduction"
                        control={control}
                        render={({ field }) => (
                            <InputNumber
                                id={field.name}
                                value={field.value}
                                onValueChange={(e) => field.onChange(e.value)}
                                mode="decimal"
                                minFractionDigits={2}
                                className="w-full"
                            />
                        )}
                    />
                    <label htmlFor="deduction">Deduction</label>
                </div>
            </div>

            {/* Net Salary */}
            <div className="col-span-12 sm:col-span-6">
                <div className="p-float-label mt-4">
                    <Controller
                        name="net_salary"
                        control={control}
                        render={({ field }) => (
                            <InputNumber
                                id={field.name}
                                value={field.value}
                                onValueChange={(e) => field.onChange(e.value)}
                                mode="decimal"
                                minFractionDigits={2}
                                className="w-full bg-gray-100"
                                disabled
                            />
                        )}
                    />
                    <label htmlFor="net_salary">Net Salary</label>
                </div>
                <small className="text-gray-500 block m-1">Auto-calculated</small>
            </div>

            {/* Payment Date */}
            <div className="col-span-12 sm:col-span-6">
                <div className="p-float-label mt-4">
                    <Controller
                        name="payment_date"
                        control={control}
                        render={({ field }) => (
                            <Calendar
                                id={field.name}
                                value={field.value ? new Date(field.value) : null}
                                onChange={(e) => field.onChange(e.value)}
                                dateFormat="yy-mm-dd"
                                className="w-full"
                                showIcon
                            />
                        )}
                    />
                    <label htmlFor="payment_date">Payment Date</label>
                </div>
            </div>

            {/* Payment Status */}
            <div className="col-span-12 sm:col-span-6">
                <div className="p-float-label mt-4">
                    <Controller
                        name="payment_status"
                        control={control}
                        rules={{ required: "Payment status is required" }}
                        render={({ field, fieldState }) => (
                            <Dropdown
                                id={field.name}
                                value={field.value}
                                onChange={(e) => field.onChange(e.value)}
                                options={paymentStatusOptions}
                                className={classNames({ "p-invalid": fieldState.invalid }) + " w-full"}
                            />
                        )}
                    />
                    <label htmlFor="payment_status">Payment Status*</label>
                </div>
                {errors.payment_status && (
                    <small className="p-error block m-1">{errors.payment_status.message}</small>
                )}
            </div>

            {/* Remarks */}
            <div className="col-span-12">
                <div className="p-float-label mt-4">
                    <InputText
                        id="remarks"
                        defaultValue={watch("remarks")}
                        className="w-full"
                        {...register("remarks")}
                    />
                    <label htmlFor="remarks">Remarks</label>
                </div>
            </div>
        </div>
    </form>
</Dialog>

            {/* Create Model End*/}
        </AuthenticatedLayout>
    );
}
