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

const CATALOGUE_SEED = [
  {
    id: "SVC-001", name: "Visa Services", icon: "plane", status: "active",
    description: "Company visas, investor visas, employment visas, and family visas for UAE residents.",
    subServices: ["Company visa", "Investor visa", "Employment visa", "Visit visa", "Transit visa"],
    basePrice: "AED 1,200", processingTime: "5–10 working days",
    activeEngagements: 38, completedThisYear: 112,
  },
  {
    id: "SVC-002", name: "Immigration & Labour Services", icon: "users-round", status: "active",
    description: "Labour card issuance, MOL approvals, work permit renewals, and immigration formalities.",
    subServices: ["Labour card issuance", "Work permit renewal", "MOL approval", "Immigration clearance"],
    basePrice: "AED 900", processingTime: "3–7 working days",
    activeEngagements: 12, completedThisYear: 44,
  },
  {
    id: "SVC-003", name: "PRO Services", icon: "file-signature", status: "active",
    description: "Public Relations Officer document handling — government liaison, document clearance, and courier.",
    subServices: ["Document clearance", "Government liaison", "Monthly PRO retainer", "Courier & typing"],
    basePrice: "AED 800", processingTime: "1–3 working days",
    activeEngagements: 24, completedThisYear: 98,
  },
  {
    id: "SVC-004", name: "Trade License Services", icon: "badge-check", status: "active",
    description: "New trade license registration, renewals, amendments, and cancellations with DED and free zones.",
    subServices: ["New license registration", "License renewal", "License amendment", "License cancellation"],
    basePrice: "AED 2,500", processingTime: "7–14 working days",
    activeEngagements: 17, completedThisYear: 63,
  },
  {
    id: "SVC-005", name: "Dubai Department Approvals", icon: "landmark", status: "active",
    description: "External approvals from Dubai Municipality, Civil Defence, Health Authority, and other departments.",
    subServices: ["Dubai Municipality", "Civil Defence approval", "DHA approval", "KHDA approval"],
    basePrice: "AED 1,500", processingTime: "5–15 working days",
    activeEngagements: 9, completedThisYear: 27,
  },
  {
    id: "SVC-006", name: "Business Setup Services", icon: "briefcase", status: "active",
    description: "End-to-end mainland and free zone company formation, including bank account introduction.",
    subServices: ["Mainland LLC setup", "Free zone setup", "Branch registration", "Bank account intro"],
    basePrice: "AED 5,000", processingTime: "10–21 working days",
    activeEngagements: 21, completedThisYear: 55,
  },
  {
    id: "SVC-007", name: "Dubai Economic Services", icon: "building-2", status: "active",
    description: "DED registrations, economic substance filings, and compliance with UAE commercial regulations.",
    subServices: ["DED registration", "Economic substance", "Commercial compliance", "Tax registration"],
    basePrice: "AED 1,800", processingTime: "5–10 working days",
    activeEngagements: 6, completedThisYear: 18,
  },
  {
    id: "SVC-008", name: "Certificate Attestation Services", icon: "stamp", status: "active",
    description: "MOFA attestation, embassy legalisation, and apostille for educational and personal documents.",
    subServices: ["MOFA attestation", "Embassy legalisation", "Apostille", "Translation & notarisation"],
    basePrice: "AED 600", processingTime: "3–7 working days",
    activeEngagements: 15, completedThisYear: 74,
  },
];

function ServiceCard({ svc, onEdit }) {
  const [expanded, setExpanded] = React.useState(false);
  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div style={{ padding: "18px 20px", display: "flex", gap: 16, alignItems: "flex-start" }}>
        <div style={{ width: 44, height: 44, borderRadius: 10, background: "var(--plum-50)", color: "var(--brand-burgundy)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
          <Icon name={svc.icon} size={22} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
            <div style={{ fontWeight: 600, fontSize: 14.5 }}>{svc.name}</div>
            <Chip kind="success">Active</Chip>
          </div>
          <div style={{ fontSize: 13, color: "var(--fg-3)", lineHeight: 1.5, marginBottom: 12 }}>{svc.description}</div>

          <div style={{ display: "flex", gap: 24, flexWrap: "wrap" }}>
            <div>
              <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--fg-3)", fontWeight: 600 }}>Base price</div>
              <div style={{ fontSize: 14, fontWeight: 600, fontFamily: "var(--font-mono)", marginTop: 2 }}>{svc.basePrice}</div>
            </div>
            <div>
              <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--fg-3)", fontWeight: 600 }}>Processing time</div>
              <div style={{ fontSize: 13.5, marginTop: 2 }}>{svc.processingTime}</div>
            </div>
            <div>
              <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--fg-3)", fontWeight: 600 }}>Active now</div>
              <div style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>{svc.activeEngagements}</div>
            </div>
            <div>
              <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--fg-3)", fontWeight: 600 }}>Completed 2025–26</div>
              <div style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>{svc.completedThisYear}</div>
            </div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 6, flexShrink: 0 }}>
          <button className="btn btn-ghost btn-sm" onClick={() => setExpanded(x => !x)}>
            <Icon name={expanded ? "chevron-up" : "chevron-down"} size={14} />
            {expanded ? "Hide" : "Sub-services"}
          </button>
          <button className="btn btn-secondary btn-sm" onClick={() => onEdit(svc)}>
            <Icon name="pencil" size={13} /> Edit
          </button>
        </div>
      </div>

      {expanded && (
        <div style={{ borderTop: "1px solid var(--border-subtle)", padding: "14px 20px 18px", background: "var(--ink-50)" }}>
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--fg-3)", fontWeight: 600, marginBottom: 10 }}>Sub-services</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {svc.subServices.map(s => (
              <div key={s} style={{ display: "flex", alignItems: "center", gap: 8, padding: "7px 14px", background: "#fff", border: "1px solid var(--border-subtle)", borderRadius: 6, fontSize: 13 }}>
                <Icon name="check" size={13} />
                {s}
              </div>
            ))}
            <button style={{ display: "flex", alignItems: "center", gap: 6, padding: "7px 14px", background: "transparent", border: "1px dashed var(--border-strong)", borderRadius: 6, fontSize: 13, color: "var(--brand-burgundy)", cursor: "pointer", fontFamily: "inherit" }}>
              <Icon name="plus" size={13} /> Add sub-service
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function CatalogueServiceModal({ svc, onClose, onSave }) {
  const isEdit = !!svc;
  const blank  = { name: "", basePrice: "", processingTime: "", description: "" };
  const [form, setForm] = React.useState(isEdit ? { name: svc.name, basePrice: svc.basePrice, processingTime: svc.processingTime, description: svc.description } : blank);
  const [error, setError] = React.useState("");
  const set = k => e => setForm(f => ({ ...f, [k]: e.target.value }));

  const handleSave = () => {
    if (!form.name.trim()) { setError("Service name is required."); return; }
    onSave({ ...(isEdit ? svc : { id: "SVC-" + Date.now().toString(36).toUpperCase(), icon: "briefcase", status: "active", subServices: [], activeEngagements: 0, completedThisYear: 0 }), ...form });
  };

  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="modal" role="dialog" aria-modal="true">
        <div className="modal-head">
          <div>
            <div className="eyebrow" style={{ marginBottom: 4 }}>Service catalogue</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">
          <div className="field">
            <label>Service name <span style={{ color: "var(--danger-500)" }}>*</span></label>
            <input value={form.name} onChange={e => { set("name")(e); setError(""); }} placeholder="e.g. Visa Services" />
            {error && <div style={{ color: "var(--danger-500)", fontSize: 11.5, marginTop: 3 }}>{error}</div>}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div className="field">
              <label>Base price</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>
          <div className="field">
            <label>Description</label>
            <textarea rows={3} value={form.description} onChange={set("description")} style={{ resize: "vertical" }} placeholder="Brief description of this service…" />
          </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>
    </>
  );
}

function ServiceCataloguePage() {
  const [services, setServices] = React.useState(CATALOGUE_SEED);
  const [editSvc,  setEditSvc]  = React.useState(null);
  const [showAdd,  setShowAdd]  = React.useState(false);

  const totalActive    = services.reduce((s, v) => s + v.activeEngagements, 0);
  const totalCompleted = services.reduce((s, v) => s + v.completedThisYear, 0);

  const handleSave = updated => {
    setServices(prev => prev.find(s => s.id === updated.id) ? prev.map(s => s.id === updated.id ? updated : s) : [...prev, updated]);
    setEditSvc(null);
    setShowAdd(false);
  };

  return (
    <>
    <div className="page">
      <div className="page-head">
        <div>
          <div className="eyebrow">Setup</div>
          <h1 className="page-title">Service catalogue</h1>
          <div className="page-sub">{services.length} services &nbsp;·&nbsp; {totalActive} active engagements &nbsp;·&nbsp; {totalCompleted} completed this year</div>
        </div>
        <Button icon="plus" onClick={() => setShowAdd(true)}>Add service</Button>
      </div>

      {/* Summary grid */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>
        {services.slice(0, 4).map(s => (
          <div key={s.id} className="kpi">
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 2 }}>
              <Icon name={s.icon} size={14} />
              <div className="lbl" style={{ fontSize: 10 }}>{s.name}</div>
            </div>
            <div className="val" style={{ fontSize: 22 }}>{s.activeEngagements} <span style={{ fontSize: 12, fontWeight: 400, color: "var(--fg-3)" }}>active</span></div>
          </div>
        ))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 28 }}>
        {services.slice(4).map(s => (
          <div key={s.id} className="kpi">
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 2 }}>
              <Icon name={s.icon} size={14} />
              <div className="lbl" style={{ fontSize: 10 }}>{s.name}</div>
            </div>
            <div className="val" style={{ fontSize: 22 }}>{s.activeEngagements} <span style={{ fontSize: 12, fontWeight: 400, color: "var(--fg-3)" }}>active</span></div>
          </div>
        ))}
      </div>

      {/* Service cards */}
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {services.map(svc => (
          <ServiceCard key={svc.id} svc={svc} onEdit={setEditSvc} />
        ))}
      </div>
    </div>

    {editSvc  && <CatalogueServiceModal svc={editSvc} onClose={() => setEditSvc(null)} onSave={handleSave} />}
    {showAdd  && <CatalogueServiceModal svc={null}    onClose={() => setShowAdd(false)} onSave={handleSave} />}
    </>
  );
}

Object.assign(window, { ServiceCataloguePage });
