import { useMemo, useState } from "react";
import { ShieldAlert, Trash2, Plus, RefreshCw } from "lucide-react";
import type { MarketType } from "@/lib/market";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { DataCardState } from "./DataCardState";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";

type Props = { market: MarketType; symbol: string };

type Position = {
    id: number;
    symbol: string;
    direction: "long" | "short";
    risk_r: number;
};

type Result = {
    position_count: number;
    gross_risk_r: number;
    long_risk_r: number;
    short_risk_r: number;
    net_direction_r: number;
    largest_cluster_r: number;
    clusters: {
        id: string;
        symbols: string[];
        direction: string;
        gross_risk_r: number;
        position_count: number;
        correlation_level: string;
    }[];
};

const label = (level: string) =>
    level.replace("_", " ").replace(/\b\w/g, (c) => c.toUpperCase());

export default function PortfolioRiskPanel({ market, symbol }: Props) {
    const [positions, setPositions] = useState<Position[]>([]);
    const [nextId, setNextId] = useState(1);
    const [result, setResult] = useState<Result | null>(null);
    const [error, setError] = useState<string | null>(null);
    const [loading, setLoading] = useState(false);

    const canAnalyze = market === "futures" && positions.length > 0;

    const correlation = useMemo(() => {
        return {};
    }, []);

    const addPosition = () => {
        setPositions((current) => [
            ...current,
            {
                id: nextId,
                symbol: symbol.toUpperCase(),
                direction: "long",
                risk_r: 1,
            },
        ]);
        setNextId((value) => value + 1);
    };

    const update = (id: number, patch: Partial<Position>) => {
        setPositions((current) =>
            current.map((p) => (p.id === id ? { ...p, ...patch } : p)),
        );
    };

    const analyze = async () => {
        if (!canAnalyze || loading) return;
        setLoading(true);
        setError(null);

        try {
            const response = await fetch("/market/portfolio-risk", {
                method: "POST",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    "X-Requested-With": "XMLHttpRequest",
                    "X-CSRF-TOKEN":
                        document
                            .querySelector('meta[name="csrf-token"]')
                            ?.getAttribute("content") ?? "",
                },
                credentials: "same-origin",
                body: JSON.stringify({
                    positions: positions.map(
                        ({ symbol, direction, risk_r }) => ({
                            symbol,
                            direction,
                            risk_r,
                        }),
                    ),
                    correlation,
                }),
            });

            const payload = await response.json().catch(() => ({}));
            if (!response.ok)
                throw new Error(
                    payload.message || `Request failed: ${response.status}`,
                );
            setResult(payload);
        } catch (caught) {
            setError(
                caught instanceof Error
                    ? caught.message
                    : "Gagal menghitung portfolio risk.",
            );
        } finally {
            setLoading(false);
        }
    };

    if (market !== "futures") return null;

    return (
        <Card className="mt-3 border-border bg-card/80 shadow-xs py-4 px-0!">
            <CardHeader className="flex flex-row items-center justify-between border-b border-border/60">
                <div className="flex items-center gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-border bg-muted/40 text-primary">
                        <ShieldAlert className="size-5" />
                    </div>
                    <div>
                        <div className="text-[11px] font-semibold uppercase tracking-[.14em] text-muted-foreground">
                            Portfolio Risk
                        </div>
                        <div className="mt-0.5 text-sm font-semibold text-foreground">
                            Exposure Clustering · Futures
                        </div>
                    </div>
                </div>

                <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={addPosition}
                    className="h-9 gap-1.5 text-xs font-semibold shadow-xs"
                >
                    <Plus className="size-4" /> Add Position
                </Button>
            </CardHeader>

            <CardContent className="p-5 pt-4 space-y-4">
                {positions.length > 0 && (
                    <div className="space-y-3">
                        {positions.map((position) => (
                            <div
                                key={position.id}
                                className="grid gap-2.5 sm:grid-cols-[1.4fr_1fr_1fr_auto] items-center"
                            >
                                <Input
                                    value={position.symbol}
                                    onChange={(e) =>
                                        update(position.id, {
                                            symbol: e.target.value.toUpperCase(),
                                        })
                                    }
                                    className="h-9 text-xs font-semibold shadow-xs"
                                />
                                <Select
                                    value={position.direction}
                                    onValueChange={(val) =>
                                        update(position.id, {
                                            direction:
                                                val as Position["direction"],
                                        })
                                    }
                                >
                                    <SelectTrigger className="h-9 text-xs shadow-xs">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="long">
                                            LONG
                                        </SelectItem>
                                        <SelectItem value="short">
                                            SHORT
                                        </SelectItem>
                                    </SelectContent>
                                </Select>
                                <Input
                                    type="number"
                                    min={0}
                                    step={0.1}
                                    value={position.risk_r}
                                    onChange={(e) =>
                                        update(position.id, {
                                            risk_r: Number(e.target.value),
                                        })
                                    }
                                    className="h-9 text-xs font-semibold shadow-xs"
                                    aria-label="Risk R"
                                />
                                <Button
                                    type="button"
                                    variant="outline"
                                    size="icon"
                                    onClick={() =>
                                        setPositions((current) =>
                                            current.filter(
                                                (p) => p.id !== position.id,
                                            ),
                                        )
                                    }
                                    className="h-9 w-9 text-muted-foreground hover:text-destructive shadow-xs"
                                    aria-label="Remove position"
                                >
                                    <Trash2 className="size-4" />
                                </Button>
                            </div>
                        ))}

                        <Button
                            type="button"
                            disabled={!canAnalyze || loading}
                            onClick={() => void analyze()}
                            className="h-9 text-xs font-semibold shadow-xs"
                        >
                            {loading ? (
                                <>
                                    <RefreshCw className="size-3.5 animate-spin" />{" "}
                                    Analyzing…
                                </>
                            ) : (
                                "Analyze Exposure"
                            )}
                        </Button>
                    </div>
                )}

                <DataCardState
                    loading={loading}
                    error={error}
                    hasData={Boolean(result)}
                    onRetry={() => void analyze()}
                    loadingLabel="Analyzing portfolio risk…"
                />

                {result && (
                    <div className="space-y-3">
                        <div className="grid gap-3 sm:grid-cols-4">
                            <Metric
                                label="Positions"
                                value={result.position_count}
                            />
                            <Metric
                                label="Gross Risk"
                                value={`${result.gross_risk_r.toFixed(2)}R`}
                            />
                            <Metric
                                label="Net Direction"
                                value={`${result.net_direction_r >= 0 ? "+" : ""}${result.net_direction_r.toFixed(2)}R`}
                            />
                            <Metric
                                label="Largest Cluster"
                                value={`${result.largest_cluster_r.toFixed(2)}R`}
                            />
                        </div>

                        <div className="space-y-2">
                            {result.clusters.map((cluster) => (
                                <div
                                    key={cluster.id}
                                    className="rounded-xl border border-border bg-background p-3.5 shadow-xs"
                                >
                                    <div className="flex flex-wrap justify-between gap-2">
                                        <div className="text-xs font-semibold text-foreground">
                                            {cluster.symbols.join(" · ")}
                                        </div>
                                        <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                                            {label(cluster.correlation_level)}
                                        </div>
                                    </div>
                                    <div className="mt-1 text-[11px] text-muted-foreground">
                                        {cluster.direction.toUpperCase()} ·{" "}
                                        {cluster.gross_risk_r.toFixed(2)}R ·{" "}
                                        {cluster.position_count} position
                                        {cluster.position_count === 1
                                            ? ""
                                            : "s"}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                <div className="text-[11px] leading-4 text-muted-foreground">
                    Ini adalah preview exposure dari posisi yang kamu masukkan.
                    Sistem belum membaca posisi live dari exchange, dan tidak
                    otomatis membuka, menutup, atau merekomendasikan transaksi.
                </div>
            </CardContent>
        </Card>
    );
}

function Metric({ label, value }: { label: string; value: string | number }) {
    return (
        <div className="rounded-xl border border-border bg-background p-3 shadow-xs">
            <div className="text-[10px] uppercase tracking-wider text-muted-foreground">
                {label}
            </div>
            <div className="mt-1 text-sm font-bold tabular-nums text-foreground">
                {value}
            </div>
        </div>
    );
}
