import {
    Activity,
    RefreshCw,
    TrendingDown,
    TrendingUp,
    Zap,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import type { MarketType } from "@/lib/market";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";

type Props = { symbol: string; market: MarketType; interval: string; provider?: string };

type Intelligence = {
    provider: string;
    derivatives_available: boolean;
    symbol: string;
    interval: string;
    derivative_period: string;
    updated_at: number;
    regime: { trend: string; volatility: string; momentum: string };
    technical: {
        price: number | null;
        rsi14: number | null;
        sma20: number | null;
        sma50: number | null;
        price_vs_sma20_pct: number | null;
        price_vs_sma50_pct: number | null;
        atr14_pct: number | null;
        return_volatility_pct: number | null;
    };
    derivatives: {
        funding: {
            rate_pct: number | null;
            next_funding_time: number | null;
            mark_price: number | null;
            index_price: number | null;
        };
        open_interest: {
            contracts: number | null;
            historical_contracts: number | null;
            change_pct: number | null;
            samples: number;
        };
        taker: {
            buy_volume: number | null;
            sell_volume: number | null;
            buy_value: number | null;
            sell_value: number | null;
            buy_sell_ratio: number | null;
            buy_pct: number | null;
            sell_pct: number | null;
            samples: number;
        };
        long_short: {
            account: {
                ratio: number | null;
                long_pct: number | null;
                short_pct: number | null;
                timestamp: number | null;
            };
            top_trader_position: {
                ratio: number | null;
                long_pct: number | null;
                short_pct: number | null;
                timestamp: number | null;
            };
        };
        liquidations: {
            long_value: number;
            short_value: number;
            total_value: number;
            events: number;
        };
    };
};

const n = (v: number | null | undefined, digits = 2) =>
    v == null || !Number.isFinite(v) ? "—" : v.toFixed(digits);

const compact = (v: number | null | undefined) => {
    if (v == null || !Number.isFinite(v)) return "—";
    return new Intl.NumberFormat("en-US", {
        notation: "compact",
        maximumFractionDigits: 2,
    }).format(v);
};

const label = (value: string) =>
    value.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());

const fundingCountdown = (timestamp: number | null | undefined) => {
    if (!timestamp) return "—";
    const diff = timestamp - Date.now();
    if (diff <= 0) return "Due";

    const totalMinutes = Math.floor(diff / 60000);
    const hours = Math.floor(totalMinutes / 60);
    const minutes = totalMinutes % 60;
    return `${hours}h ${minutes}m`;
};

export default function FuturesIntelligencePanel({
    symbol,
    market,
    interval,
    provider = "binance",
}: Props) {
    const [data, setData] = useState<Intelligence | null>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const load = useCallback(async () => {
        if (market !== "futures") {
            setData(null);
            return;
        }

        setLoading(true);
        setError(null);
        setData(null);

        try {
            const params = new URLSearchParams({
                symbol,
                market: "futures",
                provider,
                interval,
            });

            const response = await fetch(
                `/market/futures-intelligence?${params.toString()}`,
                {
                    headers: {
                        Accept: "application/json",
                        "X-Requested-With": "XMLHttpRequest",
                    },
                    credentials: "same-origin",
                    cache: "no-store",
                },
            );

            const body = await response.json().catch(() => null);

            if (!response.ok) {
                throw new Error(
                    body?.message ?? "Futures intelligence tidak tersedia.",
                );
            }

            setData(body as Intelligence);
        } catch (e) {
            setData(null);
            setError(
                e instanceof Error
                    ? e.message
                    : "Futures intelligence tidak tersedia.",
            );
        } finally {
            setLoading(false);
        }
    }, [symbol, market, interval, provider]);

    useEffect(() => {
        void load();
    }, [load]);

    useEffect(() => {
        if (!data?.derivatives.funding.next_funding_time) return;
        const timer = window.setInterval(
            () => setData((current) => (current ? { ...current } : current)),
            60_000,
        );
        return () => window.clearInterval(timer);
    }, [data?.derivatives.funding.next_funding_time]);

    if (market !== "futures") return null;

    return (
        <Card className="mt-4 border-border bg-card shadow-xs">
            <CardHeader className="flex flex-row items-center justify-between border-b border-border/60 p-5 pb-4">
                <div className="flex items-center gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-border bg-muted/40 text-amber-500">
                        <Activity className="size-5" />
                    </div>
                    <div>
                        <div className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                            Market Intelligence
                        </div>
                        <div className="mt-0.5 text-sm font-semibold text-foreground">
                            Futures Intelligence · {symbol} · {interval}
                        </div>
                        <div className="mt-0.5 text-[10px] text-muted-foreground">
                            Derivatives window: {data?.derivative_period ?? "—"}
                        </div>
                    </div>
                </div>

                <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => void load()}
                    disabled={loading}
                    className="h-9 gap-2 text-xs font-medium shadow-xs"
                >
                    <RefreshCw
                        className={`size-3.5 ${loading ? "animate-spin" : ""}`}
                    />
                    Refresh
                </Button>
            </CardHeader>

            <CardContent className="p-5 pt-4">
                {error && (
                    <div className="rounded-xl border border-destructive/30 bg-destructive/10 p-3.5 text-xs font-medium text-destructive shadow-xs">
                        {error}
                    </div>
                )}

                {loading && !data && (
                    <div className="py-6 text-center text-xs font-medium text-muted-foreground">
                        Loading futures intelligence…
                    </div>
                )}

                {data && !data.derivatives_available && (
                    <div className="rounded-md border border-amber-500/30 bg-amber-500/5 p-3 text-xs text-muted-foreground" role="status">
                        Data teknikal menggunakan {data.provider.toUpperCase()}. Metrik derivatif pada panel ini saat ini hanya tersedia melalui Binance dan tidak akan mengambil data dari exchange lain.
                    </div>
                )}
                {data && (
                    <div className="space-y-4">
                        <div className="grid gap-3 sm:grid-cols-3">
                            {(
                                [
                                    ["Trend", data.regime.trend],
                                    ["Volatility", data.regime.volatility],
                                    ["Momentum", data.regime.momentum],
                                ] as const
                            ).map(([name, value]) => (
                                <div
                                    key={name}
                                    className="rounded-xl border border-border bg-background p-3.5 shadow-xs"
                                >
                                    <div className="text-[10px] font-semibold uppercase tracking-[.14em] text-muted-foreground">
                                        {name}
                                    </div>
                                    <div className="mt-1 flex items-center gap-1.5 text-sm font-semibold capitalize text-foreground">
                                        {name === "Trend" &&
                                        value === "bullish" ? (
                                            <TrendingUp className="size-4 text-emerald-500" />
                                        ) : null}
                                        {name === "Trend" &&
                                        value === "bearish" ? (
                                            <TrendingDown className="size-4 text-red-500" />
                                        ) : null}
                                        {name === "Momentum" ? (
                                            <Zap className="size-4 text-amber-500" />
                                        ) : null}
                                        {label(value)}
                                    </div>
                                </div>
                            ))}
                        </div>

                        <div className="grid gap-4 lg:grid-cols-2">
                            <div className="rounded-xl border border-border bg-background/40 p-4 shadow-xs">
                                <div className="mb-3 text-xs font-semibold text-foreground">
                                    Technical Context
                                </div>
                                <div className="grid grid-cols-2 gap-3 text-xs">
                                    <Metric
                                        label="Price"
                                        value={n(data.technical.price, 4)}
                                    />
                                    <Metric
                                        label="RSI 14"
                                        value={n(data.technical.rsi14)}
                                    />
                                    <Metric
                                        label="ATR 14"
                                        value={
                                            data.technical.atr14_pct == null
                                                ? "—"
                                                : `${n(data.technical.atr14_pct, 3)}%`
                                        }
                                    />
                                    <Metric
                                        label="Return Volatility"
                                        value={
                                            data.technical
                                                .return_volatility_pct == null
                                                ? "—"
                                                : `${n(data.technical.return_volatility_pct, 3)}%`
                                        }
                                    />
                                    <Metric
                                        label="Price vs SMA20"
                                        value={
                                            data.technical.price_vs_sma20_pct ==
                                            null
                                                ? "—"
                                                : `${n(data.technical.price_vs_sma20_pct, 3)}%`
                                        }
                                    />
                                    <Metric
                                        label="Price vs SMA50"
                                        value={
                                            data.technical.price_vs_sma50_pct ==
                                            null
                                                ? "—"
                                                : `${n(data.technical.price_vs_sma50_pct, 3)}%`
                                        }
                                    />
                                </div>
                            </div>

                            <div className="rounded-xl border border-border bg-background/40 p-4 shadow-xs">
                                <div className="mb-3 text-xs font-semibold text-foreground">
                                    Funding & Open Interest
                                </div>
                                <div className="grid grid-cols-2 gap-3 text-xs">
                                    <Metric
                                        label="Funding"
                                        value={
                                            data.derivatives.funding.rate_pct ==
                                            null
                                                ? "—"
                                                : `${n(data.derivatives.funding.rate_pct, 4)}%`
                                        }
                                    />
                                    <Metric
                                        label="Next Funding"
                                        value={fundingCountdown(
                                            data.derivatives.funding
                                                .next_funding_time,
                                        )}
                                    />
                                    <Metric
                                        label="Mark Price"
                                        value={n(
                                            data.derivatives.funding.mark_price,
                                            4,
                                        )}
                                    />
                                    <Metric
                                        label="Open Interest"
                                        value={compact(
                                            data.derivatives.open_interest
                                                .contracts,
                                        )}
                                    />
                                    <Metric
                                        label="OI Change"
                                        value={
                                            data.derivatives.open_interest
                                                .change_pct == null
                                                ? "—"
                                                : `${n(data.derivatives.open_interest.change_pct, 2)}%`
                                        }
                                    />
                                    <Metric
                                        label="OI Samples"
                                        value={String(
                                            data.derivatives.open_interest
                                                .samples,
                                        )}
                                    />
                                </div>
                            </div>

                            <div className="rounded-xl border border-border bg-background/40 p-4 shadow-xs">
                                <div className="mb-3 text-xs font-semibold text-foreground">
                                    Taker Flow
                                </div>
                                <div className="grid grid-cols-2 gap-3 text-xs">
                                    <Metric
                                        label="Buy %"
                                        value={
                                            data.derivatives.taker.buy_pct ==
                                            null
                                                ? "—"
                                                : `${n(data.derivatives.taker.buy_pct)}%`
                                        }
                                    />
                                    <Metric
                                        label="Sell %"
                                        value={
                                            data.derivatives.taker.sell_pct ==
                                            null
                                                ? "—"
                                                : `${n(data.derivatives.taker.sell_pct)}%`
                                        }
                                    />
                                    <Metric
                                        label="Buy/Sell Ratio"
                                        value={n(
                                            data.derivatives.taker
                                                .buy_sell_ratio,
                                            3,
                                        )}
                                    />
                                    <Metric
                                        label="Samples"
                                        value={String(
                                            data.derivatives.taker.samples,
                                        )}
                                    />
                                </div>
                            </div>

                            <div className="rounded-xl border border-border bg-background/40 p-4 shadow-xs">
                                <div className="mb-3 text-xs font-semibold text-foreground">
                                    Long / Short
                                </div>
                                <div className="grid grid-cols-2 gap-3 text-xs">
                                    <Metric
                                        label="Accounts Long"
                                        value={
                                            data.derivatives.long_short.account
                                                .long_pct == null
                                                ? "—"
                                                : `${n(data.derivatives.long_short.account.long_pct)}%`
                                        }
                                    />
                                    <Metric
                                        label="Accounts Short"
                                        value={
                                            data.derivatives.long_short.account
                                                .short_pct == null
                                                ? "—"
                                                : `${n(data.derivatives.long_short.account.short_pct)}%`
                                        }
                                    />
                                    <Metric
                                        label="Top Traders Long"
                                        value={
                                            data.derivatives.long_short
                                                .top_trader_position.long_pct ==
                                            null
                                                ? "—"
                                                : `${n(data.derivatives.long_short.top_trader_position.long_pct)}%`
                                        }
                                    />
                                    <Metric
                                        label="Top Traders Short"
                                        value={
                                            data.derivatives.long_short
                                                .top_trader_position
                                                .short_pct == null
                                                ? "—"
                                                : `${n(data.derivatives.long_short.top_trader_position.short_pct)}%`
                                        }
                                    />
                                </div>
                            </div>
                        </div>

                        <div className="rounded-xl border border-border bg-background/40 p-4 shadow-xs">
                            <div className="mb-3 text-xs font-semibold text-foreground">
                                Liquidation Flow
                            </div>
                            <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
                                <Metric
                                    label="Long Liquidated"
                                    value={compact(
                                        data.derivatives.liquidations
                                            .long_value,
                                    )}
                                />
                                <Metric
                                    label="Short Liquidated"
                                    value={compact(
                                        data.derivatives.liquidations
                                            .short_value,
                                    )}
                                />
                                <Metric
                                    label="Total Value"
                                    value={compact(
                                        data.derivatives.liquidations
                                            .total_value,
                                    )}
                                />
                                <Metric
                                    label="Events"
                                    value={String(
                                        data.derivatives.liquidations.events,
                                    )}
                                />
                            </div>
                        </div>

                        <p className="text-[11px] text-muted-foreground">
                            Intelligence ini bersifat observasional. Data
                            derivatives memakai window yang dipetakan ke
                            interval chart dan tidak otomatis mengubah
                            confidence Signal Engine.
                        </p>
                    </div>
                )}
            </CardContent>
        </Card>
    );
}

function Metric({ label: title, value }: { label: string; value: string }) {
    return (
        <div className="rounded-lg border border-border/60 bg-background p-2.5 shadow-xs">
            <div className="text-[10px] uppercase tracking-wider text-muted-foreground">
                {title}
            </div>
            <div className="mt-1 font-semibold tabular-nums text-foreground">
                {value}
            </div>
        </div>
    );
}
