// screen-new-claim.jsx — F1 New claim intake form
// Patient demographics, policy, ICD-10 picker, claim type, initial doc upload.

const PCNC_t = window.PCT;
const PCNC_d = window.PCA;

function NewClaimScreen() {
  const store = useStore();
  const mode = store.state.mode;

  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    patientName: '',
    age: '',
    gender: 'F',
    phone: '',
    abhaId: '',
    insurer: '',
    policyNumber: '',
    claimType: 'CASHLESS',
    estimatedCost: '',
    icd: '',
    icdLabel: '',
    symptomOnset: '',
    doctor: '',
    doctorReg: '',
    ward: '',
    roomType: 'Private',
    admittedAt: Date.now(),
    depositCollected: 0,
    documents: [],
  });
  const setF = (patch) => setForm(f => ({ ...f, ...patch }));

  const isHmsMode = mode === 'integrated';

  // In HMS-integrated mode, pre-fill from a "selected admission"
  React.useEffect(() => {
    if (isHmsMode && !form.patientName) {
      setF({
        patientName: 'Lakshmi Ramachandran',
        age: 64,
        gender: 'F',
        phone: '+91 98450 22417',
        doctor: 'Dr. Anand Krishnan',
        doctorReg: 'KMC-12847',
        ward: 'ICU · Bed 4',
        admittedAt: Date.now(),
      });
    }
  }, [isHmsMode]);

  const handleCreate = () => {
    const id = store.createClaim({
      patient: {
        name: form.patientName,
        uhid: 'UHID-' + Math.floor(40000 + Math.random() * 999),
        age: Number(form.age),
        gender: form.gender,
        phone: form.phone,
        abha: form.abhaId,
      },
      doctor: form.doctor || 'Dr. Anand Krishnan',
      doctorReg: form.doctorReg || 'KMC-12847',
      ward: form.ward || 'GenMed · Bed 1',
      roomType: form.roomType,
      insurer: form.insurer,
      policyNumber: form.policyNumber,
      icd: form.icd,
      icdLabel: form.icdLabel,
      symptomOnset: form.symptomOnset,
      admittedAt: form.admittedAt,
      claimType: form.claimType,
      estimatedCost: Number(form.estimatedCost) || 0,
      approvedAmount: null,
      patientShare: null,
      depositCollected: Number(form.depositCollected) || 0,
      coordinator: 'Priya M.',
      documents: form.documents,
    });
    navigate(`#/claims/${id}/documents`);
  };

  const insurerOpts = PCNC_d.insurers.map(i => ({ value: i.id, label: `${i.name} · ${i.type}` }));

  // Step gates
  const step1Ready = form.patientName && form.age && form.phone && form.insurer && form.policyNumber && form.claimType && form.estimatedCost;
  const step2Ready = form.icd && form.symptomOnset;
  const step3Ready = form.doctor && form.doctorReg && form.admittedAt;

  return (
    <Shell
      active="claims"
      breadcrumb={[mode === 'standalone' ? 'My worklist' : 'Revenue', 'Claims', 'New']}
    >
      <div style={{ padding:'28px 24px 80px', maxWidth: 900 }}>
        {/* Hero */}
        <div style={{ marginBottom: 26 }}>
          <div style={{ fontSize:26, fontWeight:600, letterSpacing:'-.015em' }}>Create a new claim</div>
          <div style={{ fontSize:13.5, color: PCNC_t.c.textMuted, marginTop:6, lineHeight:1.6, maxWidth: 620 }}>
            {isHmsMode
              ? <span>Patient details are pre-filled from the admission record. Confirm and add policy/insurer to proceed.</span>
              : <span>Fill in patient and policy details. Standalone mode: nothing comes from an HMS — type it in.</span>}
          </div>
        </div>

        {/* Step indicator */}
        <div style={{
          display:'flex', alignItems:'center', gap:8, marginBottom:24,
        }}>
          {[
            { id:1, label:'Patient &amp; policy' },
            { id:2, label:'Diagnosis &amp; onset' },
            { id:3, label:'Admission &amp; doctor' },
            { id:4, label:'Initial documents' },
          ].map((s, i) => (
            <React.Fragment key={s.id}>
              <div onClick={() => s.id <= step && setStep(s.id)} style={{
                display:'flex', alignItems:'center', gap:8,
                padding:'7px 12px', borderRadius:7,
                background: step === s.id ? PCNC_t.c.brandSoft : step > s.id ? PCNC_t.c.successTint : PCNC_t.c.surface2,
                color: step === s.id ? PCNC_t.c.brand : step > s.id ? PCNC_t.c.success : PCNC_t.c.textMuted,
                fontSize:12.5, fontWeight: step === s.id ? 600 : 500,
                cursor: s.id <= step ? 'pointer' : 'default',
              }}>
                <span style={{
                  width:20, height:20, borderRadius:'50%', display:'grid', placeItems:'center',
                  background: step > s.id ? PCNC_t.c.success : step === s.id ? PCNC_t.c.brand : '#fff',
                  color: step === s.id || step > s.id ? '#fff' : PCNC_t.c.textMuted,
                  fontFamily: PCNC_t.f.mono, fontSize:10, fontWeight:700,
                  border: step < s.id ? `1px solid ${PCNC_t.c.borderStrong}` : '0',
                }}>{step > s.id ? '✓' : s.id}</span>
                <span dangerouslySetInnerHTML={{__html:s.label}}/>
              </div>
              {i < 3 && <AppIcon name="right" size={12} color={PCNC_t.c.textDim}/>}
            </React.Fragment>
          ))}
        </div>

        {/* Step content */}
        <AppCard pad={26}>
          {step === 1 && (
            <Step1 form={form} setF={setF} insurerOpts={insurerOpts} isHms={isHmsMode}/>
          )}
          {step === 2 && (
            <Step2 form={form} setF={setF}/>
          )}
          {step === 3 && (
            <Step3 form={form} setF={setF}/>
          )}
          {step === 4 && (
            <Step4 form={form} setF={setF}/>
          )}
        </AppCard>

        {/* Footer */}
        <div style={{
          marginTop:20, display:'flex', alignItems:'center', justifyContent:'space-between',
        }}>
          <a href="#/" style={{ textDecoration:'none' }}>
            <AppBtn kind="ghost" icon="left">Back to dashboard</AppBtn>
          </a>
          <div style={{ display:'flex', gap:8 }}>
            {step > 1 && <AppBtn kind="ghost" onClick={() => setStep(step - 1)}>Previous</AppBtn>}
            {step < 4 && <AppBtn kind="primary" iconRight="right" onClick={() => setStep(step + 1)}
              disabled={(step === 1 && !step1Ready) || (step === 2 && !step2Ready) || (step === 3 && !step3Ready)}>
              Continue
            </AppBtn>}
            {step === 4 && <AppBtn kind="brand" icon="check" onClick={handleCreate}>
              Create claim
            </AppBtn>}
          </div>
        </div>
      </div>
    </Shell>
  );
}

// ── Steps ────────────────────────────────────────────────
function Step1({ form, setF, insurerOpts, isHms }) {
  const isHighValue = Number(form.estimatedCost) >= 100000;
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:20 }}>
      <SectionHeading>Patient details</SectionHeading>
      {isHms && (
        <div style={{
          padding:'10px 14px', background: PCNC_t.c.accentTint, borderRadius:7,
          fontSize:12, color:'#075985', lineHeight:1.55,
          display:'flex', gap:8,
        }}>
          <AppIcon name="check" size={14} color={PCNC_t.c.accent}/>
          <span><strong>Auto-filled from admission.</strong> Patient demographics pulled from <code style={{ background:'#fff', padding:'1px 5px', borderRadius:3 }}>patient-service</code> · UHID assigned · documents linked.</span>
        </div>
      )}
      <div style={{ display:'grid', gridTemplateColumns:'2fr 80px 90px 1fr', gap:14 }}>
        <AppField label="Patient name" required><AppInput value={form.patientName} onChange={v => setF({ patientName: v })}/></AppField>
        <AppField label="Age" required><AppInput type="number" value={form.age} onChange={v => setF({ age: v })}/></AppField>
        <AppField label="Gender" required>
          <AppSelect value={form.gender} onChange={v => setF({ gender: v })} options={[
            { value:'F', label:'Female' }, { value:'M', label:'Male' }, { value:'O', label:'Other' }
          ]}/>
        </AppField>
        <AppField label="Phone" required><AppInput value={form.phone} onChange={v => setF({ phone: v })} placeholder="+91 …" mono/></AppField>
      </div>
      <AppField label="ABHA ID" hint="Optional · Ayushman Bharat Health Account">
        <AppInput value={form.abhaId} onChange={v => setF({ abhaId: v })} placeholder="14-2345-6789-0012" mono/>
      </AppField>

      <SectionHeading>Policy &amp; claim type</SectionHeading>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
        <AppField label="Insurer / TPA" required>
          <AppSelect value={form.insurer} onChange={v => setF({ insurer: v })} options={insurerOpts}/>
        </AppField>
        <AppField label="Policy number" required>
          <AppInput value={form.policyNumber} onChange={v => setF({ policyNumber: v })} placeholder="P/181000/01/2025/A032177" mono/>
        </AppField>
      </div>
      <AppField label="Claim type" required>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
          {[
            { id:'CASHLESS',      label:'Cashless',     desc:'Pre-auth via TPA portal' },
            { id:'REIMBURSEMENT', label:'Reimbursement',desc:'Patient pays, claims later' },
          ].map(o => (
            <div key={o.id} onClick={() => setF({ claimType: o.id })} style={{
              padding:'12px 14px',
              border: form.claimType === o.id ? `2px solid ${PCNC_t.c.brand}` : `1px solid ${PCNC_t.c.border}`,
              background: form.claimType === o.id ? PCNC_t.c.brandSoft : PCNC_t.c.surface,
              borderRadius:8, cursor:'pointer',
            }}>
              <div style={{ fontSize:13, fontWeight: form.claimType === o.id ? 600 : 500 }}>{o.label}</div>
              <div style={{ fontSize:11.5, color: PCNC_t.c.textMuted, marginTop:3 }}>{o.desc}</div>
            </div>
          ))}
        </div>
      </AppField>
      <AppField label="Estimated cost (₹)" required hint={isHighValue ? 'High-value claim (≥ ₹1L) — KYC + PAN + Aadhaar will be added to checklist automatically.' : 'Used for pre-auth estimate letter and high-value KYC trigger.'}>
        <AppInput type="number" value={form.estimatedCost} onChange={v => setF({ estimatedCost: v })} mono placeholder="485000"/>
      </AppField>
      {isHighValue && (
        <div style={{
          padding:'10px 12px', background: PCNC_t.c.brandSoft, borderRadius:6,
          fontSize:11.5, color:'#4C1D95', lineHeight:1.55,
          display:'flex', gap:8,
        }}>
          <AppIcon name="sparkle" size={13} color={PCNC_t.c.brand}/>
          <span>High-value KYC trigger active: KYC form, PAN, and masked Aadhaar will be auto-added to the document checklist.</span>
        </div>
      )}
    </div>
  );
}

function Step2({ form, setF }) {
  const [search, setSearch] = React.useState('');
  const filtered = PCNC_d.icd10.filter(c =>
    !search || c.code.toLowerCase().includes(search.toLowerCase()) || c.label.toLowerCase().includes(search.toLowerCase())
  ).slice(0, 8);

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:20 }}>
      <SectionHeading>Primary diagnosis (ICD-10)</SectionHeading>
      <div style={{
        padding:'12px 14px', background: PCNC_t.c.warningTint, borderRadius:7,
        fontSize:11.5, color:'#92400E', lineHeight:1.55,
        display:'flex', gap:8,
      }}>
        <AppIcon name="info" size={14} color={PCNC_t.c.warning}/>
        <span>
          <strong>ICD-10 + onset duration</strong> are the two most common causes of PED-related rejections.
          Take an extra minute to enter both correctly.
        </span>
      </div>
      <AppField label="Search ICD-10" hint="Type code or description (e.g. 'I21' or 'acute MI')">
        <AppInput value={search} onChange={setSearch} placeholder="I21.0 · acute MI · anterior wall…"/>
      </AppField>
      <div style={{ display:'flex', flexDirection:'column', gap:6, maxHeight:280, overflow:'auto' }}>
        {filtered.map(c => (
          <div key={c.code} onClick={() => setF({ icd: c.code, icdLabel: c.label })} style={{
            display:'flex', gap:14, alignItems:'center',
            padding:'12px 14px', borderRadius:7,
            border: c.code === form.icd ? `2px solid ${PCNC_t.c.brand}` : `1px solid ${PCNC_t.c.border}`,
            background: c.code === form.icd ? PCNC_t.c.brandSoft : PCNC_t.c.surface,
            cursor:'pointer',
          }}>
            <span style={{
              fontFamily: PCNC_t.f.mono, fontSize:13, fontWeight:700,
              padding:'3px 9px', borderRadius:5,
              background:'#fff', color: PCNC_t.c.text,
              minWidth:64, textAlign:'center',
              border:`1px solid ${PCNC_t.c.border}`,
            }}>{c.code}</span>
            <span style={{ fontSize:13, color: PCNC_t.c.text, flex:1 }}>{c.label}</span>
            {c.comorbid.length > 0 && (
              <div style={{ display:'flex', gap:4 }}>
                {c.comorbid.map(co => (
                  <span key={co} style={{
                    fontSize:9, fontFamily: PCNC_t.f.mono, fontWeight:600,
                    padding:'1px 5px', borderRadius:3,
                    background: PCNC_t.c.surface2, color: PCNC_t.c.textMuted, letterSpacing:'.02em',
                  }}>+{co}</span>
                ))}
              </div>
            )}
          </div>
        ))}
      </div>
      <AppField label="Symptom onset duration" required
                hint="Write the timeline + relevant history. ⚠️ Don't write 'known case of HTN' — write 'Hypertension × 8 yrs · last echo Jan 2025'.">
        <AppTextarea value={form.symptomOnset} onChange={v => setF({ symptomOnset: v })} rows={3}
          placeholder="e.g. Chest pain 4 hours prior to admission · known HTN × 8 yrs · prior MI 2021 (no PCI)"/>
      </AppField>
    </div>
  );
}

function Step3({ form, setF }) {
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:20 }}>
      <SectionHeading>Admission &amp; doctor</SectionHeading>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
        <AppField label="Treating doctor" required>
          <AppInput value={form.doctor} onChange={v => setF({ doctor: v })} placeholder="Dr. Anand Krishnan"/>
        </AppField>
        <AppField label="State medical council reg. no." required hint="e.g. KMC-12847 (Karnataka)">
          <AppInput value={form.doctorReg} onChange={v => setF({ doctorReg: v })} mono/>
        </AppField>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:14 }}>
        <AppField label="Ward / Bed" hint="e.g. ICU · Bed 4">
          <AppInput value={form.ward} onChange={v => setF({ ward: v })}/>
        </AppField>
        <AppField label="Room type">
          <AppSelect value={form.roomType} onChange={v => setF({ roomType: v })}
            options={['General','Twin sharing','Private','Deluxe','ICU']}/>
        </AppField>
        <AppField label="Deposit collected (₹)">
          <AppInput type="number" value={form.depositCollected} onChange={v => setF({ depositCollected: v })} mono/>
        </AppField>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
        <AppField label="Admission date &amp; time" required>
          <AppInput type="datetime-local"
            value={new Date(form.admittedAt - new Date().getTimezoneOffset() * 60000).toISOString().slice(0,16)}
            onChange={v => setF({ admittedAt: new Date(v).getTime() })}/>
        </AppField>
        <AppField label="Coordinator">
          <AppInput value="Priya Menon"/>
        </AppField>
      </div>
      <div style={{
        padding:'10px 12px', background: PCNC_t.c.surface2, borderRadius:6,
        fontSize:11, color: PCNC_t.c.textMuted, fontFamily: PCNC_t.f.mono, letterSpacing:'.02em',
      }}>
        Hospital · {PCNC_d.tenant.name} · ROHINI <strong style={{ color: PCNC_t.c.text }}>{PCNC_d.tenant.rohini}</strong> (auto-stamped on all PDFs)
      </div>
    </div>
  );
}

function Step4({ form, setF }) {
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      <SectionHeading>Initial documents (you can add more later)</SectionHeading>
      <div style={{
        padding:'10px 12px', background: PCNC_t.c.surface2, borderRadius:6,
        fontSize:11.5, color: PCNC_t.c.textMuted, lineHeight:1.55,
        display:'flex', gap:8,
      }}>
        <AppIcon name="info" size={13}/>
        <span>Aadhaar uploads are auto-masked (first 8 digits blacked out) before storage. Full insurer-specific checklist appears after you save.</span>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
        {['ID_PROOF','INSURANCE_CARD','CONSULTATION_PAPER','DIAGNOSTIC_REPORT'].map(dt => {
          const isUp = form.documents.includes(dt);
          if (isUp) return <DocChip key={dt} docType={dt} onRemove={() => setF({ documents: form.documents.filter(d => d !== dt) })}/>;
          return <UploadZone key={dt} docType={dt} onUpload={(p) => setF({ documents: [...form.documents, dt] })}/>;
        })}
      </div>
    </div>
  );
}

function SectionHeading({ children }) {
  return (
    <div style={{
      fontFamily: PCNC_t.f.mono, fontSize:10, fontWeight:600,
      letterSpacing:'.1em', textTransform:'uppercase', color: PCNC_t.c.textMuted,
      paddingBottom:6, borderBottom: `1px solid ${PCNC_t.c.border}`,
    }}>{children}</div>
  );
}

Object.assign(window, { NewClaimScreen });
