import { Head } from "@inertiajs/react";
import { useEffect, useMemo, useState } from "react";
import { ExternalLink, RefreshCw, Search } 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 CustomerWorkspaceNav from "@/components/customer-workspace-nav";
import AnalysisPageHeader from "@/components/analysis-page-header";
type JournalRow = {
    id: number;
    symbol: string;
    market: string;
    provider: string;
    interval: string;
    direction: string;
    signal_mode: "strict" | "balanced" | "flexible" | string | null;
    candidate_direction: string | null;
    confidence: number | null;
    status: "active" | "target_hit" | "invalidated" | string;
    outcome: "open" | "target_hit" | "invalidated";
    entry: number | null;
    stop_loss: number | null;
    take_profit: number | null;
    r_multiple: number | null;
    duration_seconds: number | null;
    detected_at: string | null;
    detected_time: number | null;
    outcome_at: number | null;
    event_candle_time: number | null;
    event_price: number | null;
};

type Summary = {
    total: number;
    active: number;
    completed: number;
    wins: number;
    losses: number;
    win_rate: number | null;
    total_r: number | null;
    average_r: number | null;
    average_duration_seconds: number | null;
};

type ProviderOption = { slug: string; name: string; markets: string[] };

type ResponseData = {
    providers?: ProviderOption[];
    data: JournalRow[];
    summary: Summary;
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    from: number | null;
    to: number | null;
};

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

const percent = (value: number | null) =>
    value === null ? "—" : `${value.toFixed(1)}%`;

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 rest = minutes % 60;
    return `${hours}h ${rest}m`;
};

const dateTime = (value: string | null) =>
    value ? new Date(value).toLocaleString() : "—";

const detailUrl = (row: JournalRow) => `/signals/journal/${row.id}`;

const chartUrl = (row: JournalRow) => {
    const params = new URLSearchParams({
        provider: row.provider,
        market: row.market,
        interval: row.interval,
    });
    const time = row.event_candle_time ?? row.detected_time;
    if (time) params.set("focus_time", String(time));
    if (row.event_price !== null)
        params.set("focus_price", String(row.event_price));
    if (row.outcome !== "open") params.set("focus_event", row.outcome);
    else params.set("focus_event", "detected");
    return `/trading/${encodeURIComponent(row.symbol)}?${params.toString()}`;
};

export default function SignalJournal() {
    const { t } = useI18n();
    const [data, setData] = useState<ResponseData | null>(null);
    const [search, setSearch] = useState("");
    const [market, setMarket] = useState("all");
    const [provider, setProvider] = useState("all");
    const [interval, setInterval] = useState("all");
    const [direction, setDirection] = useState("all");
    const [signalMode, setSignalMode] = useState("all");
    const [status, setStatus] = useState("all");
    const [page, setPage] = useState(1);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");

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

    const load = async () => {
        setLoading(true);
        setError("");
        try {
            const response = await fetch(`/signals/journal/data?${query}`, {
                headers: { Accept: "application/json" },
                credentials: "same-origin",
                cache: "no-store",
            });
            const payload = await response.json();
            if (!response.ok)
                throw new Error(
                    payload?.message ?? "Gagal memuat Signal Journal.",
                );
            setData(payload);
        } catch (err) {
            setError(
                err instanceof Error
                    ? err.message
                    : "Gagal memuat Signal Journal.",
            );
        } finally {
            setLoading(false);
        }
    };

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

    const summary = data?.summary;

    return (
        <>
            <Head title={t("Signal Journal")} />
            <div className="product-page-content mx-auto w-full max-w-[1600px] space-y-6">
                <AnalysisPageHeader
                    eyebrow={t("Signal workspace")}
                    title={t("Signal Journal")}
                    description={t(
                        "Review signal lifecycle, confirmation status, and realized outcomes from the Signal Engine.",
                    )}
                    actions={
                        <Button
                            variant="outline"
                            onClick={() => void load()}
                            disabled={loading}
                        >
                            <RefreshCw
                                className={
                                    loading
                                        ? "mr-2 size-4 animate-spin"
                                        : "mr-2 size-4"
                                }
                            />
                            {t("Refresh")}
                        </Button>
                    }
                />

                <CustomerWorkspaceNav group="signals" />

                {summary && (
                    <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                        <Card>
                            <CardHeader className="pb-2">
                                <CardTitle className="text-sm">
                                    {t("Total Signals")}
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="text-2xl font-semibold">
                                {summary.total}
                            </CardContent>
                        </Card>
                        <Card>
                            <CardHeader className="pb-2">
                                <CardTitle className="text-sm">
                                    {t("Win Rate")}
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="text-2xl font-semibold">
                                {percent(summary.win_rate)}
                            </CardContent>
                        </Card>
                        <Card>
                            <CardHeader className="pb-2">
                                <CardTitle className="text-sm">
                                    {t("Average R")}
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="text-2xl font-semibold">
                                {summary.average_r === null
                                    ? "—"
                                    : `${summary.average_r >= 0 ? "+" : ""}${summary.average_r.toFixed(2)}R`}
                            </CardContent>
                        </Card>
                        <Card>
                            <CardHeader className="pb-2">
                                <CardTitle className="text-sm">
                                    {t("Average Duration")}
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="text-2xl font-semibold">
                                {duration(summary.average_duration_seconds)}
                            </CardContent>
                        </Card>
                    </div>
                )}

                <Card>
                    <CardContent className="flex flex-wrap items-center gap-3 pt-6">
                        <div className="relative w-full min-w-0 flex-1 sm:min-w-55">
                            <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                            <Input
                                className="pl-9"
                                value={search}
                                onChange={(e) => {
                                    setSearch(e.target.value);
                                    setPage(1);
                                }}
                                placeholder={t("Search symbol / signal key...")}
                            />
                        </div>
                        <Select
                            value={market}
                            onValueChange={(v) => {
                                setMarket(v);
                                setPage(1);
                            }}
                        >
                            <SelectTrigger className="w-full sm:w-35">
                                <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={provider}
                            onValueChange={(v) => {
                                setProvider(v);
                                setPage(1);
                            }}
                        >
                            <SelectTrigger className="w-full sm:w-37.5">
                                <SelectValue placeholder="Provider" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">
                                    {t("All providers")}
                                </SelectItem>
                                {(data?.providers ?? []).map((item) => (
                                    <SelectItem
                                        key={item.slug}
                                        value={item.slug}
                                    >
                                        {item.name}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <Select
                            value={interval}
                            onValueChange={(v) => {
                                setInterval(v);
                                setPage(1);
                            }}
                        >
                            <SelectTrigger className="w-full sm:w-32.5">
                                <SelectValue placeholder="Timeframe" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">
                                    {t("All timeframes")}
                                </SelectItem>
                                {["15m", "30m", "1h", "4h", "1d", "1w"].map(
                                    (item) => (
                                        <SelectItem key={item} value={item}>
                                            {item}
                                        </SelectItem>
                                    ),
                                )}
                            </SelectContent>
                        </Select>
                        <Select
                            value={direction}
                            onValueChange={(v) => {
                                setDirection(v);
                                setPage(1);
                            }}
                        >
                            <SelectTrigger className="w-full sm:w-32.5">
                                <SelectValue placeholder="Direction" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">{t("Both")}</SelectItem>
                                <SelectItem value="long">
                                    {t("Long")}
                                </SelectItem>
                                <SelectItem value="short">
                                    {t("Short")}
                                </SelectItem>
                            </SelectContent>
                        </Select>
                        <Select
                            value={signalMode}
                            onValueChange={(v) => {
                                setSignalMode(v);
                                setPage(1);
                            }}
                        >
                            <SelectTrigger className="w-full sm:w-35">
                                <SelectValue placeholder={t("Signal mode")} />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">
                                    {t("All modes")}
                                </SelectItem>
                                <SelectItem value="strict">
                                    {t("Strict")}
                                </SelectItem>
                                <SelectItem value="balanced">
                                    {t("Balanced")}
                                </SelectItem>
                                <SelectItem value="flexible">
                                    {t("Flexible")}
                                </SelectItem>
                            </SelectContent>
                        </Select>
                        <Select
                            value={status}
                            onValueChange={(v) => {
                                setStatus(v);
                                setPage(1);
                            }}
                        >
                            <SelectTrigger className="w-full sm:w-37.5">
                                <SelectValue placeholder="Result" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">
                                    {t("All results")}
                                </SelectItem>
                                <SelectItem value="open">
                                    {t("Active")}
                                </SelectItem>
                                <SelectItem value="target_hit">
                                    {t("Target hit")}
                                </SelectItem>
                                <SelectItem value="invalidated">
                                    {t("Invalidated")}
                                </SelectItem>
                            </SelectContent>
                        </Select>
                    </CardContent>
                </Card>

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

                <Card>
                    <CardContent className="p-0">
                        <div className="overflow-x-auto">
                            <table className="w-full text-sm">
                                <thead className="border-b bg-muted/30">
                                    <tr className="text-left">
                                        <th className="px-4 py-3">
                                            {t("Signal")}
                                        </th>
                                        <th className="px-4 py-3">
                                            {t("Market")}
                                        </th>
                                        <th className="px-4 py-3">
                                            {t("Mode")}
                                        </th>
                                        <th className="px-4 py-3">
                                            {t("Direction")}
                                        </th>
                                        <th className="px-4 py-3">
                                            {t("Confidence")}
                                        </th>
                                        <th className="px-4 py-3">
                                            {t("Result")}
                                        </th>
                                        <th className="px-4 py-3">{t("R")}</th>
                                        <th className="px-4 py-3">
                                            {t("Duration")}
                                        </th>
                                        <th className="px-4 py-3">
                                            {t("Detected")}
                                        </th>
                                        <th className="px-4 py-3"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {loading && (
                                        <tr>
                                            <td
                                                colSpan={10}
                                                className="px-4 py-10 text-center text-muted-foreground"
                                            >
                                                {t("Loading Signal Journal…")}
                                            </td>
                                        </tr>
                                    )}
                                    {!loading && data?.data.length === 0 && (
                                        <tr>
                                            <td
                                                colSpan={10}
                                                className="px-4 py-10 text-center text-muted-foreground"
                                            >
                                                {t(
                                                    "Belum ada signal yang sesuai filter.",
                                                )}
                                            </td>
                                        </tr>
                                    )}
                                    {!loading &&
                                        data?.data.map((row) => (
                                            <tr
                                                key={row.id}
                                                className="border-b last:border-0"
                                            >
                                                <td className="px-4 py-3">
                                                    <div className="font-medium">
                                                        {row.symbol}
                                                    </div>
                                                    <div className="text-xs text-muted-foreground">
                                                        {row.provider.toUpperCase()}{" "}
                                                        · {row.interval}
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3 capitalize">
                                                    {row.market}
                                                </td>
                                                <td className="px-4 py-3 capitalize">
                                                    {row.signal_mode ?? "—"}
                                                </td>
                                                <td className="px-4 py-3 font-medium uppercase">
                                                    {row.direction}
                                                </td>
                                                <td className="px-4 py-3">
                                                    {percent(row.confidence)}
                                                </td>
                                                <td className="px-4 py-3">
                                                    <span className="rounded-full border px-2 py-1 text-xs capitalize">
                                                        {row.outcome ===
                                                        "target_hit"
                                                            ? "Target hit"
                                                            : row.outcome ===
                                                                "invalidated"
                                                              ? "Invalidated"
                                                              : "Active"}
                                                    </span>
                                                </td>
                                                <td className="px-4 py-3 font-medium">
                                                    {row.r_multiple === null
                                                        ? "—"
                                                        : `${row.r_multiple >= 0 ? "+" : ""}${row.r_multiple.toFixed(2)}R`}
                                                </td>
                                                <td className="px-4 py-3">
                                                    {duration(
                                                        row.duration_seconds,
                                                    )}
                                                </td>
                                                <td className="px-4 py-3 whitespace-nowrap">
                                                    {dateTime(row.detected_at)}
                                                </td>
                                                <td className="px-4 py-3 text-right">
                                                    <div className="flex items-center justify-end gap-3">
                                                        <a
                                                            href={detailUrl(
                                                                row,
                                                            )}
                                                            className="text-xs font-medium hover:underline"
                                                        >
                                                            {t("Details")}
                                                        </a>
                                                        <a
                                                            href={chartUrl(row)}
                                                            className="inline-flex items-center gap-1 text-xs font-medium hover:underline"
                                                        >
                                                            {t("Open Chart")}{" "}
                                                            <ExternalLink className="size-3" />
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                        ))}
                                </tbody>
                            </table>
                        </div>
                    </CardContent>
                </Card>

                {data && (
                    <div className="flex flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground">
                        <span>
                            {data.from ?? 0}–{data.to ?? 0} {t("of")}
                            {data.total}
                        </span>
                        <div className="flex gap-2">
                            <Button
                                variant="outline"
                                size="sm"
                                disabled={data.current_page <= 1 || loading}
                                onClick={() => setPage((p) => p - 1)}
                            >
                                {t("Previous")}
                            </Button>
                            <span className="flex items-center px-2">
                                {t("Page")}
                                {data.current_page} / {data.last_page}
                            </span>
                            <Button
                                variant="outline"
                                size="sm"
                                disabled={
                                    data.current_page >= data.last_page ||
                                    loading
                                }
                                onClick={() => setPage((p) => p + 1)}
                            >
                                {t("Next")}
                            </Button>
                        </div>
                    </div>
                )}
            </div>
        </>
    );
}
