import React, { useState, useEffect } from "react";
import { Dialog } from "primereact/dialog";
import { Button } from "primereact/button";
import { InputTextarea } from "primereact/inputtextarea";
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
import { Checkbox } from "primereact/checkbox";
import { Dropdown } from "primereact/dropdown";
import { Toast } from "primereact/toast";
import axios from "axios";

const SendForApprovalModal = ({
    visible,
    onHide,
    approvableType,
    approvableId,
    onSuccess,
}) => {
    const [users, setUsers] = useState([]);
    const [selectedUser, setSelectedUser] = useState(null);
    const [isFinal, setIsFinal] = useState(false);
    const [note, setNote] = useState("");
    const [loading, setLoading] = useState(false);
    const [fetchingUsers, setFetchingUsers] = useState(false);
    const toast = React.useRef(null);

    useEffect(() => {
        if (visible) {
            fetchUsers();
            setSelectedUser(null);
            setIsFinal(false);
            setNote("");
        }
    }, [visible]);

    const fetchUsers = async () => {
        setFetchingUsers(true);
        try {
            const response = await axios.get(route("approvals.approvers"));
            if (response.data.success) {
                setUsers(response.data.data);
            }
        } catch (error) {
            console.error("Error fetching users:", error);
            toast.current?.show({
                severity: "error",
                summary: "Error",
                detail: "Failed to fetch users",
            });
        } finally {
            setFetchingUsers(false);
        }
    };


    const handleSubmit = async () => {
        if (!selectedUser) {
            toast.current?.show({
                severity: "warn",
                summary: "Validation",
                detail: "Please select an approver",
            });
            return;
        }

        setLoading(true);
        try {
            const response = await axios.post(route("approvals.send"), {
                approvable_type: approvableType,
                approvable_id: parseInt(approvableId, 10),
                approver_ids: [parseInt(selectedUser.id, 10)],
                sequences: { [selectedUser.id]: 1 },
                is_final: { [selectedUser.id]: isFinal },
                note: note || null,
            });

            if (response.data.success) {
                toast.current?.show({
                    severity: "success",
                    summary: "Success",
                    detail: "Approval request sent successfully",
                });
                onSuccess?.();
                onHide();
            } else {
                throw new Error(response.data.message || "Failed to send approval");
            }
        } catch (error) {
            console.error("Error sending approval:", error);
            toast.current?.show({
                severity: "error",
                summary: "Error",
                detail:
                    error.response?.data?.message ||
                    "Failed to send approval request",
            });
        } finally {
            setLoading(false);
        }
    };


    const footer = (
        <div className="flex justify-end gap-2">
            <Button
                label="Cancel"
                icon="pi pi-times"
                onClick={onHide}
                className="p-button-text"
                disabled={loading}
            />
            <Button
                label="Send for Approval"
                icon="pi pi-send"
                onClick={handleSubmit}
                loading={loading}
            />
        </div>
    );

    return (
        <>
            <Toast ref={toast} />
            <Dialog
                header="Send for Approval"
                visible={visible}
                onHide={onHide}
                footer={footer}
                style={{ width: "90vw", maxWidth: "1200px" }}
                className="p-fluid"
            >
                <div className="grid">
                    {/* Left Side - User List */}
                    <div className="col-12 md:col-6">
                        <h3 className="text-lg font-semibold mb-3">
                            Select Approver
                        </h3>
                        <div className="border rounded p-2" style={{ maxHeight: "400px", overflowY: "auto" }}>
                            {fetchingUsers ? (
                                <div className="text-center p-4">Loading users...</div>
                            ) : (
                                <DataTable
                                    value={users}
                                    selection={selectedUser}
                                    onSelectionChange={(e) => {
                                        setSelectedUser(e.value);
                                    }}
                                    dataKey="id"
                                    emptyMessage="No users available"
                                    className="p-datatable-sm"
                                >
                                    <Column
                                        selectionMode="single"
                                        headerStyle={{ width: "3rem" }}
                                    />
                                    <Column
                                        field="name"
                                        header="Name"
                                        sortable
                                    />
                                    <Column
                                        field="email"
                                        header="Email"
                                        sortable
                                    />
                                </DataTable>
                            )}
                        </div>
                    </div>

                    {/* Right Side - Selected User Preview */}
                    <div className="col-12 md:col-6">
                        <h3 className="text-lg font-semibold mb-3">
                            Selected Approver
                        </h3>
                        <div className="border rounded p-2" style={{ maxHeight: "400px", overflowY: "auto" }}>
                            {!selectedUser ? (
                                <div className="text-center p-4 text-gray-500">
                                    No approver selected
                                </div>
                            ) : (
                                <div className="space-y-4">
                                    <div className="flex items-center justify-between p-3 border rounded hover:bg-gray-50">
                                        <div className="flex-1">
                                            <div className="font-medium text-base">
                                                {selectedUser.name}
                                            </div>
                                            <div className="text-sm text-gray-500">
                                                {selectedUser.email}
                                            </div>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-2 p-3 bg-purple-50 border border-purple-200 rounded">
                                        <Checkbox
                                            inputId="final-approver"
                                            checked={isFinal}
                                            onChange={(e) => setIsFinal(e.checked)}
                                        />
                                        <label
                                            htmlFor="final-approver"
                                            className="text-sm font-medium text-purple-800 cursor-pointer"
                                        >
                                            Final Approver
                                        </label>
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Note/Comment Section */}
                        <div className="mt-4">
                            <label
                                htmlFor="note"
                                className="block text-sm font-medium mb-2"
                            >
                                Note/Comment (Optional)
                            </label>
                            <InputTextarea
                                id="note"
                                value={note}
                                onChange={(e) => setNote(e.target.value)}
                                rows={4}
                                placeholder="Add any additional notes or comments..."
                                className="w-full"
                            />
                        </div>
                    </div>
                </div>
            </Dialog>
        </>
    );
};

export default SendForApprovalModal;

