import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { Toggle } from "@/components/ui/toggle";
import {
    DropdownMenu,
    DropdownMenuCheckboxItem,
    DropdownMenuContent,
    DropdownMenuLabel,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import type { ReactNode } from "react";
import type { IndicatorState } from "@/lib/market";
import { intervalLabel } from "@/lib/market";
import { useI18n } from "@/lib/i18n";
import {
    ChevronDown,
    Clock,
    Cpu,
    Ellipsis,
    LineChart,
    RotateCcw,
    Shapes,
    SlidersHorizontal,
    Zap,
} from "lucide-react";

export interface TradingChartToolbarProps {
    indicators: IndicatorState;
    onIndicatorChange: (key: keyof IndicatorState, pressed: boolean) => void;
    intervals: string[];
    interval: string;
    onIntervalChange: (interval: string) => void;
    backtestAvailable: boolean;
    backtestEnabled: boolean;
    onBacktestChange: (pressed: boolean) => void;
    signalAvailable: boolean;
    signalEnabled: boolean;
    onSignalChange: (pressed: boolean) => void;
    onResetChart: () => void;
}

const INDICATOR_OPTIONS: { key: keyof IndicatorState; labelKey: string }[] = [
    { key: "volume", labelKey: "chart.volume" },
    { key: "volumeProfile", labelKey: "chart.volume_profile" },
    { key: "sma20", labelKey: "chart.sma20" },
    { key: "ema50", labelKey: "chart.ema50" },
    { key: "bb", labelKey: "chart.bollinger" },
    { key: "rsi", labelKey: "chart.rsi14" },
    { key: "sr", labelKey: "chart.support_resistance" },
];

const SMC_OPTIONS: { key: keyof IndicatorState; labelKey: string }[] = [
    { key: "accumulation", labelKey: "chart.accumulation" },
    { key: "ob", labelKey: "chart.order_block" },
    { key: "fvg", labelKey: "chart.fvg" },
    { key: "structure", labelKey: "chart.structure" },
    { key: "swing", labelKey: "chart.swing" },
];

const PATTERN_OPTIONS: { key: keyof IndicatorState; labelKey: string }[] = [
    { key: "breakout", labelKey: "chart.pattern_breakout" },
    { key: "reversal", labelKey: "chart.pattern_reversal" },
    { key: "pullback", labelKey: "chart.pattern_pullback" },
];

const VISIBLE_INDICATOR_COUNT = 4;
const VISIBLE_SMC_COUNT = 3;

export default function TradingChartToolbar({
    indicators,
    onIndicatorChange,
    intervals,
    interval,
    onIntervalChange,
    backtestAvailable,
    backtestEnabled,
    onBacktestChange,
    signalAvailable,
    signalEnabled,
    onSignalChange,
    onResetChart,
}: TradingChartToolbarProps) {
    const { t } = useI18n();

    const selectedIndicators = INDICATOR_OPTIONS.filter(({ key }) =>
        Boolean(indicators[key]),
    ).map(({ key }) => key);
    const selectedSmc = SMC_OPTIONS.filter(({ key }) =>
        Boolean(indicators[key]),
    ).map(({ key }) => key);
    const selectedPatterns = PATTERN_OPTIONS.filter(({ key }) =>
        Boolean(indicators[key]),
    ).map(({ key }) => key);

    const activeOverlayCount =
        selectedIndicators.length +
        selectedPatterns.length +
        selectedSmc.length;

    const setIndicatorGroup = (values: string[]) => {
        const selected = new Set(values);
        INDICATOR_OPTIONS.forEach(({ key }) =>
            onIndicatorChange(key, selected.has(key)),
        );
    };

    const setSmcGroup = (values: string[]) => {
        const selected = new Set(values);
        SMC_OPTIONS.forEach(({ key }) =>
            onIndicatorChange(key, selected.has(key)),
        );
    };

    const setPatternGroup = (values: string[]) => {
        const selected = new Set(values);
        PATTERN_OPTIONS.forEach(({ key }) =>
            onIndicatorChange(key, selected.has(key)),
        );
    };

    const clearAllOverlays = () => {
        INDICATOR_OPTIONS.forEach(({ key }) => onIndicatorChange(key, false));
        PATTERN_OPTIONS.forEach(({ key }) => onIndicatorChange(key, false));
        SMC_OPTIONS.forEach(({ key }) => onIndicatorChange(key, false));
    };

    return (
        <div
            className="mb-4 w-full min-w-0 overflow-visible rounded-2xl border border-border/60 bg-card/95 shadow-[0_8px_30px_-22px_rgba(15,23,42,0.45)] backdrop-blur-xl"
            role="toolbar"
            aria-label={t("chart.tools", "Chart tools")}
        >
            <div className="flex min-w-0 flex-col gap-3 border-b border-border/50 px-3 py-3 sm:px-4 lg:flex-row lg:items-center lg:justify-between lg:px-5">
                <div className="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
                    <div className="flex shrink-0 items-center gap-2.5">
                        <div className="flex h-8 w-8 items-center justify-center rounded-xl border border-primary/15 bg-primary/10 text-primary">
                            <Clock className="h-4 w-4" />
                        </div>
                        <div className="leading-none">
                            <p className="text-[10px] font-bold uppercase tracking-[0.16em] text-muted-foreground">
                                {t("chart.timeframe", "Timeframe")}
                            </p>
                            <p className="mt-1 text-xs font-semibold text-foreground">
                                Analysis period
                            </p>
                        </div>
                    </div>

                    <ToggleGroup
                        type="single"
                        value={interval}
                        onValueChange={(value) =>
                            value && onIntervalChange(value)
                        }
                        className="flex w-fit max-w-full flex-wrap gap-1 rounded-xl border border-border/60 bg-muted/20 p-1"
                        aria-label={t("chart.timeframe", "Timeframe")}
                    >
                        {intervals.map((tf) => (
                            <ToggleGroupItem
                                key={tf}
                                value={tf}
                                size="sm"
                                className="h-8 min-w-[2.65rem] rounded-lg px-2.5 text-xs font-semibold text-muted-foreground transition-all hover:bg-background hover:text-foreground data-[state=on]:bg-primary data-[state=on]:text-primary-foreground data-[state=on]:shadow-sm"
                            >
                                {intervalLabel(tf)}
                            </ToggleGroupItem>
                        ))}
                    </ToggleGroup>
                </div>

                <div className="flex flex-wrap items-center gap-2 sm:justify-end">
                    {backtestAvailable && (
                        <FeatureToggle
                            pressed={backtestEnabled}
                            onPressedChange={onBacktestChange}
                            icon={<LineChart className="h-4 w-4" />}
                            label={t("chart.backtest", "Backtest")}
                            activeTone="primary"
                        />
                    )}
                    {signalAvailable && (
                        <FeatureToggle
                            pressed={signalEnabled}
                            onPressedChange={onSignalChange}
                            icon={<Zap className="h-4 w-4" />}
                            label={t("chart.signal_engine", "Signal Engine")}
                            activeTone="success"
                        />
                    )}
                    <span className="mx-0.5 hidden h-6 w-px bg-border sm:block" />
                    <button
                        type="button"
                        onClick={onResetChart}
                        className="inline-flex h-9 items-center justify-center gap-2 rounded-xl border border-border/60 bg-background/60 px-3 text-xs font-semibold text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground"
                        aria-label={t("chart.reset_view", "Reset chart")}
                        title={t("chart.reset_view", "Reset chart")}
                    >
                        <RotateCcw className="h-3.5 w-3.5" />
                        <span>{t("chart.reset_view", "Reset chart")}</span>
                    </button>
                    {activeOverlayCount > 0 && (
                        <button
                            type="button"
                            onClick={clearAllOverlays}
                            className="inline-flex h-9 items-center justify-center gap-2 rounded-xl border border-border/60 bg-background/60 px-3 text-xs font-semibold text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground"
                        >
                            Clear all
                        </button>
                    )}
                </div>
            </div>

            <div className="max-w-full overflow-x-auto px-3 py-3 sm:px-4 sm:py-4 lg:px-5">
                <div className="grid min-w-0 grid-cols-1 divide-y divide-border/50 rounded-xl border border-border/50 bg-muted/12 lg:grid-cols-[1.35fr_0.85fr_1.35fr] lg:divide-x lg:divide-y-0">
                    <ToolbarGroup
                        icon={<SlidersHorizontal className="h-3.5 w-3.5" />}
                        label={t("chart.indicators", "Indicators")}
                        activeCount={selectedIndicators.length}
                        totalCount={INDICATOR_OPTIONS.length}
                        tone="primary"
                        options={INDICATOR_OPTIONS}
                        selected={selectedIndicators}
                        visibleCount={VISIBLE_INDICATOR_COUNT}
                        onValueChange={setIndicatorGroup}
                        onIndicatorChange={onIndicatorChange}
                        t={t}
                    />

                    <ToolbarGroup
                        icon={<Shapes className="h-3.5 w-3.5" />}
                        label={t("chart.patterns", "Patterns")}
                        activeCount={selectedPatterns.length}
                        totalCount={PATTERN_OPTIONS.length}
                        tone="success"
                        options={PATTERN_OPTIONS}
                        selected={selectedPatterns}
                        visibleCount={PATTERN_OPTIONS.length}
                        onValueChange={setPatternGroup}
                        onIndicatorChange={onIndicatorChange}
                        t={t}
                    />

                    <ToolbarGroup
                        icon={<Cpu className="h-3.5 w-3.5" />}
                        label="SMC Concepts"
                        activeCount={selectedSmc.length}
                        totalCount={SMC_OPTIONS.length}
                        tone="indigo"
                        options={SMC_OPTIONS}
                        selected={selectedSmc}
                        visibleCount={VISIBLE_SMC_COUNT}
                        onValueChange={setSmcGroup}
                        onIndicatorChange={onIndicatorChange}
                        t={t}
                    />
                </div>
            </div>
        </div>
    );
}

function ToolbarGroup({
    icon,
    label,
    activeCount,
    totalCount,
    tone,
    options,
    selected,
    visibleCount,
    onValueChange,
    onIndicatorChange,
    t,
}: {
    icon: ReactNode;
    label: string;
    activeCount: number;
    totalCount: number;
    tone: "primary" | "success" | "indigo";
    options: { key: keyof IndicatorState; labelKey: string }[];
    selected: (keyof IndicatorState)[];
    visibleCount: number;
    onValueChange: (values: string[]) => void;
    onIndicatorChange: (key: keyof IndicatorState, pressed: boolean) => void;
    t: (key: string, fallback?: string) => string;
}) {
    const visibleOptions = options.slice(0, visibleCount);
    const advancedOptions = options.slice(visibleCount);
    const advancedActiveCount = advancedOptions.filter(({ key }) =>
        Boolean(selected.includes(key)),
    ).length;

    const toneStyles = {
        primary: {
            icon: "border-primary/15 bg-primary/10 text-primary",
            active: "data-[state=on]:border-primary/35 data-[state=on]:bg-primary/10 data-[state=on]:text-primary",
            more: "border-primary/15 bg-primary/5 text-primary hover:bg-primary/10",
        },
        success: {
            icon: "border-success-500/15 bg-success-500/10 text-success-600 dark:text-success-400",
            active: "data-[state=on]:border-success-500/35 data-[state=on]:bg-success-500/10 data-[state=on]:text-success-600 dark:data-[state=on]:text-success-400",
            more: "border-success-500/15 bg-success-500/5 text-success-700 hover:bg-success-500/10 dark:text-success-400",
        },
        indigo: {
            icon: "border-primary-500/15 bg-primary-500/10 text-primary-500",
            active: "data-[state=on]:border-primary-500/35 data-[state=on]:bg-primary-500/10 data-[state=on]:text-primary-500",
            more: "border-primary-500/15 bg-primary-500/5 text-primary-600 hover:bg-primary-500/10 dark:text-primary-400",
        },
    }[tone];

    return (
        <section className="min-w-0 px-3 py-3.5 sm:px-4">
            <div className="mb-2.5 flex items-center justify-between gap-2">
                <div className="flex min-w-0 items-center gap-2">
                    <div
                        className={cn(
                            "flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border",
                            toneStyles.icon,
                        )}
                    >
                        {icon}
                    </div>
                    <div className="min-w-0">
                        <div className="flex items-center gap-2">
                            <p className="truncate text-[11px] font-bold uppercase tracking-[0.12em] text-muted-foreground">
                                {label}
                            </p>
                            <span className="rounded-full bg-background/70 px-1.5 py-0.5 text-[9px] font-bold tabular-nums text-muted-foreground">
                                {activeCount}/{totalCount}
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <div className="flex flex-wrap items-center gap-1.5">
                <ToggleGroup
                    type="multiple"
                    value={selected}
                    onValueChange={onValueChange}
                    className="flex flex-wrap gap-1.5"
                    aria-label={label}
                >
                    {visibleOptions.map(({ key, labelKey }) => (
                        <ToggleGroupItem
                            key={key}
                            value={key}
                            size="sm"
                            className={cn(
                                "h-8 shrink-0 rounded-lg border border-border/55 bg-background/75 px-2.5 text-xs font-medium transition-colors hover:border-border hover:bg-background",
                                toneStyles.active,
                                "data-[state=on]:font-semibold",
                            )}
                        >
                            {t(labelKey, labelKey)}
                        </ToggleGroupItem>
                    ))}
                </ToggleGroup>

                {advancedOptions.length > 0 && (
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <button
                                type="button"
                                className={cn(
                                    "inline-flex h-8 items-center gap-1 rounded-lg border px-2.5 text-xs font-semibold transition-colors",
                                    toneStyles.more,
                                )}
                            >
                                <Ellipsis className="h-3.5 w-3.5" />
                                More
                                {advancedActiveCount > 0 && (
                                    <span className="rounded-full bg-background/80 px-1.5 py-0.5 text-[9px] font-bold tabular-nums">
                                        {advancedActiveCount}
                                    </span>
                                )}
                                <ChevronDown className="h-3 w-3 opacity-60" />
                            </button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="start" className="w-52">
                            <DropdownMenuLabel>{label}</DropdownMenuLabel>
                            <DropdownMenuSeparator />
                            {advancedOptions.map(({ key, labelKey }) => (
                                <DropdownMenuCheckboxItem
                                    key={key}
                                    checked={Boolean(selected.includes(key))}
                                    onCheckedChange={(checked) =>
                                        onIndicatorChange(key, checked === true)
                                    }
                                >
                                    {t(labelKey, labelKey)}
                                </DropdownMenuCheckboxItem>
                            ))}
                        </DropdownMenuContent>
                    </DropdownMenu>
                )}
            </div>
        </section>
    );
}

function FeatureToggle({
    pressed,
    onPressedChange,
    icon,
    label,
    activeTone,
}: {
    pressed: boolean;
    onPressedChange: (pressed: boolean) => void;
    icon: ReactNode;
    label: string;
    activeTone: "primary" | "success";
}) {
    return (
        <Toggle
            type="button"
            pressed={pressed}
            onPressedChange={onPressedChange}
            variant="outline"
            size="sm"
            className={cn(
                "h-9 rounded-xl border-border/60 bg-background/65 px-3 text-xs font-semibold transition-all",
                "hover:border-border hover:bg-muted/45",
                activeTone === "primary" &&
                    "data-[state=on]:border-primary/35 data-[state=on]:bg-primary/10 data-[state=on]:text-primary",
                activeTone === "success" &&
                    "data-[state=on]:border-success-500/35 data-[state=on]:bg-success-500/10 data-[state=on]:text-success-600 dark:data-[state=on]:text-success-400",
            )}
        >
            <span
                className={cn(
                    "mr-1.5",
                    activeTone === "primary" && "text-primary",
                    activeTone === "success" && "text-warning-500",
                )}
            >
                {icon}
            </span>
            {label}
            <span
                className={cn(
                    "ml-1.5 inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-[0.08em]",
                    pressed
                        ? activeTone === "primary"
                            ? "bg-primary/10 text-primary"
                            : "bg-success-500/10 text-success-600 dark:text-success-400"
                        : "bg-muted/70 text-muted-foreground",
                )}
            >
                <span
                    className={cn(
                        "h-1.5 w-1.5 rounded-full",
                        pressed
                            ? activeTone === "primary"
                                ? "bg-primary"
                                : "bg-success-500"
                            : "bg-muted-foreground/45",
                    )}
                />
                {pressed ? "On" : "Off"}
            </span>
        </Toggle>
    );
}
