"use client";
import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import axios from "axios";
import PageContainer from "@/app/components/container/PageContainer";
import {
    Box,
    Grid,
    Typography,
    Alert,
    LinearProgress,
    Switch
} from "@mui/material";
import BaseCard from "../components/shared/BaseCard";
import { getSession } from "@/utils/sessionData";

export default function PayoutMethodsPage() {
    const router = useRouter();

    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);
    const [sessionData, setSessionData] = useState<any>();
    const [user, setUser] = useState<any>();
    const [methods, setMethods] = useState<any[]>([]);

    // Clear alerts
    useEffect(() => {
        if (error || success) {
            const timer = setTimeout(() => {
                setError(null);
                setSuccess(null);
            }, 3000);
            return () => clearTimeout(timer);
        }
    }, [error, success]);

    const checkSession = async () => {
        const session = getSession();
        if (!session?.admin_id && !session?.token) {
            router.push("/login");
        }
    };

    const getAdmin = async () => {
        setIsLoading(true);
        try {
            const token = sessionData?.token ?? "";
            const response = await axios.post("/api/getAdmin", { token });

            if (response?.data?.status !== "error") {
                setUser(response?.data?.admin);
            } else {
                setError(response?.data?.message);
            }
        } catch (error: any) {
            setError(error?.message ?? "Unable to fetch admin");
        }
        setIsLoading(false);
    };

    // -------------------------
    // FETCH PAYOUT METHODS
    // -------------------------
    const getPayoutMethods = async () => {
        setIsLoading(true);
        try {
            const token = sessionData?.token ?? "";
            const response = await axios.post("/api/payoutMethods", { token });

            if (response?.data?.status !== "error") {
                setMethods(response?.data?.payoutMethods || []);
            } else {
                setError(response?.data?.message);
            }
        } catch (error: any) {
            setError(error?.message ?? "Unable to fetch payout methods");
        }
        setIsLoading(false);
    };

    // -------------------------
    // TOGGLE ENABLE / DISABLE
    // -------------------------
    const handleToggleStatus = async (id: number, currentStatus: number) => {
        try {
            setIsLoading(true);

            const newStatus = currentStatus == 1 ? 0 : 1;

            const response = await axios.post("/api/updatePayoutMethodStatus", {
                token: sessionData?.token,
                id,
                status: newStatus
            });

            if (response.data.status === "error") {
                throw new Error(response.data.message);
            }

            setSuccess("Updated successfully!");

            setMethods((prev) =>
                prev.map((m) =>
                    m.id === id ? { ...m, status: newStatus } : m
                )
            );
        } catch (err: any) {
            setError(err.message || "Failed to update payout method");
        } finally {
            setIsLoading(false);
        }
    };

    const formatMethodName = (value: string) => {
        if (value === "coinflow") return "CoinFlow ACH";
        if (value === "coinflow_paypal") return "CoinFlow Paypal";
        if (value === "coinflow_venmo") return "CoinFlow Venmo";
        return value;
    };

    useEffect(() => {
        checkSession();
    }, []);

    useEffect(() => {
        const session = getSession();
        setSessionData(session);
    }, []);

    useEffect(() => {
        if (sessionData?.token) {
            getAdmin();
            getPayoutMethods();
        }
    }, [sessionData?.token, sessionData?.admin_id]);

    useEffect(() => {
        if (user && user.role !== "Super") {
            router.push("/dashboard");
        }
    }, [user]);

    return (
        <PageContainer
            title={"Payout Methods - Emanage"}
            description="Payout Methods Management"
        >
            <Grid container spacing={2}>
                <Grid sx={{ width: { xs: "100%", lg: "100%" } }}>
                    {error && <Alert severity="error">{error}</Alert>}
                    {success && <Alert severity="success">{success}</Alert>}
                </Grid>

                <Grid sx={{ width: { xs: "100%", lg: "100%" } }}>
                    <BaseCard title="Payout Methods">
                        {isLoading && (
                            <>
                                <LinearProgress />
                                <br />
                            </>
                        )}

                        <Box sx={{ width: "100%" }}>
                            {methods.length > 0 &&
                                methods.map((method) => (
                                    <Box
                                        key={method.id}
                                        sx={{
                                            display: "flex",
                                            justifyContent: "space-between",
                                            alignItems: "center",
                                            py: 1.5,
                                            //   borderBottom: "1px solid #eee"
                                        }}
                                    >
                                        <Typography fontWeight={600}>
                                            {formatMethodName(method.method)}
                                        </Typography>

                                        <Switch
                                            checked={method.status == 1}
                                            color="success"
                                            onChange={() =>
                                                handleToggleStatus(method.id, method.status)
                                            }
                                        />
                                    </Box>
                                ))}

                            {!isLoading && methods.length === 0 && (
                                <Typography align="center" sx={{ mt: 3 }}>
                                    No payout methods found
                                </Typography>
                            )}
                        </Box>
                    </BaseCard>
                </Grid>
            </Grid>
        </PageContainer>
    );
}
