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

const ApprovalActionModal = ({
    visible,
    onHide,
    approvalData,
    onSuccess,
}) => {
    const [actionType, setActionType] = useState(null);
    const [comment, setComment] = useState("");
    const [reassignUserId, setReassignUserId] = useState(null);
    const [users, setUsers] = useState([]);
    const [isFinalApprove, setIsFinalApprove] = useState(false);
    const [reassignAsFinal, setReassignAsFinal] = useState(false);
    const [loading, setLoading] = useState(false);
    const toast = useRef(null);

    useEffect(() => {
        if (visible) {
            setActionType(null);
            setComment("");
            setReassignUserId(null);
            setIsFinalApprove(false);
            setReassignAsFinal(false);
            fetchUsers();
        }
    }, [visible]);

    const fetchUsers = async () => {
        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);
        }
    };

    const handleSubmitAction = async () => {
        if (!approvalData) return;

        try {
            setLoading(true);
            let response;
            const payload = {
                assignment_id: approvalData.assignment_id,
            };

            if (actionType === "approve" || actionType === "reject") {
                if (comment) {
                    payload.comment = comment;
                }
                if (actionType === "approve" && isFinalApprove) {
                    payload.is_final = true;
                }
                response = await axios.post(
                    route(`approvals.${actionType}`, approvalData.approval_id),
                    payload
                );
            } else if (actionType === "reassign") {
                if (!reassignUserId) {
                    toast.current?.show({
                        severity: "warn",
                        summary: "Validation",
                        detail: "Please select a user to reassign to",
                    });
                    setLoading(false);
                    return;
                }
                payload.new_user_id = reassignUserId;
                if (reassignAsFinal) {
                    payload.is_final = true;
                }
                if (comment) {
                    payload.comment = comment;
                }
                response = await axios.post(
                    route("approvals.reassign", approvalData.approval_id),
                    payload
                );
            } else if (actionType === "comment") {
                if (!comment.trim()) {
                    toast.current?.show({
                        severity: "warn",
                        summary: "Validation",
                        detail: "Please enter a comment",
                    });
                    setLoading(false);
                    return;
                }
                response = await axios.post(
                    route("approvals.comment", approvalData.approval_id),
                    { comment }
                );
            }

            if (response?.data.success) {
                toast.current?.show({
                    severity: "success",
                    summary: "Success",
                    detail: `Action completed successfully`,
                });
                onHide();
                onSuccess?.();
            }
        } catch (error) {
            console.error("Error performing action:", error);
            toast.current?.show({
                severity: "error",
                summary: "Error",
                detail:
                    error.response?.data?.message ||
                    "Failed to perform action",
            });
        } finally {
            setLoading(false);
        }
    };

    const actionModalFooter = (
        <div className="flex justify-end gap-2">
            <Button
                label="Cancel"
                icon="pi pi-times"
                onClick={() => {
                    onHide();
                    setActionType(null);
                    setComment("");
                    setReassignUserId(null);
                    setIsFinalApprove(false);
                    setReassignAsFinal(false);
                }}
                className="p-button-text"
                disabled={loading}
            />
            {actionType && (
                <Button
                    label={
                        actionType === "approve"
                            ? "Approve"
                            : actionType === "reject"
                            ? "Reject"
                            : actionType === "reassign"
                            ? "Reassign"
                            : "Add Comment"
                    }
                    icon={
                        actionType === "approve"
                            ? "pi pi-check"
                            : actionType === "reject"
                            ? "pi pi-times"
                            : actionType === "reassign"
                            ? "pi pi-forward"
                            : "pi pi-comment"
                    }
                    onClick={handleSubmitAction}
                    loading={loading}
                    className={
                        actionType === "approve"
                            ? "p-button-success"
                            : actionType === "reject"
                            ? "p-button-danger"
                            : actionType === "reassign"
                            ? "p-button-warning"
                            : "p-button-info"
                    }
                />
            )}
        </div>
    );

    if (!approvalData) return null;

    return (
        <>
            <Toast ref={toast} />
            <Dialog
                header="Take Action"
                visible={visible}
                onHide={() => {
                    onHide();
                    setActionType(null);
                    setComment("");
                    setReassignUserId(null);
                    setIsFinalApprove(false);
                    setReassignAsFinal(false);
                }}
                footer={actionModalFooter}
                style={{ width: "500px" }}
            >
                <div className="space-y-4">
                    <div>
                        <strong>Module:</strong> {approvalData.module_name || "N/A"}
                    </div>
                    <div>
                        <strong>Reference ID:</strong> {approvalData.reference_id || "N/A"}
                    </div>
                    {approvalData.is_final  == 1 && (
                        <div className="p-2 bg-purple-50 border border-purple-200 rounded">
                            <strong className="text-purple-800">⚠️ Final Approver:</strong>{" "}
                            <span className="text-purple-700">
                                Your approval will immediately finalize this request. You cannot reassign.
                            </span>
                        </div>
                    )}
                    {approvalData.note && (
                        <div>
                            <strong>Note:</strong> {approvalData.note}
                        </div>
                    )}

                    {/* Action Type Dropdown */}
                    <div>
                        <label className="block text-sm font-medium mb-2">
                            Select Action:
                        </label>
                        <Dropdown
                            value={actionType}
                            options={[
                                ...(approvalData.assignment_status === 'pending' ? [
                                    { label: "Approve", value: "approve" },
                                    { label: "Reject", value: "reject" }
                                ] : []),
                                { label: "Add Comment", value: "comment" },
                                ...(approvalData.can_reassign ? [
                                    { label: "Reassign", value: "reassign" }
                                ] : [])
                            ]}
                            onChange={(e) => {
                                setActionType(e.value);
                                setComment("");
                                setReassignUserId(null);
                                setIsFinalApprove(false);
                                setReassignAsFinal(false);
                            }}
                            placeholder="Select an action"
                            className="w-full"
                        />
                    </div>

                    {/* Reassign User Selection */}
                    {actionType === "reassign" && (
                        <div className="space-y-3">
                            <div>
                                <label className="block text-sm font-medium mb-2">
                                    Reassign To:
                                </label>
                                <Dropdown
                                    value={reassignUserId}
                                    options={users}
                                    onChange={(e) =>
                                        setReassignUserId(e.value)
                                    }
                                    optionLabel="name"
                                    optionValue="id"
                                    placeholder="Select User"
                                    className="w-full"
                                />
                            </div>
                            <div className="flex items-center gap-2 p-3 bg-purple-50 border border-purple-200 rounded">
                                <Checkbox
                                    inputId="reassign-as-final"
                                    checked={reassignAsFinal}
                                    onChange={(e) => setReassignAsFinal(e.checked)}
                                />
                                <label
                                    htmlFor="reassign-as-final"
                                    className="text-sm font-medium text-purple-800 cursor-pointer"
                                >
                                    Mark as Final Approver
                                </label>
                            </div>
                        </div>
                    )}

                    {/* Final Approve Checkbox */}
                    {actionType === "approve" && 
                     !approvalData.has_final_approver && (
                        <div className="flex items-center gap-2 p-3 bg-purple-50 border border-purple-200 rounded">
                            <Checkbox
                                inputId="final-approve"
                                checked={isFinalApprove}
                                onChange={(e) => setIsFinalApprove(e.checked)}
                            />
                            <label
                                htmlFor="final-approve"
                                className="text-sm font-medium text-purple-800 cursor-pointer"
                            >
                                Final Approve (Will immediately finalize this approval)
                            </label>
                        </div>
                    )}

                    {/* Comment/Note */}
                    {actionType && (
                        <div>
                            <label className="block text-sm font-medium mb-2">
                                {actionType === "comment"
                                    ? "Comment"
                                    : "Comment (Optional)"}
                            </label>
                            <InputTextarea
                                value={comment}
                                onChange={(e) =>
                                    setComment(e.target.value)
                                }
                                rows={4}
                                placeholder="Enter your comment..."
                                className="w-full"
                            />
                        </div>
                    )}

                    {/* History */}
                    {approvalData.history &&
                        approvalData.history.length > 0 && (
                            <div>
                                <strong>History:</strong>
                                <div className="mt-2 space-y-1 max-h-40 overflow-y-auto">
                                    {approvalData.history.map(
                                        (h, idx) => (
                                            <div
                                                key={idx}
                                                className="text-sm border-l-2 pl-2 border-gray-300"
                                            >
                                                <span className="font-medium">
                                                    {h.user}
                                                </span>{" "}
                                                {h.action} - {h.comment || "No comment"}
                                                <br />
                                                <span className="text-gray-500 text-xs">
                                                    {h.created_at}
                                                </span>
                                            </div>
                                        )
                                    )}
                                </div>
                            </div>
                        )}
                </div>
            </Dialog>
        </>
    );
};

export default ApprovalActionModal;

