'use client';

import { useState } from 'react';
import { SCORE_COMPONENTS, SCORE_COMPONENT_LABELS } from '@justice-choice/types';
import { SubmitButton } from './Actions';
import { AlertIcon, CheckCircleIcon, SaveIcon } from './Icons';

/** New ranking version: weights in whole percent with a live total that must reach exactly 100 */
export function WeightsForm({ action, initial }: { action: (fd: FormData) => Promise<void>; initial: Record<string, number> }) {
  const [w, setW] = useState<Record<string, number>>(() => Object.fromEntries(SCORE_COMPONENTS.map((k) => [k, Math.round((initial[k] ?? 0) * 100)])));
  const total = SCORE_COMPONENTS.reduce((s, k) => s + (Number.isFinite(w[k]) ? w[k] : 0), 0);
  const ok = total === 100;
  return (
    <form action={action} className="space-y-4 p-5 text-sm">
      <div className="grid gap-4 sm:grid-cols-3">
        <label className="block">
          <span className="field-label">
            Version <span className="text-danger">*</span>
          </span>
          <input name="version" placeholder="v1.1.0" required pattern="[A-Za-z0-9._\-]+" maxLength={40} className="field num" />
        </label>
        <label className="block sm:col-span-2">
          <span className="field-label">
            Reason for change <span className="text-danger">*</span>
          </span>
          <input name="description" required maxLength={500} className="field" placeholder="e.g. validated with NY matrimonial panel" />
        </label>
      </div>
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
        {SCORE_COMPONENTS.map((k) => (
          <label key={k} className="block rounded-lg border border-rule bg-paper p-2.5">
            <span className="block truncate text-xs font-semibold text-ink-2" title={SCORE_COMPONENT_LABELS[k]}>
              {SCORE_COMPONENT_LABELS[k]}
            </span>
            <span className="relative mt-1 block">
              <input
                name={k}
                type="number"
                min={0}
                max={100}
                step={1}
                inputMode="numeric"
                value={Number.isFinite(w[k]) ? w[k] : ''}
                onChange={(e) => setW((prev) => ({ ...prev, [k]: e.target.value === '' ? NaN : Math.max(0, Math.min(100, Math.round(Number(e.target.value)))) }))}
                className="field num !min-h-9 pr-7"
              />
              <span className="pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-xs text-muted">%</span>
            </span>
          </label>
        ))}
      </div>
      <div className={`flex items-center gap-3 rounded-lg border px-3 py-2.5 ${ok ? 'border-ledger/30 bg-ledger-soft text-ledger' : 'border-danger/30 bg-danger-soft text-danger'}`} aria-live="polite">
        {ok ? <CheckCircleIcon className="h-4 w-4" /> : <AlertIcon className="h-4 w-4" />}
        <span className="flex-1 font-medium">
          Total <span className="num font-bold">{total}%</span> {ok ? '— ready to save' : `— must be exactly 100% (${total > 100 ? `${total - 100} over` : `${100 - total} short`})`}
        </span>
        <span className="h-1.5 w-24 overflow-hidden rounded-full bg-surface">
          <span className="block h-full rounded-full bg-current transition-all" style={{ width: `${Math.min(100, total)}%` }} />
        </span>
      </div>
      <p className="text-xs text-muted">Versions are immutable; activate after expert review, then recalculate.</p>
      <SubmitButton disabled={!ok} pendingLabel="Saving…">
        <SaveIcon className="h-4 w-4" /> Save version
      </SubmitButton>
    </form>
  );
}
