"use client";
import { Plus, X } from "lucide-react";
import { Button, Select, Segmented } from "./ui";

export type Rule = { field: string; op: string; value?: unknown };
export type Definition = { match: "all" | "any"; rules: Rule[] };

export const DEFAULT_FIELDS = [
  { key: "lifecycle_stage", label: "Lifecycle stage" }, { key: "source", label: "Lead source" }, { key: "project", label: "Project" }, { key: "city", label: "City" },
  { key: "territory", label: "Territory" }, { key: "score", label: "Lead score" }, { key: "tags", label: "Tags" }, { key: "owner_id", label: "Owner (user id)" },
  { key: "email", label: "Has email" }, { key: "phone", label: "Has phone" }, { key: "created_at", label: "Created" }, { key: "last_activity_at", label: "Last activity" },
  { key: "deal_stage", label: "Deal stage" }, { key: "event:page_view", label: "Visited website" }, { key: "event:form_submit", label: "Submitted a form" },
  { key: "event:email.opened", label: "Opened an email" }, { key: "event:email.clicked", label: "Clicked an email" }, { key: "event:message_received", label: "Sent us a message" },
  { key: "consent:email", label: "Email consent" }, { key: "consent:sms", label: "SMS consent" }, { key: "consent:whatsapp", label: "WhatsApp consent" },
];

const OPS: Record<string, { value: string; label: string }[]> = {
  text: [{ value: "eq", label: "is" }, { value: "neq", label: "is not" }, { value: "contains", label: "contains" }, { value: "in", label: "is one of" }, { value: "exists", label: "is set" }, { value: "not_exists", label: "is empty" }],
  number: [{ value: "gt", label: ">" }, { value: "lt", label: "<" }, { value: "eq", label: "=" }, { value: "exists", label: "is set" }],
  date: [{ value: "within_days", label: "in the last (days)" }, { value: "lt", label: "before" }, { value: "gt", label: "after" }],
  event: [{ value: "within_days", label: "in the last (days)" }, { value: "exists", label: "ever" }, { value: "not_exists", label: "never" }],
  bool: [{ value: "exists", label: "yes" }, { value: "not_exists", label: "no" }],
  tags: [{ value: "eq", label: "includes" }, { value: "neq", label: "excludes" }, { value: "exists", label: "has any" }],
  consent: [{ value: "eq", label: "is" }, { value: "neq", label: "is not" }],
};

const kindOf = (f: string) => f === "score" || f.startsWith("custom.") && false ? "number" : f.endsWith("_at") ? "date" : f.startsWith("event:") ? "event" : f === "email" || f === "phone" ? "bool" : f === "tags" ? "tags" : f.startsWith("consent:") ? "consent" : f === "score" ? "number" : "text";
const noValue = (op: string, kind: string) => op === "exists" || op === "not_exists" || kind === "bool";

export function RuleBuilder({ value, onChange, fields = DEFAULT_FIELDS, customFields = [], stages = [] }: { value: Definition; onChange: (d: Definition) => void; fields?: { key: string; label: string }[]; customFields?: { key: string; label: string; type: string; options?: string[] }[]; stages?: { id: string; name: string }[] }) {
  const all = [...fields, ...customFields.map((c) => ({ key: `custom.${c.key}`, label: `Custom: ${c.label}` }))];
  const set = (i: number, r: Partial<Rule>) => onChange({ ...value, rules: value.rules.map((x, j) => (j === i ? { ...x, ...r } : x)) });
  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2 text-[12.5px]">Match <Segmented size="sm" value={value.match} onChange={(m) => onChange({ ...value, match: m })} options={[{ value: "all", label: "all" }, { value: "any", label: "any" }]} /> of these rules</div>
      {value.rules.map((r, i) => {
        const kind = r.field === "score" ? "number" : customFields.find((c) => `custom.${c.key}` === r.field)?.type === "number" ? "number" : kindOf(r.field);
        const cf = customFields.find((c) => `custom.${c.key}` === r.field);
        return (
          <div key={i} className="flex flex-wrap items-center gap-2 rounded-[9px] bg-sunken p-2">
            <Select className="min-w-[170px] flex-1" value={r.field} onChange={(e) => { const k = kindOf(e.target.value); set(i, { field: e.target.value, op: OPS[k]![0]!.value, value: k === "consent" ? "opted_in" : "" }); }}>{all.map((f) => <option key={f.key} value={f.key}>{f.label}</option>)}</Select>
            <Select className="w-[150px]" value={r.op} onChange={(e) => set(i, { op: e.target.value })}>{OPS[kind]!.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}</Select>
            {!noValue(r.op, kind) && (
              r.field === "deal_stage" ? <Select className="w-[160px]" value={String(r.value ?? "")} onChange={(e) => set(i, { value: e.target.value })}><option value="">Stage…</option>{stages.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}</Select>
              : kind === "consent" ? <Select className="w-[140px]" value={String(r.value ?? "opted_in")} onChange={(e) => set(i, { value: e.target.value })}><option value="opted_in">opted in</option><option value="opted_out">opted out</option><option value="unknown">unknown</option></Select>
              : r.field === "lifecycle_stage" ? <Select className="w-[160px]" value={String(r.value ?? "")} onChange={(e) => set(i, { value: e.target.value })}><option value="">Choose…</option>{["lead", "opportunity", "customer", "lost"].map((s) => <option key={s}>{s}</option>)}</Select>
              : cf?.options?.length ? <Select className="w-[160px]" value={String(r.value ?? "")} onChange={(e) => set(i, { value: e.target.value })}><option value="">Choose…</option>{cf.options.map((o) => <option key={o}>{o}</option>)}</Select>
              : <input className="field w-[170px]" type={kind === "date" && r.op !== "within_days" ? "date" : kind === "number" || r.op === "within_days" ? "number" : "text"} value={String(r.value ?? "")} onChange={(e) => set(i, { value: e.target.value })} placeholder={r.op === "in" ? "a, b, c" : "value"} />
            )}
            <button aria-label="Remove rule" onClick={() => onChange({ ...value, rules: value.rules.filter((_, j) => j !== i) })} className="ml-auto grid h-7 w-7 place-items-center rounded-full text-ink-3 hover:bg-ink/[.06]"><X className="h-3.5 w-3.5" /></button>
          </div>
        );
      })}
      <Button size="sm" variant="ghost" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => onChange({ ...value, rules: [...value.rules, { field: "project", op: "eq", value: "" }] })}>Add rule</Button>
    </div>
  );
}
