"use client";

import { useState } from "react";
import { toast } from "sonner";
import { RotateCcw, Save } from "lucide-react";
import { cn } from "@/shared/lib/utils";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useT } from "@/shared/i18n/client";
import { useAuth } from "@/presentation/hooks/use-auth";
import { Button } from "@/presentation/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/presentation/components/ui/card";
import { Input } from "@/presentation/components/ui/input";
import { Slider } from "@/presentation/components/ui/slider";
import { Skeleton } from "@/presentation/components/ui/skeleton";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/presentation/components/ui/select";
import ConfirmationDialog from "@/presentation/components/shared/confirmation-dialog";
import { createHealthConfigSchema, type HealthConfigFormValues } from "@/shared/schemas/health-config.schema";
import { useHealthConfig } from "../hooks/use-health-config";
import type { HealthConfig } from "@/domain/entities/health";

const WEIGHT_KEYS = ["activity", "adoption", "frequency", "completeness", "growth"] as const;
const COMPLETENESS_FIELDS = [
  "mark", "model", "construction_year", "c1_id", "c3_id", "site_id",
  "park_entry_date", "custom_status_id", "vin", "numberplate", "motor_type",
  "purchase_date", "purchase_price",
];

function toForm(c: HealthConfig): HealthConfigFormValues {
  return {
    weights: c.weights,
    target_actions: c.targets.target_actions,
    target_logins: c.targets.target_logins,
    growth_band: c.growth_band,
    tier_healthy: c.tiers.healthy,
    tier_at_risk: c.tiers.at_risk,
    module_thresholds: { ...c.module_thresholds },
    completeness_items: [...c.completeness_items],
    alert_thresholds: { ...c.alert_thresholds },
    // "custom" is never a persistable default; coerce defensively.
    default_period: c.default_period === "custom" ? "month" : c.default_period,
  };
}

export default function HealthConfigPage() {
  const t = useT();
  usePageHeader(t.pages.healthConfig.title, t.pages.healthConfig.subtitle);
  const { hasPermission } = useAuth();
  const canManage = hasPermission("health.manage");
  const { data: config, loading, save, reset } = useHealthConfig();

  const [form, setForm] = useState<HealthConfigFormValues | null>(null);
  const [seeded, setSeeded] = useState<HealthConfig | null>(null);
  const [resetOpen, setResetOpen] = useState(false);

  // Seed / re-seed the editable form whenever a fresh config arrives (initial
  // load, save, reset). Guarded state-adjustment during render — the React-
  // endorsed pattern for deriving state from changing props/data.
  if (config && config !== seeded) {
    setSeeded(config);
    setForm(toForm(config));
  }

  if (loading || !form || !config) {
    return (
      <div className="p-6 space-y-4">
        <Skeleton className="h-40 rounded-xl" />
        <Skeleton className="h-64 rounded-xl" />
      </div>
    );
  }

  const weightSum = WEIGHT_KEYS.reduce((s, k) => s + (form.weights[k] || 0), 0);
  const set = <K extends keyof HealthConfigFormValues>(key: K, value: HealthConfigFormValues[K]) =>
    setForm((f) => (f ? { ...f, [key]: value } : f));

  const onSave = () => {
    const parsed = createHealthConfigSchema(t).safeParse(form);
    if (!parsed.success) {
      toast.error(parsed.error.issues[0]?.message ?? t.validation.weightsMustTotal100);
      return;
    }
    save.mutate(parsed.data);
  };

  const disabled = !canManage;

  return (
    <div className="p-6 space-y-4">
      {!canManage && (
        <p className="text-xs text-muted-foreground bg-muted/50 rounded-lg px-3 py-2">{t.health.config.readOnly}</p>
      )}

      {/* Score weights */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center justify-between">
            {t.health.config.scoreWeights}
            <span
              className={cn(
                "text-sm font-mono font-semibold rounded-full px-2.5 py-0.5",
                weightSum === 100 ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400" : "bg-red-100 text-red-700 dark:bg-red-950/40 dark:text-red-400"
              )}
            >
              {t.health.config.total} {weightSum}
            </span>
          </CardTitle>
          <p className="text-xs text-muted-foreground">{t.health.config.weightsHint}</p>
        </CardHeader>
        <CardContent className="space-y-4">
          {WEIGHT_KEYS.map((k) => (
            <div key={k} className="flex items-center gap-4">
              <span className="w-40 text-sm">{t.health.config.weights[k]}</span>
              <Slider
                value={[form.weights[k]]}
                min={0}
                max={100}
                step={5}
                disabled={disabled}
                onValueChange={([v]) => set("weights", { ...form.weights, [k]: v })}
                className="flex-1"
              />
              <span className="w-10 text-right font-mono text-sm">{form.weights[k]}%</span>
            </div>
          ))}
        </CardContent>
      </Card>

      {/* Targets & calibration */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t.health.config.targets}</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <NumberField label={t.health.config.targetActions} suffix={t.health.config.perMonth} value={form.target_actions} onChange={(v) => set("target_actions", v)} disabled={disabled} />
          <NumberField label={t.health.config.targetLogins} suffix={t.health.config.perMonth} value={form.target_logins} onChange={(v) => set("target_logins", v)} disabled={disabled} />
          <NumberField label={t.health.config.growthBand} suffix="±%" value={form.growth_band} onChange={(v) => set("growth_band", v)} disabled={disabled} />
        </CardContent>
      </Card>

      {/* Tier cut-offs + default period */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t.health.config.tierCutoffs}</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <NumberField label={t.health.config.tierHealthy} value={form.tier_healthy} onChange={(v) => set("tier_healthy", v)} disabled={disabled} />
          <NumberField label={t.health.config.tierAtRisk} value={form.tier_at_risk} onChange={(v) => set("tier_at_risk", v)} disabled={disabled} />
          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">{t.health.config.defaultPeriod}</label>
            <Select value={form.default_period} onValueChange={(v) => set("default_period", v as HealthConfigFormValues["default_period"])} disabled={disabled}>
              <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="month">{t.health.periods.month}</SelectItem>
                <SelectItem value="week">{t.health.periods.week}</SelectItem>
                <SelectItem value="3months">{t.health.periods["3months"]}</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* Per-module adoption thresholds */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t.health.config.moduleThresholds}</CardTitle>
          <p className="text-xs text-muted-foreground">{t.health.config.moduleThresholdsHint}</p>
        </CardHeader>
        <CardContent className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
          {config.modules.map((m) => (
            <div key={m.key} className="flex items-center gap-2">
              <span className="flex-1 text-sm truncate">{m.label}</span>
              <Input
                type="number"
                value={form.module_thresholds[m.key] ?? 0}
                disabled={disabled}
                onChange={(e) => set("module_thresholds", { ...form.module_thresholds, [m.key]: Number(e.target.value) })}
                className="w-20 h-8"
              />
              <span className="w-8 text-xs text-muted-foreground">{m.unit === "percent_vehicles" ? "%" : "min"}</span>
            </div>
          ))}
        </CardContent>
      </Card>

      {/* Alert thresholds */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t.health.config.alertThresholds}</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {Object.keys(form.alert_thresholds).map((key) => (
            <NumberField
              key={key}
              label={alertLabel(t, key)}
              value={form.alert_thresholds[key]}
              onChange={(v) => set("alert_thresholds", { ...form.alert_thresholds, [key]: v })}
              disabled={disabled}
            />
          ))}
        </CardContent>
      </Card>

      {/* Completeness items */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t.health.config.completenessItems}</CardTitle>
        </CardHeader>
        <CardContent className="flex flex-wrap gap-2">
          {COMPLETENESS_FIELDS.map((field) => {
            const selected = form.completeness_items.includes(field);
            return (
              <button
                key={field}
                disabled={disabled}
                onClick={() =>
                  set(
                    "completeness_items",
                    selected ? form.completeness_items.filter((f) => f !== field) : [...form.completeness_items, field]
                  )
                }
                className={cn(
                  "text-xs rounded-full border px-2.5 py-1 font-mono transition-colors disabled:opacity-60",
                  selected ? "bg-primary text-primary-foreground border-primary" : "bg-card border-border hover:bg-muted/50"
                )}
              >
                {field}
              </button>
            );
          })}
        </CardContent>
      </Card>

      {/* Actions */}
      {canManage && (
        <div className="flex items-center justify-end gap-2 sticky bottom-0 bg-background/80 backdrop-blur py-3">
          <Button variant="outline" onClick={() => setResetOpen(true)} disabled={reset.loading}>
            <RotateCcw className="w-4 h-4 mr-1.5" />
            {t.health.config.reset}
          </Button>
          <Button onClick={onSave} disabled={save.loading || weightSum !== 100}>
            <Save className="w-4 h-4 mr-1.5" />
            {t.health.config.save}
          </Button>
        </div>
      )}

      <ConfirmationDialog
        open={resetOpen}
        onOpenChange={setResetOpen}
        title={t.health.config.resetTitle}
        description={t.health.config.resetDescription}
        confirmLabel={t.health.config.reset}
        loading={reset.loading}
        onConfirm={async () => {
          await reset.mutate();
          setResetOpen(false);
        }}
      />
    </div>
  );
}

function NumberField({
  label,
  value,
  onChange,
  suffix,
  disabled,
}: {
  label: string;
  value: number;
  onChange: (v: number) => void;
  suffix?: string;
  disabled?: boolean;
}) {
  return (
    <div>
      <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">{label}</label>
      <div className="flex items-center gap-2">
        <Input
          type="number"
          value={value}
          disabled={disabled}
          onChange={(e) => onChange(Number(e.target.value))}
          className="h-9"
        />
        {suffix && <span className="text-xs text-muted-foreground whitespace-nowrap">{suffix}</span>}
      </div>
    </div>
  );
}

function alertLabel(t: ReturnType<typeof useT>, key: string): string {
  const alerts = t.health.config.alerts as Record<string, string>;
  return alerts[key] ?? key;
}
