import { Head } from "@inertiajs/react";
import { ArrowLeft, Download, Printer, Trash2 } from "lucide-react";
import { useEffect, useState, type ReactNode } from "react";
import { Button } from "@/components/ui/button";

import { useI18n } from "@/lib/i18n";
type Trade = {
    signal_time: number;
    entry_time: number;
    exit_time: number;
    direction: string;
    score: number;
    confidence: number;
    confirmation_alignment: number;
    entry: number;
    sl: number;
    tp: number;
    exit: number;
    reason: string;
    r_multiple: number | null;
    cumulative_r: number;
};

type Result = {
    symbol?: string;
    market?: string;
    interval: string;
    lookahead_safe: boolean;
    candles: number;
    summary: {
        signals: number;
        wins: number;
        losses: number;
        win_rate: number;
        total_r: number;
        average_r: number;
        max_drawdown_r: number;
    };
    rules: {
        signal_uses_candle_close: boolean;
        entry_uses_next_candle_open: boolean;
        confirmation_uses_data_at_signal_time_only: boolean;
        same_candle_sl_tp: string;
    };
    trades: Trade[];
    equity_curve: Array<{
        index: number;
        time: number;
        cumulative_r: number;
        drawdown_r: number;
        r_multiple: number | null;
        outcome: string;
    }>;
    quality_matrix: Array<{
        confidence_bucket: string;
        alignment_bucket: string;
        signals: number;
        wins: number;
        losses: number;
        total_r: number;
        average_r: number;
        win_rate: number;
    }>;
};

type Report = {
    id: number;
    name: string;
    symbol: string;
    market: string;
    interval: string;
    direction: string;
    configuration: Record<string, unknown>;
    result: Result;
    comparison: {
        symbol: string;
        market: string;
        comparison: { a: Result; b: Result };
    } | null;
    created_at: string;
};

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

const date = (value: number) => new Date(value * 1000).toLocaleString();

export default function BacktestReportShow({ reportId }: { reportId: number }) {
    const { t } = useI18n();
    const [report, setReport] = useState<Report | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");

    useEffect(() => {
        fetch(`/market/backtest/reports/${reportId}`, {
            headers: { Accept: "application/json" },
            credentials: "same-origin",
        })
            .then(async (response) => {
                const payload = await response.json().catch(() => ({}));
                if (!response.ok) {
                    throw new Error(
                        payload?.message ?? "Report tidak ditemukan.",
                    );
                }
                setReport(payload.report as Report);
            })
            .catch((reason) =>
                setError(
                    reason instanceof Error
                        ? reason.message
                        : "Gagal memuat report.",
                ),
            )
            .finally(() => setLoading(false));
    }, [reportId]);

    const remove = async () => {
        if (!report || !window.confirm(t("Delete this report?", "Delete this report?"))) {
            return;
        }

        setError("");
        try {
            const response = await fetch(`/market/backtest/reports/${report.id}`, {
                method: "DELETE",
                headers: {
                    Accept: "application/json",
                    "X-CSRF-TOKEN":
                        document
                            .querySelector('meta[name="csrf-token"]')
                            ?.getAttribute("content") ?? "",
                },
                credentials: "same-origin",
            });

            const payload = await response.json().catch(() => ({}));
            if (!response.ok) {
                if (response.status === 401 || response.status === 419) {
                    throw new Error(
                        t(
                            "backtest.session_expired",
                            "Your session expired. Please log in again and retry.",
                        ),
                    );
                }

                if (response.status === 403) {
                    throw new Error(
                        t(
                            "backtest.delete_forbidden",
                            "You are not allowed to delete this report.",
                        ),
                    );
                }

                throw new Error(
                    payload?.message ??
                        t(
                            "backtest.delete_failed",
                            "Failed to delete the report.",
                        ),
                );
            }

            window.location.assign(`/trading/${report.symbol}`);
        } catch (reason) {
            setError(
                reason instanceof Error
                    ? reason.message
                    : t(
                          "backtest.delete_failed",
                          "Failed to delete the report.",
                      ),
            );
        }
    };

    if (loading) {
        return (
            <div className="p-6 text-sm text-muted-foreground">
                {t("Memuat report…")}</div>
        );
    }
    if (error || !report) {
        return (
            <div className="p-6 text-sm text-destructive-500">
                {error || "Report tidak ditemukan."}
            </div>
        );
    }

    const result = report.result;
    const latest = result.equity_curve.at(-1);

    return (
        <>
            <Head title={`${t("Backtest Report")} · ${report.name}`} />
            <div className="product-page min-h-full print:p-0">
                <div className="product-page-content mx-auto w-full max-w-[1400px] space-y-5">
                    <div className="flex flex-wrap items-start justify-between gap-3 print:hidden">
                        <div>
                            <button
                                type="button"
                                onClick={() => window.history.back()}
                                className="mb-2 text-xs text-muted-foreground hover:text-foreground"
                            >
                                <ArrowLeft className="mr-1 inline size-3" />
                                {t("Kembali")}</button>
                            <h1 className="text-2xl font-bold">
                                {report.name}
                            </h1>
                            <p className="mt-1 text-sm text-muted-foreground">
                                {report.symbol} · {report.market} ·{" "}
                                {report.interval} · {report.direction}
                            </p>
                        </div>
                        <div className="flex flex-wrap gap-2">
                            <Button
                                variant="outline"
                                onClick={() => window.print()}
                            >
                                <Printer className="mr-2 size-4" />
                                {t("Print / Save PDF")}</Button>
                            <a
                                href={`/market/backtest/reports/${report.id}/csv`}
                            >
                                <Button variant="outline">
                                    <Download className="mr-2 size-4" />
                                    {t("Export CSV")}</Button>
                            </a>
                            <Button
                                variant="destructive"
                                onClick={() => void remove()}
                            >
                                <Trash2 className="mr-2 size-4" />
                                {t("Delete")}</Button>
                        </div>
                    </div>

                    <section className="rounded-xl border border-border bg-card p-4">
                        <div className="grid grid-cols-2 gap-2 sm:grid-cols-4 lg:grid-cols-8">
                            <Metric
                                label="Signals"
                                value={String(result.summary.signals)}
                            />
                            <Metric
                                label="Wins"
                                value={String(result.summary.wins)}
                            />
                            <Metric
                                label="Losses"
                                value={String(result.summary.losses)}
                            />
                            <Metric
                                label="Win Rate"
                                value={`${n(result.summary.win_rate, 1)}%`}
                            />
                            <Metric
                                label="Total R"
                                value={`${n(result.summary.total_r)}R`}
                            />
                            <Metric
                                label="Average R"
                                value={`${n(result.summary.average_r)}R`}
                            />
                            <Metric
                                label="Max DD"
                                value={`${n(result.summary.max_drawdown_r)}R`}
                            />
                            <Metric
                                label="Final R"
                                value={`${n(latest?.cumulative_r ?? 0)}R`}
                            />
                        </div>
                    </section>

                    <section className="grid gap-4 lg:grid-cols-2">
                        <Panel title="Configuration">
                            <dl className="grid grid-cols-2 gap-3 text-xs">
                                <Item label="Symbol" value={report.symbol} />
                                <Item label="Market" value={report.market} />
                                <Item
                                    label="Timeframe"
                                    value={report.interval}
                                />
                                <Item
                                    label="Direction"
                                    value={report.direction}
                                />
                                <Item
                                    label="Candles"
                                    value={String(result.candles)}
                                />
                                <Item
                                    label="Ambiguity"
                                    value={String(
                                        report.configuration.ambiguity ?? "—",
                                    )}
                                />
                                <Item
                                    label="Fee"
                                    value={`${report.configuration.fee_pct ?? "—"}%`}
                                />
                                <Item
                                    label="Slippage"
                                    value={`${report.configuration.slippage_pct ?? "—"}%`}
                                />
                            </dl>
                        </Panel>
                        <Panel title={t("Replay Integrity")}>
                            <div className="space-y-2 text-xs">
                                <Item
                                    label="Look-ahead safe"
                                    value={result.lookahead_safe ? "Yes" : "No"}
                                />
                                <Item label="Signal" value="Closed candle" />
                                <Item label="Entry" value="Next candle open" />
                                <Item
                                    label="Confirmation"
                                    value="Data at signal time only"
                                />
                                <Item
                                    label="Same-candle SL/TP"
                                    value={result.rules.same_candle_sl_tp}
                                />
                                <Item
                                    label="Created"
                                    value={new Date(
                                        report.created_at,
                                    ).toLocaleString()}
                                />
                            </div>
                        </Panel>
                    </section>

                    <Panel title={t("Equity Curve / Drawdown")}>
                        <div className="grid gap-4 lg:grid-cols-2">
                            <div className="rounded-lg border border-border p-3">
                                <div className="mb-3 text-xs font-semibold">
                                    {t("Cumulative R")}</div>
                                <div className="flex h-40 items-end gap-1 overflow-hidden">
                                    {result.equity_curve
                                        .slice(-60)
                                        .map((point) => {
                                            const max = Math.max(
                                                1,
                                                ...result.equity_curve
                                                    .slice(-60)
                                                    .map((p) =>
                                                        Math.abs(
                                                            p.cumulative_r,
                                                        ),
                                                    ),
                                            );
                                            const height = Math.max(
                                                3,
                                                (Math.abs(point.cumulative_r) /
                                                    max) *
                                                    100,
                                            );
                                            return (
                                                <div
                                                    key={point.index}
                                                    title={`${date(point.time)} · ${n(point.cumulative_r)}R`}
                                                    className="flex-1 rounded-t bg-primary-500/70"
                                                    style={{
                                                        height: `${height}%`,
                                                    }}
                                                />
                                            );
                                        })}
                                </div>
                            </div>
                            <div className="rounded-lg border border-border p-3">
                                <div className="mb-3 text-xs font-semibold">
                                    {t("Drawdown")}</div>
                                <div className="flex h-40 items-end gap-1 overflow-hidden">
                                    {result.equity_curve
                                        .slice(-60)
                                        .map((point) => {
                                            const max = Math.max(
                                                1,
                                                ...result.equity_curve
                                                    .slice(-60)
                                                    .map((p) => p.drawdown_r),
                                            );
                                            const height = Math.max(
                                                2,
                                                (point.drawdown_r / max) * 100,
                                            );
                                            return (
                                                <div
                                                    key={point.index}
                                                    title={`${date(point.time)} · DD ${n(point.drawdown_r)}R`}
                                                    className="flex-1 rounded-t bg-destructive-500/50"
                                                    style={{
                                                        height: `${height}%`,
                                                    }}
                                                />
                                            );
                                        })}
                                </div>
                            </div>
                        </div>
                    </Panel>

                    <Panel title={t("Signal Quality Matrix")}>
                        <div className="overflow-x-auto">
                            <table className="w-full min-w-[760px] text-xs">
                                <thead>
                                    <tr className="border-b border-border text-left text-muted-foreground">
                                        <th className="p-2">{t("Confidence")}</th>
                                        <th className="p-2">{t("Alignment")}</th>
                                        <th className="p-2">{t("Signals")}</th>
                                        <th className="p-2">{t("W / L")}</th>
                                        <th className="p-2">{t("Win Rate")}</th>
                                        <th className="p-2">{t("Avg R")}</th>
                                        <th className="p-2">{t("Total R")}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {result.quality_matrix.map(
                                        (cell, index) => (
                                            <tr
                                                key={`${cell.confidence_bucket}-${cell.alignment_bucket}-${index}`}
                                                className="border-b border-border/60"
                                            >
                                                <td className="p-2">
                                                    {cell.confidence_bucket}
                                                </td>
                                                <td className="p-2">
                                                    {cell.alignment_bucket}
                                                </td>
                                                <td className="p-2">
                                                    {cell.signals}
                                                </td>
                                                <td className="p-2">
                                                    {cell.wins} / {cell.losses}
                                                </td>
                                                <td className="p-2">
                                                    {n(cell.win_rate, 1)}%
                                                </td>
                                                <td className="p-2">
                                                    {n(cell.average_r)}{t("R")}</td>
                                                <td className="p-2">
                                                    {n(cell.total_r)}{t("R")}</td>
                                            </tr>
                                        ),
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </Panel>

                    <Panel title={`${t("Trades")} (${result.trades.length})`}>
                        <div className="overflow-x-auto">
                            <table className="w-full min-w-[1100px] text-xs">
                                <thead>
                                    <tr className="border-b border-border text-left text-muted-foreground">
                                        <th className="p-2">{t("Signal")}</th>
                                        <th className="p-2">{t("Entry")}</th>
                                        <th className="p-2">{t("Exit")}</th>
                                        <th className="p-2">{t("Dir")}</th>
                                        <th className="p-2">{t("Confidence")}</th>
                                        <th className="p-2">{t("Entry")}</th>
                                        <th className="p-2">{t("SL")}</th>
                                        <th className="p-2">{t("TP")}</th>
                                        <th className="p-2">{t("Exit")}</th>
                                        <th className="p-2">{t("Result")}</th>
                                        <th className="p-2">{t("R")}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {result.trades.map((trade, index) => (
                                        <tr
                                            key={`${trade.signal_time}-${index}`}
                                            className="border-b border-border/60"
                                        >
                                            <td className="p-2">
                                                {date(trade.signal_time)}
                                            </td>
                                            <td className="p-2">
                                                {date(trade.entry_time)}
                                            </td>
                                            <td className="p-2">
                                                {date(trade.exit_time)}
                                            </td>
                                            <td className="p-2 font-semibold">
                                                {trade.direction.toUpperCase()}
                                            </td>
                                            <td className="p-2">
                                                {trade.confidence}%
                                            </td>
                                            <td className="p-2">
                                                {trade.entry}
                                            </td>
                                            <td className="p-2">{trade.sl}</td>
                                            <td className="p-2">{trade.tp}</td>
                                            <td className="p-2">
                                                {trade.exit}
                                            </td>
                                            <td className="p-2">
                                                {trade.reason.replaceAll(
                                                    "_",
                                                    " ",
                                                )}
                                            </td>
                                            <td className="p-2 font-semibold">
                                                {trade.r_multiple == null
                                                    ? "—"
                                                    : `${n(trade.r_multiple)}R`}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </Panel>

                    {report.comparison && (
                        <Panel title={t("Timeframe Comparison")}>
                            <div className="grid gap-3 sm:grid-cols-2">
                                {[
                                    report.comparison.comparison.a,
                                    report.comparison.comparison.b,
                                ].map((item) => (
                                    <div
                                        key={item.interval}
                                        className="rounded-lg border border-border p-3"
                                    >
                                        <div className="text-sm font-semibold">
                                            {item.interval}
                                        </div>
                                        <div className="mt-2 grid grid-cols-2 gap-2">
                                            <Metric
                                                label="Signals"
                                                value={String(
                                                    item.summary.signals,
                                                )}
                                            />
                                            <Metric
                                                label="Win Rate"
                                                value={`${n(item.summary.win_rate, 1)}%`}
                                            />
                                            <Metric
                                                label="Total R"
                                                value={`${n(item.summary.total_r)}R`}
                                            />
                                            <Metric
                                                label="Max DD"
                                                value={`${n(item.summary.max_drawdown_r)}R`}
                                            />
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </Panel>
                    )}
                </div>
            </div>
            <style>{`@media print { body { background: white !important; } }`}</style>
        </>
    );
}

function Panel({ title, children }: { title: string; children: ReactNode }) {
    return (
        <section className="rounded-xl border border-border bg-card p-4">
            <h2 className="mb-3 text-sm font-semibold">{title}</h2>
            {children}
        </section>
    );
}

function Metric({ label, value }: { label: string; value: string }) {
    return (
        <div className="rounded-lg border border-border bg-background/50 p-3">
            <div className="text-[10px] font-semibold uppercase tracking-[.12em] text-muted-foreground">
                {label}
            </div>
            <div className="mt-1 text-sm font-bold">{value}</div>
        </div>
    );
}

function Item({ label, value }: { label: string; value: string }) {
    return (
        <div>
            <dt className="text-[10px] uppercase tracking-[.12em] text-muted-foreground">
                {label}
            </dt>
            <dd className="mt-1 font-medium text-foreground">{value}</dd>
        </div>
    );
}
