// Organization Chart master setup

const OrgChartPage = ({ divisions, setDivisions, departments, setDepartments, positions, setPositions, users, auditLog, setAuditLog, tenant, canEdit }) => {
  const [view, setView] = useState("tree"); // tree | chart
  const [selected, setSelected] = useState({ type:"div", id: divisions[0]?.id });
  const [deleteFor, setDeleteFor] = useState(null);
  const [adding, setAdding] = useState(null);
  const toast = useToast();

  const audit = (a, r, who="ธนพร อัศวิน") => setAuditLog(p => [{ id:"a"+Math.random().toString(36).slice(2,7), scope:"tenant", tenant_id:tenant.id, action:a, reason:r, performed_by:who, at: nowStamp() }, ...p]);

  const handleDelete = (type, id, reason) => {
    if (type==="div") { setDivisions(p=>p.filter(x=>x.id!==id)); audit("delete", `ลบ Division — ${reason}`); }
    if (type==="dept") { setDepartments(p=>p.filter(x=>x.id!==id)); audit("delete", `ลบ Department — ${reason}`); }
    if (type==="pos") { setPositions(p=>p.filter(x=>x.id!==id)); audit("delete", `ลบ Position — ${reason}`); }
    toast({kind:"success", msg:"ลบรายการสำเร็จ"});
    setDeleteFor(null);
  };

  const sel = selected.type==="div" ? divisions.find(x=>x.id===selected.id)
    : selected.type==="dept" ? departments.find(x=>x.id===selected.id)
    : selected.type==="pos" ? positions.find(x=>x.id===selected.id) : null;

  return (
    <div className="p-6">
      <PageHeader title="Organization Chart" subtitle="โครงสร้าง Division → Department → Position ของบริษัท"
        right={<>
          <Segmented value={view} onChange={setView} options={[{value:"tree", label:"Tree"},{value:"chart", label:"Chart"}]}/>
          {canEdit ? <Button icon="plus" onClick={()=>setAdding({type:"div"})}>เพิ่ม Division</Button> : <Badge color="slate" icon="eye">อ่านอย่างเดียว</Badge>}
        </>}/>

      {!canEdit && (
        <div className="mb-4 px-4 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-700 text-[12.5px] flex items-center gap-2.5">
          <Icon name="shield" size={14} className="text-slate-500"/>
          <span>คุณกำลังดู Organization Chart แบบ <strong>อ่านอย่างเดียว</strong> · ติดต่อ Company Admin เพื่อขอสิทธิ์แก้ไข</span>
        </div>
      )}

      {view === "tree" ? (
        <div className="grid grid-cols-12 gap-4">
          {/* Tree */}
          <div className="col-span-12 lg:col-span-4 bg-white rounded-2xl border border-ink-100 overflow-hidden">
            <div className="px-3 py-3 border-b border-ink-100 flex items-center gap-2">
              <Icon name="network" size={14} className="text-ink-500"/>
              <div className="text-[13px] font-semibold text-ink-900">Organization Tree</div>
              <div className="ml-auto text-[11px] text-ink-500">{divisions.length} · {departments.length} · {positions.length}</div>
            </div>
            <div className="max-h-[640px] overflow-y-auto thin-scroll p-1.5">
              {divisions.map(div => {
                const deps = departments.filter(d=>d.division_id===div.id);
                return (
                  <TreeNode key={div.id} label={div.name} icon="network" tone="indigo" defaultOpen
                    selected={selected.type==="div" && selected.id===div.id}
                    onClick={()=>setSelected({type:"div", id:div.id})}
                    actions={canEdit ? <TreeActions onAdd={()=>setAdding({type:"dept", parent:div.id})} onDelete={()=>setDeleteFor({type:"div", id:div.id, name:div.name})}/> : null}>
                    {deps.map(dp => {
                      const pps = positions.filter(p=>p.department_id===dp.id);
                      return (
                        <TreeNode key={dp.id} label={dp.name} icon="building" tone="violet"
                          selected={selected.type==="dept" && selected.id===dp.id}
                          onClick={()=>setSelected({type:"dept", id:dp.id})}
                          actions={canEdit ? <TreeActions onAdd={()=>setAdding({type:"pos", parent:dp.id, div:div.id})} onDelete={()=>setDeleteFor({type:"dept", id:dp.id, name:dp.name})}/> : null}>
                          {pps.map(p => {
                            const u = users.find(u=>u.positions.includes(p.id));
                            return (
                              <div key={p.id} className={`group flex items-center gap-2 px-2 py-1.5 rounded-md transition ml-1 ${selected.type==="pos" && selected.id===p.id?"bg-brand-50":"hover:bg-ink-50"}`}>
                                <span className="w-1.5 h-1.5 rounded-full bg-ink-300 ml-1.5"/>
                                <button onClick={()=>setSelected({type:"pos", id:p.id})} className="flex-1 text-left min-w-0">
                                  <div className={`text-[12px] truncate ${selected.type==="pos" && selected.id===p.id?"text-brand-700 font-semibold":"text-ink-800"}`}>{p.name}</div>
                                  <div className="text-[10px] text-ink-500 truncate font-mono">{p.level}{u ? ` · ${u.full_name}` : <span className="text-amber-600"> · ยังไม่มีผู้รับผิดชอบ</span>}</div>
                                </button>
                                {canEdit && <button onClick={()=>setDeleteFor({type:"pos", id:p.id, name:p.name})} className="opacity-0 group-hover:opacity-100 p-1 text-rose-500 hover:bg-rose-50 rounded"><Icon name="trash" size={11}/></button>}
                              </div>
                            );
                          })}
                        </TreeNode>
                      );
                    })}
                  </TreeNode>
                );
              })}
            </div>
          </div>

          {/* Detail */}
          <div className="col-span-12 lg:col-span-8">
            {sel ? (
              <div className="bg-white rounded-2xl border border-ink-100 overflow-hidden">
                <div className="px-5 py-4 border-b border-ink-100">
                  <div className="text-[10.5px] uppercase tracking-wider text-ink-400">{selected.type==="div"?"Division":selected.type==="dept"?"Department":"Position"}</div>
                  <div className="text-[18px] font-bold text-ink-900 mt-0.5">{sel.name}</div>
                </div>
                <div className="p-5">
                  {!canEdit && <div className="mb-3 text-[11.5px] text-ink-500 flex items-center gap-1.5"><Icon name="eye" size={12}/>ข้อมูลนี้อ่านได้อย่างเดียว</div>}
                  {selected.type === "div" && (
                    <div>
                      <div className="grid grid-cols-2 gap-4">
                        <Field label="ชื่อ Division"><Input defaultValue={sel.name} disabled={!canEdit}/></Field>
                        <Field label="คำย่อ"><Input defaultValue={sel.short} className="font-mono uppercase" disabled={!canEdit}/></Field>
                        <Field label="คำอธิบาย" className="col-span-2"><Textarea rows={2} placeholder="—" disabled={!canEdit}/></Field>
                      </div>
                      <div className="mt-4 grid grid-cols-3 gap-3">
                        <StatCard label="Departments" value={departments.filter(d=>d.division_id===sel.id).length}/>
                        <StatCard label="Positions" value={positions.filter(p=>p.division_id===sel.id).length}/>
                        <StatCard label="Users" value={users.filter(u=>u.positions.some(pid=>positions.find(p=>p.id===pid)?.division_id===sel.id)).length}/>
                      </div>
                    </div>
                  )}
                  {selected.type === "dept" && (
                    <div className="grid grid-cols-2 gap-4">
                      <Field label="ชื่อ Department"><Input defaultValue={sel.name} disabled={!canEdit}/></Field>
                      <Field label="Division"><Select defaultValue={sel.division_id} disabled={!canEdit}>{divisions.map(d=><option key={d.id} value={d.id}>{d.name}</option>)}</Select></Field>
                      <Field label="คำอธิบาย" className="col-span-2"><Textarea rows={2} disabled={!canEdit}/></Field>
                    </div>
                  )}
                  {selected.type === "pos" && (
                    <div className="grid grid-cols-2 gap-4">
                      <Field label="ชื่อตำแหน่ง"><Input defaultValue={sel.name} disabled={!canEdit}/></Field>
                      <Field label="ระดับตำแหน่ง">
                        <Select defaultValue={sel.level} disabled={!canEdit}>
                          {["officer","senior","manager","director"].map(l=><option key={l}>{l}</option>)}
                        </Select>
                      </Field>
                      <Field label="Department"><Select defaultValue={sel.department_id} disabled={!canEdit}>{departments.map(d=><option key={d.id} value={d.id}>{d.name}</option>)}</Select></Field>
                      <Field label="Division"><Select defaultValue={sel.division_id} disabled={!canEdit}>{divisions.map(d=><option key={d.id} value={d.id}>{d.name}</option>)}</Select></Field>
                      <Field label="คำอธิบาย" className="col-span-2"><Textarea rows={2} disabled={!canEdit}/></Field>
                    </div>
                  )}
                </div>
              </div>
            ) : <EmptyState icon="network" title="เลือกหน่วยงานจากด้านซ้าย"/>}
          </div>
        </div>
      ) : (
        <OrgChartVisual divisions={divisions} departments={departments} positions={positions} users={users}/>
      )}

      <ReasonModal open={!!deleteFor} onClose={()=>setDeleteFor(null)} onConfirm={(r)=>handleDelete(deleteFor.type, deleteFor.id, r)}
        title="ยืนยันการลบ" subtitle={deleteFor?.name} confirmLabel="ลบรายการ"/>

      <AddOrgModal adding={adding} divisions={divisions} departments={departments} onClose={()=>setAdding(null)}
        onAdd={(payload)=>{
          if (adding.type==="div") setDivisions(p => [...p, { id:"d"+Date.now(), name:payload.name, short:payload.short || payload.name.slice(0,3).toUpperCase() }]);
          if (adding.type==="dept") setDepartments(p => [...p, { id:"dp"+Date.now(), division_id:adding.parent, name:payload.name, short:payload.short || payload.name.slice(0,3).toUpperCase() }]);
          if (adding.type==="pos") setPositions(p => [...p, { id:"p"+Date.now(), department_id:adding.parent, division_id:adding.div, name:payload.name, level: payload.level || "officer" }]);
          audit("create", `เพิ่ม ${adding.type==="div"?"Division":adding.type==="dept"?"Department":"Position"} — ${payload.name}`);
          toast({kind:"success", msg:"เพิ่มสำเร็จ"});
          setAdding(null);
        }}/>
    </div>
  );
};

const StatCard = ({ label, value }) => (
  <div className="rounded-lg border border-ink-100 bg-ink-50/60 px-3 py-2.5">
    <div className="text-[10.5px] text-ink-500 uppercase tracking-wider">{label}</div>
    <div className="text-[20px] font-bold text-ink-900 font-mono">{value}</div>
  </div>
);

const OrgChartVisual = ({ divisions, departments, positions, users }) => (
  <div className="bg-white rounded-2xl border border-ink-100 p-6 overflow-x-auto thin-scroll">
    <div className="flex flex-col items-center min-w-fit">
      <div className="px-5 py-3 rounded-xl bg-gradient-to-br from-indigo-600 to-indigo-700 text-white font-semibold shadow-lg">บริษัท</div>
      <div className="w-px h-4 bg-ink-300"/>
      <div className="flex items-start gap-4">
        {divisions.map((d,i) => (
          <div key={d.id} className="flex flex-col items-center">
            {i > 0 && <div className="absolute -translate-y-2 h-2"/>}
            <div className="px-4 py-2 rounded-lg bg-indigo-50 border-2 border-indigo-200 text-indigo-700 font-semibold text-[13px] min-w-[180px] text-center">{d.name}</div>
            <div className="w-px h-3 bg-ink-300"/>
            <div className="flex items-start gap-3">
              {departments.filter(dp=>dp.division_id===d.id).map(dp => {
                const pps = positions.filter(p=>p.department_id===dp.id);
                return (
                  <div key={dp.id} className="flex flex-col items-center">
                    <div className="px-3 py-1.5 rounded-md bg-violet-50 border border-violet-200 text-violet-700 font-medium text-[12px] min-w-[140px] text-center">{dp.name}</div>
                    <div className="w-px h-3 bg-ink-300"/>
                    <div className="flex flex-col gap-1 items-center">
                      {pps.map(p => {
                        const u = users.find(u=>u.positions.includes(p.id));
                        return (
                          <div key={p.id} className="px-2.5 py-1 rounded-md bg-white border border-ink-200 text-[11px] min-w-[140px] text-center">
                            <div className="font-medium text-ink-800">{p.name}</div>
                            <div className={`text-[10px] truncate ${u?"text-emerald-600":"text-amber-600"}`}>{u?.full_name || "ยังไม่ผูก"}</div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

const AddOrgModal = ({ adding, divisions, departments, onClose, onAdd }) => {
  const [name, setName] = useState("");
  const [short, setShort] = useState("");
  const [level, setLevel] = useState("officer");
  useEffect(() => { if (adding) { setName(""); setShort(""); setLevel("officer"); } }, [adding]);
  if (!adding) return null;
  const t = adding.type === "div" ? "Division" : adding.type === "dept" ? "Department" : "Position";
  return (
    <Modal open onClose={onClose} title={`เพิ่ม ${t}`} width={480}
      footer={<>
        <Button variant="secondary" onClick={onClose}>ยกเลิก</Button>
        <Button disabled={!name.trim()} onClick={()=>onAdd({name:name.trim(), short:short.trim(), level})}>เพิ่ม</Button>
      </>}>
      <div className="grid grid-cols-2 gap-3">
        <Field label={`ชื่อ ${t}`} required className="col-span-2"><Input value={name} onChange={e=>setName(e.target.value)} autoFocus/></Field>
        {(adding.type==="div" || adding.type==="dept") && (
          <Field label="คำย่อ" hint="ใช้ในคอลัมน์ตาราง"><Input value={short} onChange={e=>setShort(e.target.value.toUpperCase())} className="font-mono uppercase"/></Field>
        )}
        {adding.type === "pos" && (
          <Field label="ระดับ"><Select value={level} onChange={e=>setLevel(e.target.value)}>{["officer","senior","manager","director"].map(l=><option key={l}>{l}</option>)}</Select></Field>
        )}
      </div>
    </Modal>
  );
};

Object.assign(window, { OrgChartPage });
