// =============================================================================
// HeadlineSift.com — Ranking Rule Add/Edit Form
// =============================================================================
"use client";

import { useFormState, useFormStatus } from "react-dom";
import { createRankingRule, updateRankingRule } from "./actions";

interface EditRuleInput {
  id: string; categoryId: string; countryId: string | null;
  freshnessWeight: number; sourceTrustWeight: number; sourceCountWeight: number;
  officialSourceBoost: number; impactWeight: number;
  duplicatePenalty: number; lowConfidencePenalty: number; clickbaitPenalty: number;
  maxStories: number; status: string;
}

interface SelectOption { id: string; name: string; code?: string; }

interface Props {
  editRule?: EditRuleInput | null;
  categories: SelectOption[];
  countries: SelectOption[];
  onCancel: () => void;
}

function SubmitButton({ isEditing }: { isEditing: boolean }) {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending} className="btn-primary">
      {pending ? <span className="flex items-center gap-2"><svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"/><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>{isEditing ? "Saving…" : "Creating…"}</span> : (isEditing ? "Save Changes" : "Create Rule")}
    </button>
  );
}

export default function RankingRuleForm({ editRule, categories, countries, onCancel }: Props) {
  const isEditing = !!editRule;
  const action = editRule ? updateRankingRule.bind(null, editRule.id) : createRankingRule;
  const [state, formAction] = useFormState(action, { error: "" });

  return (
    <div className="card animate-slide-up">
      <div className="flex items-center justify-between mb-5">
        <h2 className="text-lg font-semibold text-heading">{isEditing ? "Edit Ranking Rule" : "Add Ranking Rule"}</h2>
        <button type="button" onClick={onCancel} className="btn-ghost text-xs">Cancel</button>
      </div>
      {state.error && <div className="mb-5 rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-inset ring-red-200" role="alert">{state.error}</div>}
      <form action={formAction} className="space-y-5">
        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label htmlFor="categoryId" className="label">Category <span className="text-red-500">*</span></label>
            <select id="categoryId" name="categoryId" required defaultValue={editRule?.categoryId ?? ""} className="input mt-1.5">
              <option value="" disabled>Select a category…</option>
              {categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </div>
          <div>
            <label htmlFor="countryId" className="label">Country</label>
            <select id="countryId" name="countryId" defaultValue={editRule?.countryId ?? ""} className="input mt-1.5">
              <option value="">All countries (global)</option>
              {countries.map((c) => <option key={c.id} value={c.id}>{c.name} ({c.code})</option>)}
            </select>
            <p className="mt-1 text-2xs text-body-muted">Leave empty for a global rule.</p>
          </div>
        </div>

        <div className="border-t border-border pt-5">
          <h3 className="text-sm font-semibold text-heading mb-3">Boost Weights (0–5)</h3>
          <div className="grid gap-4 sm:grid-cols-3">
            {(["freshnessWeight", "sourceTrustWeight", "sourceCountWeight", "officialSourceBoost", "impactWeight"] as const).map((field) => (
              <div key={field}>
                <label htmlFor={field} className="label text-xs">{field.replace(/([A-Z])/g, " $1").replace(/^./, (s) => s.toUpperCase())}</label>
                <input id={field} name={field} type="number" min={0} max={5} step={0.1} defaultValue={editRule?.[field] ?? (field === "officialSourceBoost" ? 1.5 : 1.0)} className="input mt-1.5" style={{ maxWidth: "5rem" }} />
              </div>
            ))}
          </div>
        </div>

        <div className="border-t border-border pt-5">
          <h3 className="text-sm font-semibold text-heading mb-3">Penalties (0–2)</h3>
          <div className="grid gap-4 sm:grid-cols-3">
            {(["duplicatePenalty", "lowConfidencePenalty", "clickbaitPenalty"] as const).map((field) => (
              <div key={field}>
                <label htmlFor={field} className="label text-xs">{field.replace(/([A-Z])/g, " $1").replace(/^./, (s) => s.toUpperCase())}</label>
                <input id={field} name={field} type="number" min={0} max={2} step={0.1} defaultValue={editRule?.[field] ?? (field === "clickbaitPenalty" ? 0.5 : field === "duplicatePenalty" ? 0.8 : 0.7)} className="input mt-1.5" style={{ maxWidth: "5rem" }} />
              </div>
            ))}
          </div>
        </div>

        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label htmlFor="maxStories" className="label">Max Stories</label>
            <input id="maxStories" name="maxStories" type="number" min={1} max={500} defaultValue={editRule?.maxStories ?? 100} className="input mt-1.5" style={{ maxWidth: "6rem" }} />
          </div>
          <div>
            <label htmlFor="status" className="label">Status</label>
            <select id="status" name="status" defaultValue={editRule?.status ?? "ACTIVE"} className="input mt-1.5" style={{ maxWidth: "8rem" }}>
              <option value="ACTIVE">Active</option>
              <option value="INACTIVE">Inactive</option>
              <option value="DRAFT">Draft</option>
            </select>
          </div>
        </div>

        <div className="flex items-center gap-3 pt-1">
          <SubmitButton isEditing={isEditing} />
          <button type="button" onClick={onCancel} className="btn-secondary">Cancel</button>
        </div>
      </form>
    </div>
  );
}
