// ──── TREATMENTS catalog ────
const TX_CATEGORIES = ["İmplant","Ortodonti","Kanal Tedavisi","Kompozit Dolgu","Zirkonyum / Kron","Beyazlatma","Diş Çekimi","Tartar Temizliği","Diğer"];


function Treatments({ data, onNav, setSelectedPatient, onUpdatePatient, onUpdateCatalog }) {
  const { Card, Tag, fmtTRY } = window.DentUI;
  const I = window.DentIcons;
  const [showFilter, setShowFilter] = React.useState(false);
  const [clinicFilter, setClinicFilter] = React.useState("all");
  const [statusFilter, setStatusFilter] = React.useState("all");
  const [catFilter, setCatFilter] = React.useState("all");
  const [importMsg, setImportMsg] = React.useState(null);
  const catalogImportRef = React.useRef();
  const isMobile = window.innerWidth < 768;

  // Catalog edit state
  const [editingCode, setEditingCode] = React.useState(null);
  const [editForm, setEditForm] = React.useState({ code: "", name: "", baseFee: "" });
  const [addingNew, setAddingNew] = React.useState(false);
  const [newForm, setNewForm] = React.useState({ code: "", name: "", baseFee: "" });

  const saveCatalog = (next) => { if (onUpdateCatalog) onUpdateCatalog(next); };

  const startEdit = (c) => {
    setEditingCode(c.code);
    setEditForm({ code: c.code, name: c.name, baseFee: String(c.baseFee) });
    setAddingNew(false);
  };

  const commitEdit = () => {
    if (!editForm.name.trim()) return;
    saveCatalog(data.TREATMENTS_CATALOG.map(c =>
      c.code === editingCode
        ? { code: editForm.code.trim().toUpperCase().slice(0, 6) || editingCode, name: editForm.name.trim(), baseFee: parseFloat(editForm.baseFee) || 0 }
        : c
    ));
    setEditingCode(null);
  };

  const deleteItem = (code) => {
    saveCatalog(data.TREATMENTS_CATALOG.filter(c => c.code !== code));
  };

  const startAdd = () => {
    setAddingNew(true);
    setEditingCode(null);
    setNewForm({ code: "", name: "", baseFee: "" });
  };

  const commitAdd = () => {
    if (!newForm.name.trim()) return;
    const autoCode = newForm.code.trim().toUpperCase().slice(0, 6) ||
      newForm.name.replace(/\s+/g, "").slice(0, 3).toUpperCase();
    saveCatalog([...data.TREATMENTS_CATALOG, {
      code: autoCode,
      name: newForm.name.trim(),
      baseFee: parseFloat(newForm.baseFee) || 0,
    }]);
    setNewForm({ code: "", name: "", baseFee: "" });
    setAddingNew(false);
  };

  const handleCatalogTemplate = () => {
    const XLSX = window.XLSX;
    const rows = [
      ["Kod *", "İşlem Adı *", "Standart Fiyat (₺) *"],
      ["IMP", "İmplant", 18000],
      ["KAN", "Kanal Tedavisi", 4500],
      ["DOL", "Kompozit Dolgu", 1800],
      ["ZIR", "Zirkonyum Kron", 7500],
      ["BEY", "Diş Beyazlatma", 5500],
      ["CEK", "Diş Çekimi", 1500],
      ["TRT", "Tartar Temizliği", 1400],
    ];
    const ws = XLSX.utils.aoa_to_sheet(rows);
    ws["!cols"] = [12, 28, 22].map(w => ({ wch: w }));
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "İşlem Katalogu");
    XLSX.writeFile(wb, "DentSide_Islem_Katalogu_Taslak.xlsx");
  };

  const handleCatalogImport = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      try {
        const XLSX = window.XLSX;
        const wb = XLSX.read(ev.target.result, { type: "array" });
        const ws = wb.Sheets[wb.SheetNames[0]];
        const rows = XLSX.utils.sheet_to_json(ws, { header: 1 });
        const items = rows.slice(1).filter(r => r[0] && r[1]).map(r => ({
          code: String(r[0] || "").trim().toUpperCase().slice(0, 6),
          name: String(r[1] || "").trim(),
          baseFee: parseFloat(r[2]) || 0,
        })).filter(r => r.name);
        if (items.length === 0) { setImportMsg({ error: "Geçerli satır bulunamadı." }); return; }
        if (onUpdateCatalog) onUpdateCatalog(items);
        setImportMsg({ count: items.length });
        setTimeout(() => setImportMsg(null), 3000);
      } catch {
        setImportMsg({ error: "Dosya okunamadı." });
      }
    };
    reader.readAsArrayBuffer(file);
    e.target.value = "";
  };

  let patients = data.PATIENTS;
  if (clinicFilter !== "all") patients = patients.filter(p => p.clinicId === clinicFilter);
  if (statusFilter !== "all") patients = patients.filter(p => p.status === statusFilter);
  if (catFilter !== "all") patients = patients.filter(p => p.treatment && p.treatment.toLowerCase().includes(catFilter.toLowerCase()));

  const activeCount = data.PATIENTS.filter(p => p.status === "Devam ediyor").length;

  const IconEdit = () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
      <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
      <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
    </svg>
  );
  const IconTrash = () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
      <polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/>
      <path d="M9 6V4h6v2"/>
    </svg>
  );
  const IconCheck = () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
      <polyline points="20 6 9 17 4 12"/>
    </svg>
  );
  const IconX = () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
      <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
    </svg>
  );

  return (
    <div className="view">
      <div className="page-head">
        <div>
          <h1 className="page-title">Tedaviler</h1>
          <p className="page-sub">{patients.length} hasta · {activeCount} aktif tedavi</p>
        </div>
        <div className="page-actions">
          <button className={`btn btn--ghost ${showFilter?"is-active":""}`} onClick={() => setShowFilter(v => !v)}>
            <I.Filter size={15}/>Filtre {showFilter ? "▲" : "▼"}
          </button>
        </div>
      </div>

      {showFilter && (
        <div style={{background:"var(--surface)",border:"1px solid var(--line)",borderRadius:"var(--radius-lg)",padding:"16px 20px",marginBottom:16,display:"flex",flexDirection:"column",gap:12}}>
          <div style={{display:"flex",gap:24,flexWrap:"wrap"}}>
            <div>
              <div style={{fontSize:11,fontWeight:700,color:"var(--text-mute)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:8}}>Klinik</div>
              <div className="chips">
                <button className={`chip ${clinicFilter==="all"?"is-on":""}`} onClick={() => setClinicFilter("all")}>Tümü</button>
                {data.CLINICS.map(c => (
                  <button key={c.id} className={`chip ${clinicFilter===c.id?"is-on":""}`} onClick={() => setClinicFilter(c.id)}>
                    <span className="clinic-bullet" style={{background:c.color}}/>{c.name.split(" ").slice(0,2).join(" ")}
                  </button>
                ))}
              </div>
            </div>
            <div>
              <div style={{fontSize:11,fontWeight:700,color:"var(--text-mute)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:8}}>Durum</div>
              <div className="seg">
                <button className={`seg__opt ${statusFilter==="all"?"is-on":""}`} onClick={() => setStatusFilter("all")}>Tümü</button>
                <button className={`seg__opt ${statusFilter==="Devam ediyor"?"is-on":""}`} onClick={() => setStatusFilter("Devam ediyor")}>Aktif</button>
                <button className={`seg__opt ${statusFilter==="Tamamlandı"?"is-on":""}`} onClick={() => setStatusFilter("Tamamlandı")}>Biten</button>
                <button className={`seg__opt ${statusFilter==="Bekliyor"?"is-on":""}`} onClick={() => setStatusFilter("Bekliyor")}>Bekliyor</button>
              </div>
            </div>
            <div>
              <div style={{fontSize:11,fontWeight:700,color:"var(--text-mute)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:8}}>Tedavi tipi</div>
              <div className="chips">
                <button className={`chip ${catFilter==="all"?"is-on":""}`} onClick={() => setCatFilter("all")}>Tümü</button>
                {TX_CATEGORIES.filter(c => c !== "Diğer").map(cat => (
                  <button key={cat} className={`chip ${catFilter===cat?"is-on":""}`} onClick={() => setCatFilter(cat)}>{cat}</button>
                ))}
              </div>
            </div>
          </div>
          {(clinicFilter !== "all" || statusFilter !== "all" || catFilter !== "all") && (
            <button className="btn btn--ghost btn--sm" style={{alignSelf:"flex-start"}} onClick={() => { setClinicFilter("all"); setStatusFilter("all"); setCatFilter("all"); }}>
              Filtreleri temizle
            </button>
          )}
        </div>
      )}

      <div className="tx-grid" style={isMobile ? {gridTemplateColumns:"1fr",display:"block"} : {gridTemplateColumns:"1fr 1fr"}}>
        <Card padding={24} style={isMobile ? {marginBottom:14} : {}}>
          <div className="card-head" style={{marginBottom:12}}>
            <div>
              <h3 className="card-title">İşlem katalogu</h3>
              <p className="card-sub">Standart fiyat ve hekim payı</p>
            </div>
            <div style={{display:"flex",gap:8,flexShrink:0}}>
              <button className="btn btn--ghost btn--sm" onClick={handleCatalogTemplate}>
                <I.Export size={13}/> Taslak İndir
              </button>
              <button className="btn btn--ghost btn--sm" onClick={() => catalogImportRef.current.click()}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                Excel İmport
              </button>
              <input ref={catalogImportRef} type="file" accept=".xlsx,.xls" style={{display:"none"}} onChange={handleCatalogImport}/>
            </div>
          </div>
          {importMsg && (
            <div style={{marginBottom:10,padding:"8px 12px",borderRadius:8,fontSize:13,
              background: importMsg.error ? "#fef2f2" : "#ecfdf5",
              color: importMsg.error ? "#dc2626" : "#059669",
              border: `1px solid ${importMsg.error ? "#fecaca" : "#a7f3d0"}`}}>
              {importMsg.error || `${importMsg.count} işlem başarıyla yüklendi.`}
            </div>
          )}

          <div className="catalog">
            {data.TREATMENTS_CATALOG.length === 0 && !addingNew && (
              <p style={{fontSize:13,color:"var(--text-mute)",padding:"12px 0"}}>
                Henüz işlem eklenmedi. Aşağıdan ekleyebilir veya Excel ile toplu yükleyebilirsiniz.
              </p>
            )}

            {data.TREATMENTS_CATALOG.map(c => (
              editingCode === c.code ? (
                <div key={c.code} className="catalog-row catalog-row--edit">
                  <input
                    className="cat-input cat-input--code"
                    value={editForm.code}
                    onChange={e => setEditForm(f => ({...f, code: e.target.value}))}
                    placeholder="KOD"
                    maxLength={6}
                  />
                  <input
                    className="cat-input cat-input--name"
                    value={editForm.name}
                    onChange={e => setEditForm(f => ({...f, name: e.target.value}))}
                    placeholder="İşlem adı"
                    autoFocus
                    onKeyDown={e => { if (e.key === "Enter") commitEdit(); if (e.key === "Escape") setEditingCode(null); }}
                  />
                  <input
                    className="cat-input cat-input--fee"
                    value={editForm.baseFee}
                    onChange={e => setEditForm(f => ({...f, baseFee: e.target.value}))}
                    placeholder="0"
                    type="number"
                    min="0"
                  />
                  <div className="cat-actions">
                    <button className="cat-btn cat-btn--save" onClick={commitEdit} title="Kaydet"><IconCheck/></button>
                    <button className="cat-btn cat-btn--cancel" onClick={() => setEditingCode(null)} title="İptal"><IconX/></button>
                  </div>
                </div>
              ) : (
                <div key={c.code} className="catalog-row">
                  <span className="catalog-code">{c.code}</span>
                  <span className="catalog-name">{c.name}</span>
                  <span className="num">{fmtTRY(c.baseFee)}</span>
                  <div className="cat-actions">
                    <button className="cat-btn cat-btn--edit" onClick={() => startEdit(c)} title="Düzenle"><IconEdit/></button>
                    <button className="cat-btn cat-btn--del" onClick={() => deleteItem(c.code)} title="Sil"><IconTrash/></button>
                  </div>
                </div>
              )
            ))}

            {addingNew && (
              <div className="catalog-row catalog-row--edit catalog-row--new">
                <input
                  className="cat-input cat-input--code"
                  value={newForm.code}
                  onChange={e => setNewForm(f => ({...f, code: e.target.value}))}
                  placeholder="KOD"
                  maxLength={6}
                />
                <input
                  className="cat-input cat-input--name"
                  value={newForm.name}
                  onChange={e => setNewForm(f => ({...f, name: e.target.value}))}
                  placeholder="İşlem adı"
                  autoFocus
                  onKeyDown={e => { if (e.key === "Enter") commitAdd(); if (e.key === "Escape") setAddingNew(false); }}
                />
                <input
                  className="cat-input cat-input--fee"
                  value={newForm.baseFee}
                  onChange={e => setNewForm(f => ({...f, baseFee: e.target.value}))}
                  placeholder="₺"
                  type="number"
                  min="0"
                />
                <div className="cat-actions">
                  <button className="cat-btn cat-btn--save" onClick={commitAdd} title="Ekle"><IconCheck/></button>
                  <button className="cat-btn cat-btn--cancel" onClick={() => setAddingNew(false)} title="İptal"><IconX/></button>
                </div>
              </div>
            )}
          </div>

          {!addingNew && (
            <button className="cat-add-btn" onClick={startAdd}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                <line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
              </svg>
              İşlem Ekle
            </button>
          )}
        </Card>

        <Card padding={24} style={{gridColumn: "span 2"}}>
          <div className="card-head">
            <div>
              <h3 className="card-title">Tedavi planları</h3>
              <p className="card-sub">{patients.length} hasta gösteriliyor</p>
            </div>
          </div>
          <div className="tx-list">
            {patients.length === 0 && <p style={{fontSize:13,color:"var(--text-mute)",padding:"12px 0"}}>Filtre kriterlerine uyan hasta bulunamadı.</p>}
            {patients.map(p => {
              const c = data.CLINICS.find(cc => cc.id === p.clinicId);
              if (!c) return null;
              const done = p.plan.filter(s => s.status === "Tamamlandı").length;
              const total = p.plan.length;
              const pct = total ? Math.round((done/total)*100) : 0;
              const next = p.plan.find(s => s.status === "Planlandı");
              return (
                <div key={p.id} className="tx-row" style={{cursor:"pointer"}}
                  onClick={() => { setSelectedPatient(p.id); onNav("patients"); }}>
                  <div>
                    <div className="tx-row__name">{p.name}</div>
                    <div className="tx-row__sub muted">{p.treatment || "—"} · <span style={{color:c.color}}>●</span> {c.name}</div>
                  </div>
                  <div className="tx-prog">
                    <div className="tx-prog__bar"><div className="tx-prog__fill" style={{width:`${pct}%`}}/></div>
                    <span className="muted xs">{done}/{total} seans</span>
                  </div>
                  <div className="tx-next">
                    {next ? (
                      <>
                        <span className="muted xs">Sonraki</span>
                        <span>{next.procedure}</span>
                      </>
                    ) : total > 0 ? <Tag color="green" dot>Tamamlandı</Tag> : <span className="muted xs">—</span>}
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>

    </div>
  );
}

window._dsTreatments = Treatments;
