"use client";

import { useState } from "react";

import { useToast } from "@/components/admin/common/ToastProvider";

type Rule = {
  id: string;
  target: string;
  action: string;
  matchType: string;
  matchValue: string;
  priority: number;
  isActive: boolean;
  description: string | null;
  hitCount: number;
  lastHitAt: string | null;
  createdAt: string;
};

const TARGET_LABELS: Record<string, string> = {
  SUBMISSION: "Prijava firme",
  REVIEW: "Recenzija",
  PROFILE_QUESTION: "Pitanje na profilu",
  LISTING_LEAD: "Lead / upit",
};

const ACTION_LABELS: Record<string, string> = {
  AUTO_APPROVE: "Auto-odobri",
  AUTO_REJECT: "Auto-odbij",
  FLAG_FOR_REVIEW: "Označi za pregled",
  PRIORITIZE: "Prioritet u redu",
};

const MATCH_TYPE_LABELS: Record<string, string> = {
  EMAIL_DOMAIN: "E-mail domen (npr. @smartechor.rs)",
  EMAIL_EXACT: "Tačan e-mail",
  IP_CIDR: "IP / CIDR (npr. 192.168.1.0/24)",
  PHONE_PREFIX: "Telefon prefiks (npr. 38165)",
  KEYWORD_CONTAINS: "Sadrži reč",
  KEYWORD_REGEX: "Regex u tekstu",
  COMPANY_NAME_CONTAINS: "Naziv firme sadrži",
};

const ACTION_TONE: Record<string, string> = {
  AUTO_APPROVE: "bg-emerald-100 text-emerald-800",
  AUTO_REJECT: "bg-rose-100 text-rose-800",
  FLAG_FOR_REVIEW: "bg-amber-100 text-amber-800",
  PRIORITIZE: "bg-sky-100 text-sky-800",
};

export function AutoModerationManager({ initialRules }: { initialRules: Rule[] }) {
  const [rules, setRules] = useState<Rule[]>(initialRules);
  const [creating, setCreating] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  const toast = useToast();
  const [form, setForm] = useState({
    target: "SUBMISSION",
    action: "FLAG_FOR_REVIEW",
    matchType: "EMAIL_DOMAIN",
    matchValue: "",
    priority: 100,
    description: "",
  });

  async function create() {
    if (form.matchValue.trim().length < 2) return;
    setCreating(true);
    try {
      const res = await fetch("/api/admin/auto-moderation", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = (await res.json()) as { ok?: boolean; rule?: Rule; error?: string };
      if (res.ok && data.rule) {
        setRules((r) => [...r, data.rule!]);
        setForm({ ...form, matchValue: "", description: "" });
        setFormError(null);
        toast.success("Pravilo je kreirano.");
      } else {
        const msg = data.error || "Greška pri kreiranju.";
        setFormError(msg);
        toast.error(msg);
      }
    } finally {
      setCreating(false);
    }
  }

  async function toggle(id: string, isActive: boolean) {
    const res = await fetch(`/api/admin/auto-moderation/${id}`, {
      method: "PATCH",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ isActive }),
    });
    if (res.ok) {
      setRules((r) => r.map((x) => (x.id === id ? { ...x, isActive } : x)));
    }
  }

  async function remove(id: string) {
    if (!confirm("Obrisati pravilo?")) return;
    const res = await fetch(`/api/admin/auto-moderation/${id}`, { method: "DELETE" });
    if (res.ok) setRules((r) => r.filter((x) => x.id !== id));
  }

  const grouped = new Map<string, Rule[]>();
  for (const r of rules) {
    const arr = grouped.get(r.target) ?? [];
    arr.push(r);
    grouped.set(r.target, arr);
  }

  return (
    <div className="space-y-6">
      <section className="rounded-2xl border border-border bg-white p-5">
        <h2 className="font-display text-lg font-bold">Novo pravilo</h2>
        <div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          <Field label="Resurs">
            <select
              value={form.target}
              onChange={(e) => setForm({ ...form, target: e.target.value })}
              className="h-10 w-full rounded-lg border border-border bg-white px-3 text-sm"
            >
              {Object.entries(TARGET_LABELS).map(([k, v]) => (
                <option key={k} value={k}>{v}</option>
              ))}
            </select>
          </Field>
          <Field label="Akcija">
            <select
              value={form.action}
              onChange={(e) => setForm({ ...form, action: e.target.value })}
              className="h-10 w-full rounded-lg border border-border bg-white px-3 text-sm"
            >
              {Object.entries(ACTION_LABELS).map(([k, v]) => (
                <option key={k} value={k}>{v}</option>
              ))}
            </select>
          </Field>
          <Field label="Vrsta provere">
            <select
              value={form.matchType}
              onChange={(e) => setForm({ ...form, matchType: e.target.value })}
              className="h-10 w-full rounded-lg border border-border bg-white px-3 text-sm"
            >
              {Object.entries(MATCH_TYPE_LABELS).map(([k, v]) => (
                <option key={k} value={k}>{v}</option>
              ))}
            </select>
          </Field>
          <Field label="Vrednost" full>
            <input
              type="text"
              value={form.matchValue}
              onChange={(e) => setForm({ ...form, matchValue: e.target.value })}
              placeholder="npr. @gmail.com  /  viagra|kazino  /  192.168.1.0/24"
              className="h-10 w-full rounded-lg border border-border bg-white px-3 font-mono text-sm"
            />
          </Field>
          <Field label="Prioritet (manji = viši)">
            <input
              type="number"
              value={form.priority}
              onChange={(e) => setForm({ ...form, priority: Number(e.target.value) || 100 })}
              className="h-10 w-full rounded-lg border border-border bg-white px-3 text-sm"
            />
          </Field>
          <Field label="Opis (audit)" full>
            <input
              type="text"
              value={form.description}
              onChange={(e) => setForm({ ...form, description: e.target.value })}
              placeholder="Zašto si dodao ovo pravilo?"
              className="h-10 w-full rounded-lg border border-border bg-white px-3 text-sm"
            />
          </Field>
        </div>
        <button
          type="button"
          onClick={create}
          disabled={creating || form.matchValue.trim().length < 2}
          className="mt-4 inline-flex h-10 items-center rounded-lg bg-primary px-5 text-sm font-bold text-primary-foreground disabled:opacity-50"
        >
          {creating ? "Kreiram…" : "Dodaj pravilo"}
        </button>
        {formError && (
          <p className="mt-3 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700">
            {formError}
          </p>
        )}
      </section>

      {[...grouped.entries()].map(([target, items]) => (
        <section key={target} className="rounded-2xl border border-border bg-white p-5">
          <h3 className="font-display text-base font-bold">
            {TARGET_LABELS[target] || target}
            <span className="ml-2 text-sm font-normal text-muted-foreground">
              ({items.length})
            </span>
          </h3>
          <div className="mt-4 space-y-2">
            {items.map((r) => (
              <article
                key={r.id}
                className="flex flex-wrap items-start gap-3 rounded-xl border border-border/60 bg-zinc-50 p-3"
              >
                <span
                  className={`shrink-0 rounded-full px-2.5 py-1 text-xs font-bold ${ACTION_TONE[r.action] || ""}`}
                >
                  {ACTION_LABELS[r.action] || r.action}
                </span>
                <div className="min-w-0 flex-1">
                  <p className="text-sm">
                    <span className="text-muted-foreground">
                      {MATCH_TYPE_LABELS[r.matchType] || r.matchType}:
                    </span>{" "}
                    <code className="rounded bg-zinc-200 px-1.5 py-0.5 font-mono text-xs">
                      {r.matchValue}
                    </code>
                  </p>
                  {r.description && (
                    <p className="mt-1 text-xs text-muted-foreground">{r.description}</p>
                  )}
                  <p className="mt-1 text-xs text-muted-foreground">
                    Prioritet: {r.priority} · Aktivirano {r.hitCount}×
                    {r.lastHitAt &&
                      ` · poslednji put ${new Date(r.lastHitAt).toLocaleString("sr-Latn-RS")}`}
                  </p>
                </div>
                <div className="flex shrink-0 items-center gap-2">
                  <label className="flex cursor-pointer items-center gap-1.5 text-xs">
                    <input
                      type="checkbox"
                      checked={r.isActive}
                      onChange={(e) => toggle(r.id, e.target.checked)}
                    />
                    Aktivno
                  </label>
                  <button
                    type="button"
                    onClick={() => remove(r.id)}
                    className="rounded-lg border border-rose-200 bg-white px-2.5 py-1 text-xs font-semibold text-rose-700 hover:bg-rose-50"
                  >
                    Obriši
                  </button>
                </div>
              </article>
            ))}
          </div>
        </section>
      ))}

      {rules.length === 0 && (
        <p className="rounded-2xl border border-dashed border-border bg-zinc-50 p-8 text-center text-sm text-muted-foreground">
          Još nema definisanih pravila. Dodajte prvo gore — najčešći šablon je
          „<strong>Auto-odobri</strong> · EMAIL_DOMAIN · @yourtrusteddomain.rs”.
        </p>
      )}
    </div>
  );
}

function Field({
  label,
  children,
  full,
}: {
  label: string;
  children: React.ReactNode;
  full?: boolean;
}) {
  return (
    <div className={full ? "sm:col-span-2 lg:col-span-3" : ""}>
      <label className="text-xs font-bold uppercase tracking-wide text-muted-foreground">
        {label}
      </label>
      <div className="mt-1">{children}</div>
    </div>
  );
}
