import { Head } from "@inertiajs/react";
import { useEffect, useMemo, useState } from "react";
import {
    ExternalLink,
    GitCompareArrows,
    RefreshCw,
    Search,
    Trash2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";

import { useI18n } from "@/lib/i18n";
import AnalysisPageHeader from "@/components/analysis-page-header";
type Report = {
    id: number;
    name: string;
    symbol: string;
    market: string;
    interval: string;
    direction: string;
    configuration?: Record<string, unknown> | null;
    result?: {
        summary?: {
            signals?: number;
            wins?: number;
            losses?: number;
            win_rate?: number;
            total_r?: number;
            average_r?: number;
            max_drawdown_r?: number;
        };
    } | null;
    created_at: string;
};

type Paginator = {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    from: number | null;
    to: number | null;
};

type ReportsResponse = Paginator & { data: Report[] };

const csrf = () =>
    document
        .querySelector('meta[name="csrf-token"]')
        ?.getAttribute("content") ?? "";

const number = (value: unknown, digits = 2) =>
    typeof value === "number" ? value.toFixed(digits) : "—";

export default function BacktestReports() {
    const { t } = useI18n();
    const [reports, setReports] = useState<ReportsResponse | null>(null);
    const [search, setSearch] = useState("");
    const [market, setMarket] = useState("all");
    const [interval, setInterval] = useState("all");
    const [direction, setDirection] = useState("all");
    const [page, setPage] = useState(1);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");
    const [selected, setSelected] = useState<number[]>([]);
    const [comparison, setComparison] = useState<Report[] | null>(null);
    const [compareLoading, setCompareLoading] = useState(false);

    const query = useMemo(() => {
        const params = new URLSearchParams();
        if (search.trim()) params.set("search", search.trim());
        if (market !== "all") params.set("market", market);
        if (interval !== "all") params.set("interval", interval);
        if (direction !== "all") params.set("direction", direction);
        params.set("page", String(page));
        params.set("per_page", "20");
        return params.toString();
    }, [search, market, interval, direction, page]);

    const load = async () => {
        setLoading(true);
        setError("");
        try {
            const response = await fetch(`/market/backtest/reports?${query}`, {
                headers: { Accept: "application/json" },
                credentials: "same-origin",
            });
            const payload = await response.json();
            if (!response.ok)
                throw new Error(payload?.message ?? "Gagal memuat report.");
            setReports(payload);
        } catch (e) {
            setError(e instanceof Error ? e.message : "Gagal memuat report.");
        } finally {
            setLoading(false);
        }
    };

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

    const toggleSelected = (id: number) => {
        setSelected((current) =>
            current.includes(id)
                ? current.filter((item) => item !== id)
                : current.length < 2
                  ? [...current, id]
                  : current,
        );
    };

    const deleteReport = async (report: Report) => {
        if (!window.confirm(t("Delete report", "Delete report") + ` "${report.name}"?`)) return;

        setError("");
        try {
            const response = await fetch(`/market/backtest/reports/${report.id}`, {
                method: "DELETE",
                headers: { Accept: "application/json", "X-CSRF-TOKEN": csrf() },
                credentials: "same-origin",
            });

            const payload = await response.json().catch(() => ({}));
            if (!response.ok) {
                throw new Error(payload?.message ?? "Gagal menghapus report.");
            }

            setSelected((current) => current.filter((id) => id !== report.id));
            await load();
        } catch (error) {
            setError(error instanceof Error ? error.message : "Gagal menghapus report.");
        }
    };

    const compareSelected = async () => {
        if (selected.length !== 2 || compareLoading) return;
        setCompareLoading(true);
        setError("");
        try {
            const response = await fetch("/market/backtest/reports/compare", {
                method: "POST",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": csrf(),
                },
                credentials: "same-origin",
                body: JSON.stringify({ ids: selected }),
            });
            const payload = await response.json();
            if (!response.ok)
                throw new Error(
                    payload?.message ?? "Gagal membandingkan report.",
                );
            setComparison(payload.reports ?? []);
        } catch (e) {
            setComparison(null);
            setError(
                e instanceof Error ? e.message : "Gagal membandingkan report.",
            );
        } finally {
            setCompareLoading(false);
        }
    };

    const resetFilters = () => {
        setSearch("");
        setMarket("all");
        setInterval("all");
        setDirection("all");
        setPage(1);
    };

    return (
        <>
            <Head title={t("Backtest Reports")} />
            <div className="product-page-content mx-auto w-full max-w-7xl space-y-5">
                <AnalysisPageHeader
                    eyebrow={t("Backtest workspace")}
                    title={t("Saved Reports")}
                    description={t(
                        "Save, search, reopen, compare, and manage historical replay results.",
                    )}
                />

                <Card className="border-border/70 bg-background/95 shadow-sm backdrop-blur-xl md:sticky md:top-2 md:z-20">
                    <CardContent className="p-3 sm:p-4">
                        <div className="grid gap-3 md:grid-cols-[2fr_1fr_1fr_1fr_auto]">
                            <div className="relative">
                                <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                                <Input
                                    value={search}
                                    onChange={(event) => {
                                        setSearch(event.target.value);
                                        setPage(1);
                                    }}
                                    placeholder={t("Search report name or symbol...")}
                                    className="pl-9"
                                />
                            </div>
                            <Select
                                value={market}
                                onValueChange={(value) => {
                                    setMarket(value);
                                    setPage(1);
                                }}
                            >
                                <SelectTrigger>
                                    <SelectValue placeholder="Market" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">
                                        {t("All markets")}</SelectItem>
                                    <SelectItem value="spot">{t("Spot")}</SelectItem>
                                    <SelectItem value="futures">
                                        {t("Futures")}</SelectItem>
                                </SelectContent>
                            </Select>
                            <Select
                                value={interval}
                                onValueChange={(value) => {
                                    setInterval(value);
                                    setPage(1);
                                }}
                            >
                                <SelectTrigger>
                                    <SelectValue placeholder="Timeframe" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">
                                        {t("All timeframes")}</SelectItem>
                                    <SelectItem value="5m">{t("5m")}</SelectItem>
                                    <SelectItem value="15m">{t("15m")}</SelectItem>
                                    <SelectItem value="1h">{t("1h")}</SelectItem>
                                    <SelectItem value="4h">{t("4h")}</SelectItem>
                                </SelectContent>
                            </Select>
                            <Select
                                value={direction}
                                onValueChange={(value) => {
                                    setDirection(value);
                                    setPage(1);
                                }}
                            >
                                <SelectTrigger>
                                    <SelectValue placeholder="Direction" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">
                                        {t("All directions")}</SelectItem>
                                    <SelectItem value="both">
                                        {t("Long + Short")}</SelectItem>
                                    <SelectItem value="long">{t("Long")}</SelectItem>
                                    <SelectItem value="short">{t("Short")}</SelectItem>
                                </SelectContent>
                            </Select>
                            <Button
                                type="button"
                                variant="outline"
                                onClick={resetFilters}
                                title={t("Reset filters")}
                            >
                                <RefreshCw className="size-4" />
                            </Button>
                        </div>
                        <div className="mt-3 flex flex-wrap items-center justify-between gap-2 border-t border-border/60 pt-3 text-xs text-muted-foreground">
                            <span>
                                {selected.length === 0
                                    ? t("Select up to 2 reports to compare.")
                                    : t(`${selected.length} report selected`)}
                            </span>
                            {selected.length > 0 && (
                                <Button
                                    variant="ghost"
                                    size="sm"
                                    className="h-8 px-2 text-xs"
                                    onClick={() => setSelected([])}
                                >
                                    {t("Clear selection")}
                                </Button>
                            )}
                        </div>
                    </CardContent>
                </Card>

                {error && (
                    <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
                        {error}
                    </div>
                )}

                <Card>
                    <CardHeader className="flex flex-row items-center justify-between gap-3">
                        <div className="space-y-0.5">
                            <CardTitle className="text-base">{t("Reports")}</CardTitle>
                            <p className="text-xs text-muted-foreground">
                                {t("Select up to 2 reports to compare.")}
                            </p>
                        </div>
                        <Button
                            type="button"
                            variant="outline"
                            disabled={selected.length !== 2 || compareLoading}
                            onClick={() => void compareSelected()}
                        >
                            <GitCompareArrows className="mr-2 size-4" />
                            {compareLoading
                                ? "Comparing…"
                                : `${t("Compare")} (${selected.length}/2)`}
                        </Button>
                    </CardHeader>
                    <CardContent>
                        <div className="overflow-x-auto">
                            <table className="w-full min-w-[900px] text-sm">
                                <thead>
                                    <tr className="border-b text-left text-xs text-muted-foreground">
                                        <th className="p-2">{t("Compare")}</th>
                                        <th className="p-2">{t("Report")}</th>
                                        <th className="p-2">{t("Market")}</th>
                                        <th className="p-2">{t("TF")}</th>
                                        <th className="p-2">{t("Direction")}</th>
                                        <th className="p-2">{t("Signals")}</th>
                                        <th className="p-2">{t("Total R")}</th>
                                        <th className="p-2">{t("Max DD")}</th>
                                        <th className="p-2">{t("Created")}</th>
                                        <th className="p-2" />
                                    </tr>
                                </thead>
                                <tbody>
                                    {loading ? (
                                        <tr>
                                            <td
                                                colSpan={10}
                                                className="p-8 text-center text-muted-foreground"
                                            >
                                                {t("Loading reports…")}</td>
                                        </tr>
                                    ) : !reports?.data.length ? (
                                        <tr>
                                            <td
                                                colSpan={10}
                                                className="p-8 text-center text-muted-foreground"
                                            >
                                                {t("Belum ada backtest report tersimpan.")}</td>
                                        </tr>
                                    ) : (
                                        reports.data.map((report) => {
                                            const summary =
                                                report.result?.summary;
                                            return (
                                                <tr
                                                    key={report.id}
                                                    className="border-b border-border/60"
                                                >
                                                    <td className="p-2">
                                                        <input
                                                            type="checkbox"
                                                            checked={selected.includes(
                                                                report.id,
                                                            )}
                                                            disabled={
                                                                selected.length >= 2 &&
                                                                !selected.includes(report.id)
                                                            }
                                                            onChange={() =>
                                                                toggleSelected(
                                                                    report.id,
                                                                )
                                                            }
                                                            aria-label={`${t("Select")} ${report.name} ${t("for comparison")}`}
                                                        />
                                                    </td>
                                                    <td className="p-2">
                                                        <a
                                                            className="font-medium hover:underline"
                                                            href={`/backtest/reports/${report.id}`}
                                                        >
                                                            {report.name}
                                                        </a>
                                                        <div className="text-xs text-muted-foreground">
                                                            {report.symbol}
                                                        </div>
                                                    </td>
                                                    <td className="p-2 capitalize">
                                                        {report.market}
                                                    </td>
                                                    <td className="p-2">
                                                        {report.interval}
                                                    </td>
                                                    <td className="p-2">
                                                        {report.direction}
                                                    </td>
                                                    <td className="p-2">
                                                        {summary?.signals ??
                                                            "—"}
                                                    </td>
                                                    <td className="p-2 font-semibold">
                                                        {number(
                                                            summary?.total_r,
                                                        )}
                                                        {t("R")}</td>
                                                    <td className="p-2">
                                                        {number(
                                                            summary?.max_drawdown_r,
                                                        )}
                                                        {t("R")}</td>
                                                    <td className="p-2 whitespace-nowrap text-xs text-muted-foreground">
                                                        {new Date(
                                                            report.created_at,
                                                        ).toLocaleString()}
                                                    </td>
                                                    <td className="p-2">
                                                        <div className="flex justify-end gap-1">
                                                            <Button
                                                                asChild
                                                                size="icon"
                                                                variant="ghost"
                                                                aria-label={t("Open report")}
                                                                title={t("Open report")}
                                                            >
                                                                <a
                                                                    href={`/backtest/reports/${report.id}`}
                                                                >
                                                                    <ExternalLink className="size-4" />
                                                                </a>
                                                            </Button>
                                                            <Button
                                                                size="icon"
                                                                variant="ghost"
                                                                className="text-destructive"
                                                                aria-label={t("Delete report")}
                                                                title={t("Delete report")}
                                                                onClick={() =>
                                                                    void deleteReport(
                                                                        report,
                                                                    )
                                                                }
                                                            >
                                                                <Trash2 className="size-4" />
                                                            </Button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            );
                                        })
                                    )}
                                </tbody>
                            </table>
                        </div>

                        {reports && reports.last_page > 1 && (
                            <div className="mt-4 flex items-center justify-between gap-3 text-sm">
                                <span className="text-muted-foreground">
                                    {t("Showing")}{reports.from ?? 0}–
                                    {reports.to ?? 0} {t("of")}{reports.total}
                                </span>
                                <div className="flex gap-2">
                                    <Button
                                        variant="outline"
                                        disabled={reports.current_page <= 1}
                                        onClick={() =>
                                            setPage((value) => value - 1)
                                        }
                                    >
                                        {t("Previous")}</Button>
                                    <span className="flex items-center px-2 text-xs text-muted-foreground">
                                        {reports.current_page} /{" "}
                                        {reports.last_page}
                                    </span>
                                    <Button
                                        variant="outline"
                                        disabled={
                                            reports.current_page >=
                                            reports.last_page
                                        }
                                        onClick={() =>
                                            setPage((value) => value + 1)
                                        }
                                    >
                                        {t("Next")}</Button>
                                </div>
                            </div>
                        )}
                    </CardContent>
                </Card>

                {comparison && comparison.length === 2 && (
                    <Card>
                        <CardHeader>
                            <CardTitle className="text-base">
                                {t("Saved Report Comparison")}</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <div className="grid gap-3 md:grid-cols-2">
                                {comparison.map((report) => {
                                    const summary = report.result?.summary;
                                    return (
                                        <div
                                            key={report.id}
                                            className="rounded-lg border border-border p-4"
                                        >
                                            <div className="font-semibold">
                                                {report.name}
                                            </div>
                                            <div className="mt-1 text-xs text-muted-foreground">
                                                {report.symbol} ·{" "}
                                                {report.market} ·{" "}
                                                {report.interval} ·{" "}
                                                {report.direction}
                                            </div>
                                            <div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
                                                <Metric
                                                    label="Signals"
                                                    value={
                                                        summary?.signals ?? "—"
                                                    }
                                                />
                                                <Metric
                                                    label="Win rate"
                                                    value={
                                                        summary?.win_rate !=
                                                        null
                                                            ? `${number(summary.win_rate, 1)}%`
                                                            : "—"
                                                    }
                                                />
                                                <Metric
                                                    label="Total R"
                                                    value={`${number(summary?.total_r)}R`}
                                                />
                                                <Metric
                                                    label="Max DD"
                                                    value={`${number(summary?.max_drawdown_r)}R`}
                                                />
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        </CardContent>
                    </Card>
                )}
            </div>
        </>
    );
}

function Metric({ label, value }: { label: string; value: string | number }) {
    return (
        <div className="rounded-md border border-border/60 bg-background/40 p-2">
            <div className="text-[10px] uppercase tracking-wide text-muted-foreground">
                {label}
            </div>
            <div className="mt-1 text-sm font-semibold">{value}</div>
        </div>
    );
}
