/* global React, Icon, Chip, Button, api */

const SM_ICON_OPTIONS = [
  { name: "plane",          label: "Plane"           },
  { name: "users-round",    label: "Users"           },
  { name: "file-signature", label: "File-signature"  },
  { name: "badge-check",    label: "Badge-check"     },
  { name: "landmark",       label: "Landmark"        },
  { name: "briefcase",      label: "Briefcase"       },
  { name: "building-2",     label: "Building"        },
  { name: "stamp",          label: "Stamp"           },
  { name: "shield",         label: "Shield"          },
  { name: "globe",          label: "Globe"           },
  { name: "file-text",      label: "File"            },
  { name: "wallet",         label: "Wallet"          },
  { name: "car",            label: "Car"             },
  { name: "ship",           label: "Ship"            },
  { name: "star",           label: "Star"            },
  { name: "zap",            label: "Zap"             },
];

const INIT_SERVICES = [
  {
    id: "SVC-001", name: "Visa Services",                icon: "plane",
    desc: "Company visas, investor visas, employment visas, family visas and tourist visit visas for UAE residents and businesses.",
    basePrice: "AED 400",   processingTime: "2–15 working days",  status: "active",
  },
  {
    id: "SVC-002", name: "Immigration & Labour",         icon: "users-round",
    desc: "Labour card issuance, MOL approvals, work permit renewals, and immigration formalities with GDRFA and MOHRE.",
    basePrice: "AED 600",   processingTime: "1–7 working days",   status: "active",
  },
  {
    id: "SVC-003", name: "PRO Services",                 icon: "file-signature",
    desc: "Public Relations Officer services — government document handling, clearance, liaison, and monthly retainer packages.",
    basePrice: "AED 150",   processingTime: "Same day – 5 days",  status: "active",
  },
  {
    id: "SVC-004", name: "Trade License Services",       icon: "badge-check",
    desc: "New trade license registration, renewals, amendments, and cancellations with DED, free zones and offshore authorities.",
    basePrice: "AED 1,200", processingTime: "3–14 working days",  status: "active",
  },
  {
    id: "SVC-005", name: "Dubai Dept. Approvals",        icon: "landmark",
    desc: "External approvals from Dubai Municipality, Civil Defence, Dubai Health Authority, KHDA, RTA and other departments.",
    basePrice: "AED 1,500", processingTime: "5–15 working days",  status: "active",
  },
  {
    id: "SVC-006", name: "Business Setup Services",      icon: "briefcase",
    desc: "End-to-end mainland, free zone and offshore company formation including bank account introduction.",
    basePrice: "AED 6,000", processingTime: "7–21 working days",  status: "active",
  },
  {
    id: "SVC-007", name: "Dubai Economic Services",      icon: "building-2",
    desc: "DED registrations, economic substance filings, VAT and corporate tax registration, and commercial compliance.",
    basePrice: "AED 1,800", processingTime: "3–14 working days",  status: "active",
  },
  {
    id: "SVC-008", name: "Certificate Attestation",      icon: "stamp",
    desc: "MOFA attestation, embassy legalisation, apostille and translation & notarisation for personal and corporate documents.",
    basePrice: "AED 350",   processingTime: "1–10 working days",  status: "active",
  },
];

function newSvcId() { return "SVC-" + Date.now().toString(36).toUpperCase(); }

/* ─── Icon Picker ─── */
function IconPicker({ value, onChange }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(8, 1fr)", gap: 8, marginTop: 6 }}>
      {SM_ICON_OPTIONS.map(opt => {
        const active = value === opt.name;
        return (
          <button key={opt.name} type="button" title={opt.label}
            onClick={() => onChange(opt.name)}
            style={{
              display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
              gap: 4, padding: "10px 6px", borderRadius: 8, cursor: "pointer",
              border: active ? "2px solid var(--brand-burgundy)" : "1px solid var(--border-subtle)",
              background: active ? "var(--plum-50)" : "#fff",
              color: active ? "var(--brand-burgundy)" : "var(--fg-3)",
            }}>
            <Icon name={opt.name} size={18} />
            <span style={{ fontSize: 9, fontFamily: "var(--font-mono)", lineHeight: 1, textAlign: "center", color: "inherit" }}>{opt.label}</span>
          </button>
        );
      })}
    </div>
  );
}

/* ─── Add / Edit Modal ─── */
function ServiceFormModal({ svc, onClose, onSave }) {
  const isEdit = !!svc;
  const blank  = { name: "", icon: "briefcase", desc: "", basePrice: "", processingTime: "", status: "active" };
  const [form, setForm]     = React.useState(isEdit ? { ...svc } : blank);
  const [errors, setErrors] = React.useState({});

  const set = k => e => setForm(f => ({ ...f, [k]: e.target.value }));

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Service name is required";
    return e;
  };

  const handleSave = () => {
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    onSave({ ...form });
  };

  const errStyle = { color: "var(--danger-500)", fontSize: 11.5, marginTop: 3 };

  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="modal" role="dialog" aria-modal="true" style={{ maxWidth: 580 }}>
        <div className="modal-head">
          <div>
            <div className="eyebrow" style={{ marginBottom: 4 }}>Service Master</div>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{isEdit ? "Edit service" : "Add service"}</h2>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="modal-body">
          {/* Name */}
          <div className="field">
            <label>Service name <span style={{ color: "var(--danger-500)" }}>*</span></label>
            <input value={form.name} onChange={set("name")} placeholder="e.g. Visa Services" />
            {errors.name && <div style={errStyle}>{errors.name}</div>}
          </div>

          {/* Icon picker */}
          <div className="field">
            <label>Icon</label>
            <IconPicker value={form.icon} onChange={v => setForm(f => ({ ...f, icon: v }))} />
          </div>

          {/* Description */}
          <div className="field">
            <label>Description</label>
            <textarea rows={3} value={form.desc} onChange={set("desc")}
              placeholder="Brief description shown in the service catalogue…"
              style={{ resize: "vertical" }} />
          </div>

          {/* Price + Time */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div className="field">
              <label>Base price (from)</label>
              <input value={form.basePrice} onChange={set("basePrice")} placeholder="e.g. AED 1,200" />
            </div>
            <div className="field">
              <label>Processing time</label>
              <input value={form.processingTime} onChange={set("processingTime")} placeholder="e.g. 5–10 working days" />
            </div>
          </div>

          {/* Status */}
          <div className="field">
            <label>Status</label>
            <div style={{ display: "flex", gap: 8, marginTop: 2 }}>
              {["active", "inactive"].map(s => (
                <button key={s} type="button" onClick={() => setForm(f => ({ ...f, status: s }))}
                  style={{
                    padding: "7px 20px", borderRadius: 6, cursor: "pointer",
                    fontFamily: "inherit", fontSize: 13, fontWeight: 500,
                    border: form.status === s ? "2px solid var(--brand-burgundy)" : "1px solid var(--border-subtle)",
                    background: form.status === s ? "var(--plum-50)" : "#fff",
                    color:      form.status === s ? "var(--brand-burgundy)" : "var(--fg-3)",
                  }}>
                  {s === "active" ? "Active" : "Inactive"}
                </button>
              ))}
            </div>
          </div>

          <div className="modal-footer">
            <Button variant="secondary" type="button" onClick={onClose}>Cancel</Button>
            <Button icon="check" onClick={handleSave}>{isEdit ? "Save changes" : "Add service"}</Button>
          </div>
        </div>
      </div>
    </>
  );
}

/* ─── Delete Confirmation ─── */
function SvcDeleteConfirmModal({ svc, onClose, onConfirm }) {
  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="modal" role="dialog" style={{ maxWidth: 420 }}>
        <div className="modal-head">
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>Delete service?</h2>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="modal-body">
          <div style={{ padding: "12px 14px", background: "var(--ink-50)", borderRadius: 8, marginBottom: 18, display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--plum-50)", color: "var(--brand-burgundy)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <Icon name={svc.icon} size={18} />
            </div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{svc.name}</div>
              <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 1 }}>{svc.id}</div>
            </div>
          </div>
          <p style={{ fontSize: 13.5, color: "var(--fg-2)", margin: "0 0 4px" }}>
            This service will be permanently deleted from the master list.
          </p>
          <p style={{ fontSize: 13, color: "var(--fg-3)", margin: 0 }}>
            Sub-services and stages linked to this service will become orphaned. Active engagements will not be affected.
          </p>
          <div className="modal-footer" style={{ marginTop: 20 }}>
            <Button variant="secondary" onClick={onClose}>Cancel</Button>
            <button className="btn" onClick={onConfirm}
              style={{ background: "var(--danger-500)", color: "#fff", border: "1px solid var(--danger-500)", display: "flex", alignItems: "center", gap: 6, padding: "8px 16px", borderRadius: 6, cursor: "pointer", fontFamily: "inherit", fontSize: 13.5, fontWeight: 600 }}>
              <Icon name="trash-2" size={14} />Delete service
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

/* ─── Main Page ─── */
function ServiceMasterPage() {
  const [services, setServices] = React.useState([]);
  const [loading,  setLoading]  = React.useState(true);
  const [search,   setSearch]   = React.useState("");
  const [status,   setStatus]   = React.useState("all");
  const [modal,    setModal]    = React.useState(null);
  const [delSvc,   setDelSvc]   = React.useState(null);

  React.useEffect(() => {
    api.get("/services")
      .then(res => setServices((res.data || []).map(api.map.service)))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const q = search.toLowerCase();
  const filtered = services.filter(s => {
    if (status !== "all" && s.status !== status) return false;
    if (q && !s.name.toLowerCase().includes(q) && !(s.desc || "").toLowerCase().includes(q)) return false;
    return true;
  });

  const handleSave = async (svc) => {
    try {
      if (svc._id) {
        const res = await api.put("/services/" + svc._id, { name: svc.name, icon: svc.icon, desc: svc.desc, basePrice: svc.basePrice, processingTime: svc.processingTime, status: svc.status });
        const updated = api.map.service(res.data);
        setServices(prev => prev.map(s => s._id === updated._id ? updated : s));
      } else {
        const res = await api.post("/services", { name: svc.name, icon: svc.icon, desc: svc.desc, basePrice: svc.basePrice, processingTime: svc.processingTime, status: svc.status });
        setServices(prev => [...prev, api.map.service(res.data)]);
      }
      setModal(null);
    } catch (err) {
      alert(err.message);
    }
  };

  const handleDelete = async () => {
    try {
      await api.delete("/services/" + delSvc._id);
      setServices(prev => prev.filter(s => s._id !== delSvc._id));
      setDelSvc(null);
    } catch (err) {
      alert(err.message);
    }
  };

  const total    = services.length;
  const active   = services.filter(s => s.status === "active").length;
  const inactive = total - active;

  const tabBtn = (id, label) => (
    <button key={id} onClick={() => setStatus(id)}
      style={{
        padding: "6px 18px", borderRadius: 6, border: "1px solid", cursor: "pointer",
        fontFamily: "inherit", fontSize: 13, fontWeight: status === id ? 600 : 400,
        background:  status === id ? "var(--plum-900)" : "#fff",
        color:       status === id ? "#fff"            : "var(--fg-2)",
        borderColor: status === id ? "var(--plum-900)" : "var(--border-strong)",
      }}>
      {label}
    </button>
  );

  return (
    <>
    <div className="page">
      {/* Header */}
      <div className="page-head">
        <div>
          <div className="eyebrow">Setup · Services</div>
          <h1 className="page-title">Service master</h1>
          <div className="page-sub">{total} service{total !== 1 ? "s" : ""} &nbsp;·&nbsp; {active} active &nbsp;·&nbsp; {inactive} inactive</div>
        </div>
        <Button icon="plus" onClick={() => setModal("add")}>Add service</Button>
      </div>

      {/* KPIs */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 28 }}>
        {[
          { lbl: "Total services", val: total    },
          { lbl: "Active",         val: active   },
          { lbl: "Inactive",       val: inactive  },
          { lbl: "Service types",  val: total    },
        ].map(k => (
          <div key={k.lbl} className="kpi">
            <div className="lbl">{k.lbl}</div>
            <div className="val">{k.val}</div>
          </div>
        ))}
      </div>

      {/* Toolbar */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18, flexWrap: "wrap" }}>
        {/* Status tabs */}
        <div style={{ display: "flex", gap: 6 }}>
          {tabBtn("all",      `All (${total})`)}
          {tabBtn("active",   `Active (${active})`)}
          {tabBtn("inactive", `Inactive (${inactive})`)}
        </div>

        {/* Search */}
        <div style={{ position: "relative", flex: 1, maxWidth: 360, marginLeft: "auto" }}>
          <span style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--fg-3)", pointerEvents: "none", display: "flex" }}>
            <Icon name="search" size={15} />
          </span>
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Search services…"
            style={{ width: "100%", padding: "7px 12px 7px 34px", border: "1px solid var(--border-subtle)", borderRadius: 8, fontFamily: "inherit", fontSize: 13, outline: "none", background: "#fff" }} />
        </div>
        {search && (
          <button onClick={() => setSearch("")}
            style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 12.5, color: "var(--fg-3)", background: "transparent", border: 0, cursor: "pointer", fontFamily: "inherit" }}>
            <Icon name="x" size={12} />Clear
          </button>
        )}
        <div style={{ fontSize: 13, color: "var(--fg-3)" }}>{filtered.length} result{filtered.length !== 1 ? "s" : ""}</div>
      </div>

      {/* Table */}
      {filtered.length === 0 ? (
        <div className="card" style={{ textAlign: "center", padding: "64px 20px", color: "var(--fg-3)" }}>
          <Icon name="list-checks" size={32} />
          <div style={{ marginTop: 12, fontSize: 15, fontWeight: 500, color: "var(--fg-2)" }}>No services found</div>
          <div style={{ fontSize: 13, marginTop: 4 }}>Adjust your filter or search, or add a new service.</div>
          <button className="btn btn-primary" style={{ marginTop: 18, display: "inline-flex", alignItems: "center", gap: 6 }}
            onClick={() => setModal("add")}>
            <Icon name="plus" size={14} />Add service
          </button>
        </div>
      ) : (
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead>
              <tr style={{ background: "var(--ink-50)", borderBottom: "1px solid var(--border-subtle)" }}>
                {["Service", "Description", "Base price", "Processing time", "Status", ""].map((h, i) => (
                  <th key={i} style={{
                    padding: "10px 20px",
                    textAlign: i === 5 ? "right" : "left",
                    fontSize: 10.5, fontWeight: 700, color: "var(--fg-3)",
                    textTransform: "uppercase", letterSpacing: "0.1em",
                    width: [null, null, 130, 170, 90, 120][i],
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map((svc, i) => (
                <tr key={svc.id} style={{ borderTop: i > 0 ? "1px solid var(--border-subtle)" : undefined }}>
                  {/* Service name + icon */}
                  <td style={{ padding: "14px 20px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                      <div style={{
                        width: 38, height: 38, borderRadius: 9, flexShrink: 0,
                        background: svc.status === "active" ? "var(--plum-50)" : "var(--ink-100)",
                        color: svc.status === "active" ? "var(--brand-burgundy)" : "var(--fg-4)",
                        display: "flex", alignItems: "center", justifyContent: "center",
                      }}>
                        <Icon name={svc.icon} size={18} />
                      </div>
                      <div>
                        <div style={{ fontSize: 14, fontWeight: 600 }}>{svc.name}</div>
                        <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--fg-4)", marginTop: 1 }}>{svc.id}</div>
                      </div>
                    </div>
                  </td>
                  {/* Description */}
                  <td style={{ padding: "14px 20px" }}>
                    <div style={{ fontSize: 12.5, color: "var(--fg-3)", lineHeight: 1.45, maxWidth: 320 }}>
                      {svc.desc || <span style={{ color: "var(--fg-4)" }}>No description</span>}
                    </div>
                  </td>
                  {/* Base price */}
                  <td style={{ padding: "14px 20px" }}>
                    <div style={{ fontSize: 13, fontWeight: 600, fontFamily: "var(--font-mono)" }}>
                      {svc.basePrice
                        ? <><span style={{ fontSize: 10, fontWeight: 400, color: "var(--fg-3)", fontFamily: "inherit" }}>from </span>{svc.basePrice}</>
                        : <span style={{ color: "var(--fg-4)", fontFamily: "inherit", fontWeight: 400 }}>—</span>}
                    </div>
                  </td>
                  {/* Processing time */}
                  <td style={{ padding: "14px 20px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: "var(--fg-2)" }}>
                      {svc.processingTime
                        ? <><Icon name="clock" size={13} />{svc.processingTime}</>
                        : <span style={{ color: "var(--fg-4)" }}>—</span>}
                    </div>
                  </td>
                  {/* Status */}
                  <td style={{ padding: "14px 20px" }}>
                    <Chip kind={svc.status === "active" ? "success" : "default"}>
                      {svc.status === "active" ? "Active" : "Inactive"}
                    </Chip>
                  </td>
                  {/* Actions */}
                  <td style={{ padding: "14px 20px", textAlign: "right" }}>
                    <div style={{ display: "flex", gap: 4, justifyContent: "flex-end" }}>
                      <button className="btn btn-ghost btn-sm" onClick={() => setModal(svc)}>
                        <Icon name="pencil" size={13} />Edit
                      </button>
                      <button className="btn btn-ghost btn-sm" title="Delete"
                        style={{ color: "var(--danger-500)" }}
                        onClick={() => setDelSvc(svc)}>
                        <Icon name="trash-2" size={13} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>

    {/* Add / Edit modal */}
    {modal !== null && (
      <ServiceFormModal
        svc={modal === "add" ? null : modal}
        onClose={() => setModal(null)}
        onSave={handleSave}
      />
    )}

    {/* Delete confirmation */}
    {delSvc && (
      <SvcDeleteConfirmModal
        svc={delSvc}
        onClose={() => setDelSvc(null)}
        onConfirm={handleDelete}
      />
    )}
    </>
  );
}

Object.assign(window, { ServiceMasterPage });
