/* ProHippo — reusable modal, add/edit form, empty state */

function Modal({ title, sub, onClose, children, width = 560 }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-card" style={{ maxWidth: width }} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div className="modal-title">{title}</div>
            {sub && <div className="card-sub" style={{ marginTop: 2 }}>{sub}</div>}
          </div>
          <button className="icon-btn" style={{ width: 34, height: 34 }} onClick={onClose}>
            <Icon name="x" size={16} />
          </button>
        </div>
        <div className="modal-body">{children}</div>
      </div>
    </div>
  );
}

/* Generic add/edit form driven by a field schema.
 * fields: [{ k, label, type:"text"|"number"|"select"|"date"|"textarea", options?, required?, full?, mono?, placeholder? }]
 */
function FormModal({ title, sub, fields, initial = {}, onClose, onSubmit, submitLabel = "Save" }) {
  const blank = {};
  fields.forEach(f => { blank[f.k] = initial[f.k] != null ? initial[f.k] : (f.type === "number" ? "" : (f.options ? f.options[0] : "")); });
  const [v, setV] = React.useState(blank);
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState("");
  const set = (k, val) => setV(s => ({ ...s, [k]: val }));

  const submit = async () => {
    for (const f of fields) {
      if (f.required && !String(v[f.k] || "").trim()) {
        setError("Please fill in: " + f.label);
        return;
      }
    }
    setSaving(true); setError("");
    const payload = { ...v };
    fields.forEach(f => { if (f.type === "number") payload[f.k] = Number(payload[f.k]) || 0; });
    try {
      await onSubmit(payload);
      onClose();
    } catch (e) {
      console.error("Form save error:", e);
      setError("Could not save: " + (e.message || "unknown error"));
      setSaving(false);
    }
  };

  return (
    <Modal title={title} sub={sub} onClose={onClose}>
      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        {fields.map(f => (
          <div key={f.k} className="field" style={{ gridColumn: f.full ? "span 2" : "auto" }}>
            <label>{f.label}{f.required && <span style={{ color: "var(--p-danger)" }}> *</span>}</label>
            {f.type === "select" ? (
              <select value={v[f.k]} onChange={e => set(f.k, e.target.value)}>
                {f.options.map(o => <option key={o} value={o}>{o}</option>)}
              </select>
            ) : f.type === "textarea" ? (
              <textarea value={v[f.k]} placeholder={f.placeholder || ""} rows={3} onChange={e => set(f.k, e.target.value)} />
            ) : (
              <input
                type={f.type === "number" ? "number" : f.type === "date" ? "date" : "text"}
                value={v[f.k]}
                placeholder={f.placeholder || ""}
                onChange={e => set(f.k, e.target.value)}
                style={{ fontFamily: f.mono ? "ui-monospace, monospace" : "inherit" }}
              />
            )}
          </div>
        ))}
      </div>
      {error && <div className="auth-error-box" style={{ marginTop: 14 }}>{error}</div>}
      <div className="row" style={{ gap: 8, marginTop: 18 }}>
        <button className="btn btn-secondary" style={{ flex: 1, justifyContent: "center" }} onClick={onClose} disabled={saving}>Cancel</button>
        <button className="btn btn-primary" style={{ flex: 2, justifyContent: "center" }} onClick={submit} disabled={saving}>
          {saving ? "Saving…" : <><Icon name="check" size={14} />{submitLabel}</>}
        </button>
      </div>
    </Modal>
  );
}

function EmptyState({ icon = "folder", title, sub, actionLabel, onAction, onSeed }) {
  return (
    <div className="card" style={{ padding: "56px 32px", textAlign: "center" }}>
      <div style={{ width: 64, height: 64, borderRadius: 18, background: "var(--p-lavender-2)", color: "var(--p-primary-2)", display: "grid", placeItems: "center", margin: "0 auto 16px" }}>
        <Icon name={icon} size={28} />
      </div>
      <div className="card-title" style={{ fontSize: 17 }}>{title}</div>
      {sub && <div className="card-sub" style={{ marginTop: 6, maxWidth: 420, marginLeft: "auto", marginRight: "auto" }}>{sub}</div>}
      <div className="row" style={{ gap: 10, marginTop: 20, justifyContent: "center" }}>
        {onAction && <button className="btn btn-primary" onClick={onAction}><Icon name="plus" size={14} />{actionLabel}</button>}
        {onSeed && <button className="btn btn-secondary" onClick={onSeed}><Icon name="sparkle" size={14} />Load sample data</button>}
      </div>
    </div>
  );
}

/* ── Field schemas for each entity ── */
const STATUS_OPTS    = ["Individual", "Company", "Firm", "LLP", "HUF", "Trust", "AOP/BOI"];
const AUTHORITY_OPTS = ["Scrutiny", "CIT(A)", "ITAT", "Penalty", "Rectification", "High Court"];
const MODE_OPTS      = ["Physical", "e-Proceeding", "Video Conference"];
const HEARING_STATUS = ["Upcoming", "Adjourned", "Decided"];
const PRIORITY_OPTS  = ["high", "medium", "low"];
const NOTICE_STATUS  = ["AI Parsed", "Reply Drafted", "Submitted"];
const INVOICE_STATUS = ["Outstanding", "Partial", "Paid", "Overdue"];
const MATTER_STATUS  = ["Active", "Pending", "Submitted", "Decided"];

const ASSESSEE_FIELDS = [
  { k: "name",   label: "Name",            type: "text",   required: true, full: true },
  { k: "pan",    label: "PAN",             type: "text",   mono: true, placeholder: "ABCPS1234F" },
  { k: "status", label: "Status",          type: "select", options: STATUS_OPTS },
  { k: "group",  label: "Group / Family",  type: "text",   placeholder: "— if none" },
  { k: "staff",  label: "Assigned staff",  type: "text" },
  { k: "mobile", label: "Mobile",          type: "text",   placeholder: "+91 …" },
  { k: "email",  label: "Email",           type: "text", full: true },
];

const HEARING_FIELDS = [
  { k: "assessee", label: "Assessee",       type: "text",   required: true, full: true },
  { k: "pan",      label: "PAN",            type: "text",   mono: true },
  { k: "ay",       label: "Assessment Year",type: "text",   placeholder: "2021-22" },
  { k: "authority",label: "Authority",      type: "select", options: AUTHORITY_OPTS },
  { k: "bench",    label: "Bench / Officer",type: "text" },
  { k: "section",  label: "Section",        type: "text",   placeholder: "— if none" },
  { k: "ita",      label: "ITA / Appeal No.",type: "text",  placeholder: "— if none" },
  { k: "date",     label: "Hearing date",   type: "date",   required: true },
  { k: "time",     label: "Time",           type: "text",   placeholder: "11:30" },
  { k: "mode",     label: "Mode",           type: "select", options: MODE_OPTS },
  { k: "status",   label: "Status",         type: "select", options: HEARING_STATUS },
  { k: "priority", label: "Priority",       type: "select", options: PRIORITY_OPTS },
  { k: "staff",    label: "Staff",          type: "text" },
];

const NOTICE_FIELDS = [
  { k: "assessee", label: "Assessee",       type: "text",   required: true, full: true },
  { k: "pan",      label: "PAN",            type: "text",   mono: true },
  { k: "ay",       label: "Assessment Year",type: "text" },
  { k: "section",  label: "Section",        type: "text",   placeholder: "142(1)" },
  { k: "authority",label: "Authority",      type: "select", options: AUTHORITY_OPTS },
  { k: "date",     label: "Notice date",    type: "date",   required: true },
  { k: "din",      label: "DIN",            type: "text",   mono: true, full: true },
  { k: "status",   label: "Status",         type: "select", options: NOTICE_STATUS },
];

const INVOICE_FIELDS = [
  { k: "number",   label: "Invoice No.",    type: "text",   required: true, mono: true, placeholder: "PH/26-27/0125" },
  { k: "assessee", label: "Assessee",       type: "text",   required: true },
  { k: "service",  label: "Service",        type: "text",   full: true },
  { k: "ay",       label: "Assessment Year",type: "text" },
  { k: "amount",   label: "Amount (₹)",     type: "number", required: true },
  { k: "date",     label: "Issued date",    type: "date" },
  { k: "due",      label: "Due date",       type: "date" },
  { k: "status",   label: "Status",         type: "select", options: INVOICE_STATUS },
];

const MATTER_FIELDS = [
  { k: "type",     label: "Type",           type: "select", options: AUTHORITY_OPTS },
  { k: "assessee", label: "Assessee",       type: "text",   required: true },
  { k: "ay",       label: "Assessment Year",type: "text" },
  { k: "section",  label: "Section",        type: "text",   placeholder: "— if none" },
  { k: "ita",      label: "ITA / Appeal No.",type: "text",  placeholder: "— if none", full: true },
  { k: "bench",    label: "Bench / Officer",type: "text" },
  { k: "status",   label: "Status",         type: "select", options: MATTER_STATUS },
  { k: "priority", label: "Priority",       type: "select", options: PRIORITY_OPTS },
  { k: "staff",    label: "Staff",          type: "text" },
];

Object.assign(window, {
  Modal, FormModal, EmptyState,
  ASSESSEE_FIELDS, HEARING_FIELDS, NOTICE_FIELDS, INVOICE_FIELDS, MATTER_FIELDS,
});
