"use client"

import { getTransactionMyGoldflea, getTransactionMyIncome, getTransactionMyPoints, getTransactionMyTopup } from "@/libs/axios/modules/transaction";
import { PostModel, TransactionModel, UserModel } from "@/models";
import { AnimatePresence, motion } from "framer-motion";
import { useCallback, useState } from "react";
import Skeleton from "react-loading-skeleton";
import Breadcrumbs from "../components/Breadcrumbs";
import CalendarWidget from "./components/CalendarWidget";
import CardDashboard from "./components/CardDashboard";
import DashboardNovel from "./components/DashboardNovel";

type CoinHistoryItem = {
    id: string;
    title: string;
    amount: number;
    created_at: string;
    status?: string;
};

type CoinHistoryType = "topup" | "points" | "goldflea" | "income";

type CoinHistoryState = {
    open: boolean;
    type: CoinHistoryType | null;
    loading: boolean;
    items: CoinHistoryItem[];
    limit: number;
    page: number;
    hasMore: boolean;
};

type TransactionsState = {
    loading: boolean;
    data: TransactionModel[];
    limit: number;
    page: number;
    total: number;
};

interface DashboardPageState {
    myAllPosts: PostModel[];
    transactionNovel: TransactionModel[];
    topupHistory?: {
        items: CoinHistoryItem[];
        hasMore: boolean;
    };
    user: UserModel;
    token: string;
}

export default function DashboardPage({ myAllPosts, transactionNovel, user, token }: DashboardPageState) {
    const [coinHistory, setCoinHistory] = useState<CoinHistoryState>({
        open: false,
        type: null,
        loading: false,
        items: [],
        limit: 10,
        page: 1,
        hasMore: false,
    });

    const [transactions, setTransactions] = useState<TransactionsState>({
        loading: false,
        data: transactionNovel ?? [],
        limit: 10,
        page: 1,
        total: 0,
    });

    const fetchCoinHistoryPage = useCallback(
        async (type: CoinHistoryType, page: number, limit: number) => {
            if (!token) return { items: [] as CoinHistoryItem[], hasMore: false };

            const request = (() => {
                switch (type) {
                    case "topup":
                        return getTransactionMyTopup;
                    case "points":
                        return getTransactionMyPoints;
                    case "goldflea":
                        return getTransactionMyGoldflea;
                    case "income":
                        return getTransactionMyIncome;
                }
            })();

            const { data: response } = await request(token, { page, limit });
            const total = response?.pagination?.total ?? 0;
            const isLastPage = page * limit >= total;

            const items: CoinHistoryItem[] = (response?.data ?? []).map((trx: TransactionModel) => {
                const createdAt = trx.created_at ? new Date(trx.created_at) : null;
                const createdAtText =
                    createdAt && !Number.isNaN(createdAt.getTime())
                        ? createdAt.toLocaleString("id-ID")
                        : "";

                const amount = type === "income" ? Number(trx.nominal ?? 0) : Number(trx.coins ?? 0);

                return {
                    id: String(trx.id),
                    title: String(trx.title ?? trx.code ?? "-"),
                    amount,
                    status: trx.status,
                    created_at: createdAtText,
                };
            }).filter((item: any) => item.status === "successful");;

            return { items, hasMore: !isLastPage };
        },
        [token]
    );

    const loadCoinHistory = useCallback(
        async (type: CoinHistoryType, page: number) => {
            if (!token) return;

            setCoinHistory((prev) => ({
                ...prev,
                open: true,
                type,
                loading: true,
                page,
                items: page > 1 ? prev.items : [],
            }));

            try {
                const result = await fetchCoinHistoryPage(type, page, coinHistory.limit);
                setCoinHistory((prev) => ({
                    ...prev,
                    open: true,
                    type,
                    loading: false,
                    page,
                    items:
                        page > 1
                            ? [...prev.items, ...result.items.filter((x) => !prev.items.some((y) => y.id === x.id))]
                            : result.items,
                    hasMore: result.hasMore,
                }));
            } catch (error) {
                console.error("Gagal mengambil history koin:", error);
                setCoinHistory((prev) => ({ ...prev, loading: false }));
            }
        },
        [coinHistory.limit, fetchCoinHistoryPage, token]
    );

    const handleOpenCoinHistory = useCallback(
        (type: CoinHistoryType) => {
            if (coinHistory.open && coinHistory.type === type) {
                setCoinHistory((prev) => ({ ...prev, open: false }));
                return;
            }

            void loadCoinHistory(type, 1);
        },
        [coinHistory.open, coinHistory.type, loadCoinHistory]
    );

    const DashboardListSkeleton = ({ rows = 5 }: { rows?: number }) => {
        return (
            <div className="flex flex-col gap-3">
                {Array.from({ length: rows }).map((_, idx) => (
                    <Skeleton key={idx} height={20} />
                ))}
            </div>
        );
    };

    return (
        <div className="flex flex-col gap-6 w-full ">
            <Breadcrumbs title="Dashboard" href="/user" />
            <div className="w-full bg-white p-4 rounded-lg shadow-md">
                <div className="grid grid-cols-2 lg:grid-cols-4 w-full items-stretch gap-3 lg:gap-4">
                    <CardDashboard
                        title="Total Coin"
                        value={user.totalTopupCoins}
                        bgColor="#FB7600"
                        buttonText="Detail"
                        onButtonClick={() => handleOpenCoinHistory("topup")}
                        bgImage="/assets/Main/Writer/DashboardAssets/coin.png"
                    />
                    <CardDashboard
                        title="Total Point"
                        value={user.totalPoints}
                        bgColor="#32689F"
                        buttonText="Detail"
                        onButtonClick={() => handleOpenCoinHistory("points")}
                        bgImage="/assets/Main/Writer/DashboardAssets/coinb.png"
                    />
                    <CardDashboard
                        title="Total Goldflea"
                        value={user.totalGoldflea}
                        bgColor="#6B4E0B"
                        buttonText="Detail"
                        onButtonClick={() => handleOpenCoinHistory("goldflea")}
                        bgImage="/assets/Main/Writer/DashboardAssets/coinf.png"
                    />
                    <CardDashboard
                        title="Total Income"
                        value={user.totalIncome}
                        bgColor="#2E802B"
                        buttonText="Detail"
                        onButtonClick={() => handleOpenCoinHistory("income")}
                        bgImage="/assets/Main/Writer/DashboardAssets/coint.png"
                    />
                </div>

                <AnimatePresence>
                    {coinHistory.open && (
                        <motion.div
                            className="mt-6! rounded-2xl bg-white shadow-sm ring-1 ring-gray-100"
                            initial={{ opacity: 0, y: -16 }}
                            animate={{ opacity: 1, y: 0 }}
                            exit={{ opacity: 0, y: -16 }}
                            transition={{ type: "spring", stiffness: 300, damping: 28 }}
                        >
                            <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
                                <div>
                                    <p className="text-sm font-semibold text-gray-900">
                                        Riwayat Transaksi
                                    </p>
                                    <p className="text-xs text-gray-500 mt-0.5">
                                        {coinHistory.type === "topup"
                                            ? "Topup Coin"
                                            : coinHistory.type === "points"
                                                ? "Poin"
                                                : coinHistory.type === "goldflea"
                                                    ? "Goldflea"
                                                    : "Income"}
                                    </p>
                                </div>

                                <button
                                    type="button"
                                    className="text-xs px-3 py-1.5 rounded-lg bg-green-50 text-green-600 border border-green-200 transition cursor-pointer"
                                    onClick={() =>
                                        setCoinHistory((prev) => ({ ...prev, open: false }))
                                    }
                                >
                                    Tutup
                                </button>
                            </div>

                            <div className="max-h-80 overflow-y-auto px-5 py-4">
                                {coinHistory.loading ? (
                                    <DashboardListSkeleton rows={6} />
                                ) : coinHistory.items.length === 0 ? (
                                    <div className="flex items-center justify-center py-10">
                                        <p className="text-sm text-gray-400 italic">
                                            Belum ada transaksi
                                        </p>
                                    </div>
                                ) : (
                                    <div className="flex flex-col gap-4">
                                        {coinHistory.items.map((item) => (
                                            <div
                                                key={item.id}
                                                className="flex items-center justify-between"
                                            >
                                                <div className="min-w-0">
                                                    <p className="text-sm font-medium text-gray-900 truncate">
                                                        {item.title}
                                                    </p>
                                                    <p className="text-xs text-gray-500 mt-1 truncate capitalize flex items-center gap-1">
                                                        {item.status && (
                                                            <span className={`
                                                inline-flex items-center gap-2 px-2 py-0.5 rounded-full text-[10px] font-semibold capitalize
                                                ${item.status === "successful"
                                                                    ? "bg-green-100 text-green-700"
                                                                    : item.status === "pending"
                                                                        ? "bg-yellow-100 text-yellow-700"
                                                                        : "bg-red-100 text-red-700"
                                                                }
                                            `}>
                                                                <span className={`
                                                    w-1.5 h-1.5 rounded-full ml-1
                                                    ${item.status === "successful"
                                                                        ? "bg-green-500"
                                                                        : item.status === "pending"
                                                                            ? "bg-yellow-500"
                                                                            : "bg-red-500"
                                                                    }
                                                `} />
                                                                {item.status}
                                                            </span>
                                                        )}
                                                        <span>•</span>
                                                        <span>{item.created_at}</span>
                                                    </p>
                                                </div>

                                                <p
                                                    className={`text-sm font-semibold whitespace-nowrap ${coinHistory.type === "income"
                                                            ? "text-green-600"
                                                            : "text-gray-800"
                                                        }`}
                                                >
                                                    {coinHistory.type === "income"
                                                        ? `Rp ${Number(item.amount || 0).toLocaleString()}`
                                                        : `${Number(item.amount || 0).toLocaleString()} ${coinHistory.type === "topup"
                                                            ? "coin"
                                                            : coinHistory.type === "points"
                                                                ? "point"
                                                                : "goldflea"
                                                        }`}
                                                </p>
                                            </div>
                                        ))}

                                        {coinHistory.hasMore && (
                                            <button
                                                type="button"
                                                className="mt-2 w-full py-2 rounded-xl bg-gray-50 hover:bg-gray-100 text-sm font-medium transition disabled:opacity-50"
                                                disabled={coinHistory.loading}
                                                onClick={() => {
                                                    if (!coinHistory.type) return;
                                                    void loadCoinHistory(
                                                        coinHistory.type,
                                                        coinHistory.page + 1
                                                    );
                                                }}
                                            >
                                                {coinHistory.loading ? "Memuat..." : "Show more"}
                                            </button>
                                        )}
                                    </div>
                                )}
                            </div>
                        </motion.div>
                    )}
                </AnimatePresence>
            </div>

            <div className="flex flex-col xl:flex-row gap-6 w-full min-w-0">
                <div className="w-full xl:w-2/3 min-w-0">
                    <DashboardNovel transactions={transactions.data} loading={transactions.loading} token={token} />
                </div>
                <div className="w-full xl:w-1/3 min-w-0">
                    <CalendarWidget token={token} />
                </div>
            </div>
        </div>
    );
}