import { History, RefreshCw } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import type { MarketType } from "@/lib/market";
import type { SignalHistoryResponse } from "@/types/insight";

import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { DataCardState } from "./DataCardState";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";

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

const fmt = (value: number | null) =>
    value == null
        ? "—"
        : value.toLocaleString(undefined, { maximumFractionDigits: 8 });

const duration = (seconds: number | null) => {
    if (seconds == null) return "—";
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}m`;
    const hours = Math.floor(minutes / 60);
    const remaining = minutes % 60;
    return `${hours}h ${remaining}m`;
};

const statusLabel = (status: string) =>
    ({
        active: "ACTIVE",
        target_hit: "TARGET HIT",
        invalidated: "INVALIDATED",
        inactive: "INACTIVE",
    })[status] ?? status.toUpperCase();

export default function SignalHistory({
    symbol,
    market,
    interval,
    provider,
    enabled,
}: Props) {
    const [data, setData] = useState<SignalHistoryResponse | null>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [status, setStatus] = useState("all");
    const requestRef = useRef<AbortController | null>(null);

    const load = useCallback(async () => {
        if (!enabled) return;
        requestRef.current?.abort();
        const controller = new AbortController();
        requestRef.current = controller;
        setLoading(true);
        setError(null);
        try {
            const params = new URLSearchParams({
                symbol,
                market,
                interval,
                provider,
                per_page: "10",
            });
            if (status && status !== "all") params.set("status", status);
            const response = await fetch(
                `/market/signal-history?${params.toString()}`,
                {
                    headers: {
                        Accept: "application/json",
                        "X-Requested-With": "XMLHttpRequest",
                    },
                    credentials: "same-origin",
                    cache: "no-store",
                    signal: controller.signal,
                },
            );
            const raw: unknown = await response.json();
            if (!response.ok) {
                const message =
                    raw &&
                    typeof raw === "object" &&
                    "message" in raw &&
                    typeof raw.message === "string"
                        ? raw.message
                        : "Gagal mengambil signal history.";
                throw new Error(message);
            }
            setData(raw as SignalHistoryResponse);
        } catch (e) {
            if (e instanceof DOMException && e.name === "AbortError") return;
            setError(
                e instanceof Error
                    ? e.message
                    : "Gagal mengambil signal history.",
            );
        } finally {
            if (!controller.signal.aborted) setLoading(false);
        }
    }, [enabled, interval, market, provider, status, symbol]);

    useEffect(() => {
        void load();
        return () => {
            requestRef.current?.abort();
            requestRef.current = null;
        };
    }, [load]);

    if (!enabled) return null;

    return (
        <Card className="mt-3 border-border bg-card shadow-xs py-4 px-0!">
            <CardHeader className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between border-b border-border/60">
                <div className="flex items-center gap-3.5">
                    <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-border bg-muted/40 text-primary">
                        <History className="size-5" />
                    </div>
                    <div>
                        <div className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                            Archive Logs
                        </div>
                        <div className="mt-0.5 text-base font-bold text-foreground flex items-center gap-2">
                            <span>Signal History</span>
                            <Badge
                                variant="secondary"
                                className="px-2 py-0.5 text-[10px] font-medium"
                            >
                                {symbol}
                            </Badge>
                            <Badge
                                variant="outline"
                                className="px-2 py-0.5 text-[10px] font-medium uppercase"
                            >
                                {provider}
                            </Badge>
                        </div>
                    </div>
                </div>

                <div className="flex flex-wrap items-center gap-2">
                    <Select value={status} onValueChange={setStatus}>
                        <SelectTrigger className="h-9 w-[140px] text-xs font-medium shadow-xs">
                            <SelectValue placeholder="All status" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="all">All status</SelectItem>
                            <SelectItem value="active">Active</SelectItem>
                            <SelectItem value="target_hit">
                                Target hit
                            </SelectItem>
                            <SelectItem value="invalidated">
                                Invalidated
                            </SelectItem>
                        </SelectContent>
                    </Select>

                    <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>
                </div>
            </CardHeader>

            <CardContent className="p-5 pt-4">
                <DataCardState
                    loading={loading}
                    error={error}
                    hasData={Boolean(data)}
                    onRetry={() => void load()}
                    loadingLabel="Loading signal history…"
                    empty={data?.items.length === 0}
                    emptyLabel="Belum ada signal history untuk filter ini."
                />

                {data && data.items.length > 0 && (
                    <div className="space-y-3">
                        {data.items.map((item) => {
                            const isLong = item.direction === "long";
                            return (
                                <div
                                    key={item.id}
                                    className="rounded-xl border border-border bg-background p-4 transition-colors hover:border-border/80 shadow-xs"
                                >
                                    <div className="flex flex-wrap items-center gap-2">
                                        <Badge
                                            variant="outline"
                                            className={`rounded-md px-2 py-0.5 text-xs font-bold ${
                                                isLong
                                                    ? "border-emerald-500/20 bg-emerald-500/10 text-emerald-500"
                                                    : "border-rose-500/20 bg-rose-500/10 text-rose-500"
                                            }`}
                                        >
                                            {isLong ? "LONG" : "SHORT"}
                                        </Badge>
                                        <Badge
                                            variant="secondary"
                                            className="rounded-md px-2 py-0.5 text-[11px] font-medium"
                                        >
                                            {item.interval}
                                        </Badge>
                                        <Badge
                                            variant="outline"
                                            className="rounded-md px-2 py-0.5 text-[11px] font-semibold text-muted-foreground"
                                        >
                                            {statusLabel(item.status)}
                                        </Badge>
                                        <span className="ml-auto text-[11px] font-normal text-muted-foreground">
                                            {item.detected_at
                                                ? new Date(
                                                      item.detected_at * 1000,
                                                  ).toLocaleString()
                                                : "—"}
                                        </span>
                                    </div>
                                    <div className="mt-3 grid gap-2.5 sm:grid-cols-6">
                                        <Mini
                                            label="Entry"
                                            value={fmt(item.entry)}
                                        />
                                        <Mini
                                            label="SL"
                                            value={fmt(item.stop_loss)}
                                        />
                                        <Mini
                                            label="TP"
                                            value={fmt(item.take_profit)}
                                        />
                                        <Mini
                                            label="Confidence"
                                            value={
                                                item.confidence == null
                                                    ? "—"
                                                    : `${item.confidence}%`
                                            }
                                        />
                                        <Mini
                                            label="R:R"
                                            value={
                                                item.risk_reward == null
                                                    ? "—"
                                                    : `1 : ${item.risk_reward.toFixed(2)}`
                                            }
                                        />
                                        <Mini
                                            label="Duration"
                                            value={duration(
                                                item.duration_seconds,
                                            )}
                                        />
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}
            </CardContent>
        </Card>
    );
}

function Mini({ label, value }: { label: string; value: string }) {
    return (
        <div className="rounded-xl border border-border bg-card p-2.5 shadow-xs">
            <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                {label}
            </div>
            <div className="mt-1 text-xs font-bold text-foreground font-mono">
                {value}
            </div>
        </div>
    );
}
