import { InfoButton } from '@/components/grow-better/help-tip';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import type { GrowBetterDirection, GrowBetterModel } from '@/types/grow-better';

const directions: Record<string, GrowBetterDirection> = {
    revenue: 'higher',
    profit: 'higher',
    cash: 'balanced',
    debt: 'lower',
    ops: 'higher',
    retention: 'higher',
};

export function GrowBetterConfig({
    model,
    weights,
    enabled,
    values,
    saving,
    onWeight,
    onToggle,
    onValue,
    onBalance,
    onReset,
}: {
    model: GrowBetterModel;
    weights: Record<string, number>;
    enabled: Record<string, boolean>;
    values: Record<string, number | null>;
    saving: boolean;
    onWeight: (key: string, weight: number) => void;
    onToggle: (key: string, enabled: boolean) => void;
    onValue: (key: string, value: number | null) => void;
    onBalance: () => void;
    onReset: () => void;
}) {
    const total = Object.values(weights).reduce(
        (sum, weight) => sum + weight,
        0,
    );
    const balanced = total === 100;

    return (
        <div className="rounded-xl border px-5">
            {model.pillars.map((pillar) => (
                <section
                    key={pillar.key}
                    className="border-b py-6 last:border-b-0"
                >
                    <div className="mb-3 flex items-center gap-2">
                        <span
                            className="size-2 rounded-full"
                            style={{ background: pillar.color }}
                        />
                        <h3 className="flex items-center gap-1.5 text-sm font-semibold">
                            {pillar.name}
                            {pillar.optional ? ' · optional' : ''}
                            <InfoButton
                                title={pillar.name}
                                help={pillar.help}
                                direction={directions[pillar.key] ?? 'higher'}
                            />
                        </h3>
                        <span className="ml-auto text-sm tabular-nums">
                            {weights[pillar.key] ?? 0}
                            <span className="text-xs text-muted-foreground">
                                %
                            </span>
                        </span>
                    </div>
                    <input
                        type="range"
                        min={0}
                        max={50}
                        value={weights[pillar.key] ?? 0}
                        aria-label={`${pillar.name} weight`}
                        className="mb-4 h-1 w-full cursor-pointer accent-primary"
                        onChange={(event) =>
                            onWeight(pillar.key, Number(event.target.value))
                        }
                    />
                    <div className="grid gap-2 sm:grid-cols-2">
                        {pillar.kpis.map((kpi) => {
                            const isOn = enabled[kpi.key] ?? kpi.enabled;

                            return (
                                <div
                                    key={kpi.key}
                                    className={`flex items-center gap-2 rounded-lg border px-3 py-2 text-sm ${isOn ? '' : 'opacity-50'}`}
                                >
                                    <Checkbox
                                        checked={isOn}
                                        onCheckedChange={(checked) =>
                                            onToggle(kpi.key, checked === true)
                                        }
                                        aria-label={`Include ${kpi.name}`}
                                    />
                                    <span className="flex min-w-0 flex-1 items-center gap-1">
                                        <span className="truncate font-medium">
                                            {kpi.name}
                                        </span>
                                        <InfoButton
                                            title={kpi.name}
                                            help={kpi.help}
                                            direction={kpi.direction}
                                        />
                                    </span>
                                    {kpi.source === 'manual' ? (
                                        <Input
                                            type="number"
                                            inputMode="decimal"
                                            aria-label={`${kpi.name} value`}
                                            className="h-8 w-24"
                                            value={values[kpi.key] ?? ''}
                                            placeholder="Value"
                                            onChange={(event) => {
                                                const next = event.target.value;
                                                onValue(
                                                    kpi.key,
                                                    next === ''
                                                        ? null
                                                        : Number(next),
                                                );
                                            }}
                                        />
                                    ) : (
                                        <span className="text-[11px] text-muted-foreground tabular-nums">
                                            {kpi.display ?? 'No data'}
                                        </span>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                </section>
            ))}
            <div className="flex flex-col gap-3 py-4 sm:flex-row sm:items-center sm:justify-between">
                <p className="text-sm text-muted-foreground">
                    Total pillar weight — recommended 100%
                </p>
                <p className="text-sm">
                    <span className="font-semibold tabular-nums">{total}</span>%
                    {' · '}
                    <span
                        className={
                            balanced
                                ? 'font-semibold text-emerald-600 dark:text-emerald-400'
                                : 'font-semibold text-amber-600 dark:text-amber-400'
                        }
                    >
                        {balanced
                            ? 'Balanced'
                            : `${total > 100 ? 'Over' : 'Under'} by ${Math.abs(total - 100)}% — auto-normalized`}
                    </span>
                </p>
            </div>
            <div className="flex flex-wrap gap-2 pb-5">
                <Button type="button" onClick={onBalance}>
                    Auto-balance to 100%
                </Button>
                <Button type="button" variant="outline" onClick={onReset}>
                    Reset
                </Button>
                <span className="self-center text-xs text-muted-foreground">
                    {saving ? 'Saving…' : 'Changes save automatically'}
                </span>
            </div>
        </div>
    );
}
