// tab-documents.jsx — F2 Document checklist tab
// Renders the insurer's pre-auth or reimbursement checklist,
// shows uploaded vs missing, opens UploadZone for missing items,
// triggers KYC for high-value claims automatically.

const PCDT_t = window.PCT;
const PCDT_d = window.PCA;

function DocumentsTab({ claim, insurer }) {
  const store = useStore();
  const integrated = useIntegrated();
  const [override, setOverride] = React.useState(false);
  const [overrideReason, setOverrideReason] = React.useState('');
  const [syncing, setSyncing] = React.useState(false);

  // Build the effective checklist: base + KYC auto-trigger
  const baseChecklist = claim.claimType === 'CASHLESS'
    ? insurer.preauthChecklist
    : insurer.reimbursementChecklist;

  const isHighValue = claim.estimatedCost >= 100000;
  const kycExtras = isHighValue && claim.claimType === 'CASHLESS' ? [
    { docType: 'KYC_FORM',       label: 'KYC form (claim ≥ ₹1L)',   required: true, autoAdded: true },
    { docType: 'PAN_CARD',       label: 'PAN card (claim ≥ ₹1L)',   required: true, autoAdded: true },
    { docType: 'AADHAAR_MASKED', label: 'Masked Aadhaar (claim ≥ ₹1L)', required: true, autoAdded: true },
  ] : [];

  // Filter out KYC items that are already in the base checklist
  const seen = new Set(baseChecklist.map(c => c.docType));
  const checklist = [...baseChecklist, ...kycExtras.filter(k => !seen.has(k.docType))];

  const uploaded = claim.documents || [];
  const missing = checklist.filter(item => item.required && !uploaded.includes(item.docType));
  const allRequiredPresent = missing.length === 0;
  const missingFromHms = integrated
    ? missing.filter(m => window.HMS_AVAILABLE_DOCS && window.HMS_AVAILABLE_DOCS.includes(m.docType))
    : [];
  const fromHms = integrated
    ? uploaded.filter(d => window.HMS_AVAILABLE_DOCS && window.HMS_AVAILABLE_DOCS.includes(d))
    : [];

  // Auto-advance to PREAUTH_READY when all docs are in
  React.useEffect(() => {
    if (claim.status === 'INTAKE' || claim.status === 'DOCS_PENDING') {
      if (allRequiredPresent) {
        store.updateClaim(claim.id, { status: 'PREAUTH_READY' });
      } else if (claim.status === 'INTAKE' && uploaded.length > 0) {
        store.updateClaim(claim.id, { status: 'DOCS_PENDING' });
      }
    }
  }, [allRequiredPresent, claim.status]);

  const handleUpload = (payload) => {
    store.addDocument(claim.id, payload.docType);
    store.toast({
      icon: 'whatsapp',
      title: 'Document uploaded',
      body: `${PCDT_d.docTypes[payload.docType]?.label} · OCR verified`,
    });
  };

  return (
    <div style={{ display:'grid', gridTemplateColumns:'1fr 320px', gap:14 }}>
      {/* MAIN */}
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        {/* Status header */}
        <AppCard>
          <div data-demo="clm-doc-catch" style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:14 }}>
            <div style={{ flex:1 }}>
              <AppSectionLabel>Insurer schema · {insurer.name} · {claim.claimType === 'CASHLESS' ? 'Cashless pre-auth' : 'Reimbursement'}</AppSectionLabel>
              <div style={{ marginTop:8, fontSize:18, fontWeight:600, letterSpacing:'-.005em' }}>
                {allRequiredPresent
                  ? <span style={{ color: PCDT_t.c.success }}>All required documents present</span>
                  : <span>{checklist.length - missing.length} of {checklist.length} required documents uploaded</span>}
              </div>
              <div style={{ fontSize:12.5, color: PCDT_t.c.textMuted, marginTop:4, lineHeight:1.55 }}>
                {allRequiredPresent
                  ? 'Pre-auth submission is unblocked. Move to the Pre-auth tab.'
                  : 'Missing documents block pre-auth submission. Either upload them, or override with a documented reason.'}
              </div>
              {integrated && fromHms.length > 0 && (
                <div style={{
                  marginTop:8, display:'flex', alignItems:'center', gap:8, flexWrap:'wrap',
                  fontSize:11.5, color: PCDT_t.c.textMuted,
                }}>
                  <HmsBadge variant="chip">HMS</HmsBadge>
                  <span>{fromHms.length} document{fromHms.length > 1 ? 's' : ''} auto-linked from HMS · {uploaded.length - fromHms.length} added manually</span>
                </div>
              )}
            </div>
            <div style={{ width:120, flexShrink:0 }}>
              <ProgressRing value={(checklist.length - missing.length)} total={checklist.length}/>
            </div>
          </div>

          {isHighValue && claim.claimType === 'CASHLESS' && (
            <div style={{
              marginTop:14, padding:'10px 14px',
              background: PCDT_t.c.brandSoft,
              borderRadius:7,
              fontSize:12, color:'#4C1D95', lineHeight:1.55,
              display:'flex', gap:8, alignItems:'flex-start',
            }}>
              <AppIcon name="sparkle" size={14} color={PCDT_t.c.brand}/>
              <span>
                <strong>High-value KYC trigger.</strong> Claim ≥ ₹1L auto-added <strong>KYC + PAN + Masked Aadhaar</strong> to the checklist regardless of insurer.
              </span>
            </div>
          )}

          {integrated && missingFromHms.length > 0 && (
            <div style={{
              marginTop:12, padding:'12px 14px',
              background: PCDT_t.c.brandSoft,
              border: `1px solid ${PCDT_t.c.brand}40`,
              borderRadius:8,
              display:'flex', alignItems:'center', gap:12,
            }}>
              <div style={{
                width:32, height:32, borderRadius:7,
                background:'#fff', color: PCDT_t.c.brand,
                display:'grid', placeItems:'center', flexShrink:0,
              }}>
                <AppIcon name="sparkle" size={15}/>
              </div>
              <div style={{ flex:1, fontSize:12.5, color:'#4C1D95', lineHeight:1.55 }}>
                <strong>{missingFromHms.length} missing document{missingFromHms.length > 1 ? 's' : ''} available in HMS</strong>
                <div style={{ fontSize:11, marginTop:3, color:'#5B21B6' }}>
                  {missingFromHms.map(m => window.HMS_SERVICE_FOR[m.docType]).filter((v,i,a) => a.indexOf(v) === i).join(' · ')}
                </div>
              </div>
              <AppBtn size="sm" kind="brand" icon="refresh" disabled={syncing}
                onClick={() => {
                  setSyncing(true);
                  setTimeout(() => {
                    missingFromHms.forEach(m => store.addDocument(claim.id, m.docType));
                    setSyncing(false);
                    store.toast({ icon:'whatsapp', title:`${missingFromHms.length} documents pulled from HMS`, body:'Linked from clinical, lab, radiology, billing services' });
                  }, 900);
                }}>
                {syncing ? 'Syncing…' : 'Sync from HMS'}
              </AppBtn>
            </div>
          )}
        </AppCard>

        {/* Checklist */}
        <AppCard pad={0}>
          <div style={{
            padding:'14px 18px', borderBottom: `1px solid ${PCDT_t.c.border}`,
            display:'flex', justifyContent:'space-between', alignItems:'center',
          }}>
            <AppSectionLabel>Required documents</AppSectionLabel>
            <span style={{ fontSize:11, color: PCDT_t.c.textDim, fontFamily: PCDT_t.f.mono, letterSpacing:'.04em', textTransform:'uppercase' }}>
              From <strong style={{ color: PCDT_t.c.text }}>{insurer.name}</strong> · {claim.claimType.toLowerCase()}
            </span>
          </div>
          <div style={{ padding:14, display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
            {checklist.map(item => (
              <DocChecklistRow
                key={item.docType}
                item={item}
                present={uploaded.includes(item.docType)}
                onUpload={handleUpload}
                onRemove={() => store.removeDocument(claim.id, item.docType)}
              />
            ))}
          </div>
        </AppCard>

        {/* Override panel — only if missing */}
        {!allRequiredPresent && (
          <AppCard>
            <AppSectionLabel>Pre-auth submission · blocked</AppSectionLabel>
            <div style={{ fontSize:12.5, color: PCDT_t.c.textMuted, marginTop:10, lineHeight:1.55 }}>
              You can submit anyway with a documented reason — most TPAs will raise a query, but it's faster than waiting in some cases.
            </div>
            <div style={{
              marginTop:12, padding:12, borderRadius:7,
              background: PCDT_t.c.surface2,
              border: `1px dashed ${PCDT_t.c.borderStrong}`,
            }}>
              <label style={{ display:'flex', alignItems:'flex-start', gap:8, cursor:'pointer' }}>
                <input type="checkbox" checked={override} onChange={e => setOverride(e.target.checked)}
                  style={{ marginTop:3, accentColor: PCDT_t.c.brand }}/>
                <span style={{ fontSize:13 }}>Override the document checklist for this submission</span>
              </label>
              {override && (
                <div style={{ marginTop:10 }}>
                  <AppField label="Reason for override" required>
                    <AppTextarea value={overrideReason} onChange={setOverrideReason}
                      placeholder="e.g. Original lab report mislaid; will couriered tomorrow. Patient stable; admit-side urgent." rows={3}/>
                  </AppField>
                  <div style={{ display:'flex', justifyContent:'flex-end', marginTop:10 }}>
                    <AppBtn kind="primary" size="sm" disabled={!overrideReason.trim()}>
                      Save override
                    </AppBtn>
                  </div>
                </div>
              )}
            </div>
          </AppCard>
        )}

        {/* Uploaded non-required docs (already-attached extras) */}
        {uploaded.filter(d => !checklist.some(c => c.docType === d)).length > 0 && (
          <AppCard>
            <AppSectionLabel>Other documents on file</AppSectionLabel>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginTop:12 }}>
              {uploaded.filter(d => !checklist.some(c => c.docType === d)).map(d => (
                <DocChip key={d} docType={d} onRemove={() => store.removeDocument(claim.id, d)}/>
              ))}
            </div>
          </AppCard>
        )}
      </div>

      {/* RIGHT SIDE */}
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <ICDCard claim={claim}/>
        <SchemaValidatorCard insurer={insurer} claim={claim}/>
      </div>
    </div>
  );
}

function ProgressRing({ value, total }) {
  const pct = total === 0 ? 100 : Math.round((value / total) * 100);
  const r = 36, c = 2 * Math.PI * r;
  const offset = c * (1 - pct / 100);
  const tone = pct === 100 ? PCDT_t.c.success : pct >= 60 ? PCDT_t.c.warning : PCDT_t.c.error;
  return (
    <div style={{ position:'relative', width:96, height:96, marginLeft:'auto' }}>
      <svg width="96" height="96" viewBox="0 0 96 96">
        <circle cx="48" cy="48" r={r} stroke={PCDT_t.c.surface2} strokeWidth="8" fill="none"/>
        <circle cx="48" cy="48" r={r} stroke={tone} strokeWidth="8" fill="none"
          strokeDasharray={c} strokeDashoffset={offset}
          strokeLinecap="round" transform="rotate(-90 48 48)"
          style={{ transition:'stroke-dashoffset .4s' }}/>
      </svg>
      <div style={{
        position:'absolute', inset:0,
        display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
      }}>
        <div style={{ fontFamily: PCDT_t.f.mono, fontSize:20, fontWeight:600, color: tone, fontVariantNumeric:'tabular-nums' }}>{pct}%</div>
        <div style={{ fontSize:10, color: PCDT_t.c.textMuted, fontFamily: PCDT_t.f.mono }}>{value}/{total}</div>
      </div>
    </div>
  );
}

function DocChecklistRow({ item, present, onUpload, onRemove }) {
  const integrated = useIntegrated();
  const fromHms = integrated && window.HMS_AVAILABLE_DOCS && window.HMS_AVAILABLE_DOCS.includes(item.docType);
  if (present) {
    return (
      <div style={{ position:'relative' }}>
        <DocChip docType={item.docType} onRemove={onRemove}/>
        {fromHms && (
          <span style={{ position:'absolute', top:6, right:6 }}>
            <HmsBadge variant="chip">HMS</HmsBadge>
          </span>
        )}
      </div>
    );
  }
  return <UploadZone docType={item.docType} label={item.label} required={item.required} onUpload={onUpload} compact/>;
}

function ICDCard({ claim }) {
  const store = useStore();
  const [editing, setEditing] = React.useState(false);
  const [icdSearch, setIcdSearch] = React.useState(claim.icd);

  const filtered = PCDT_d.icd10
    .filter(c => !icdSearch || c.code.toLowerCase().includes(icdSearch.toLowerCase()) || c.label.toLowerCase().includes(icdSearch.toLowerCase()))
    .slice(0, 6);

  const handlePick = (code) => {
    const icd = PCDT_d.icd10.find(i => i.code === code);
    store.updateClaim(claim.id, { icd: icd.code, icdLabel: icd.label });
    setEditing(false);
  };

  return (
    <AppCard>
      <AppSectionLabel right={
        <button onClick={() => setEditing(!editing)} style={{
          fontSize:11, color: PCDT_t.c.accent, background:'none', border:'none',
          cursor:'pointer', fontWeight:500, fontFamily: PCDT_t.f.sans,
        }}>{editing ? 'Cancel' : 'Change'}</button>
      }>Diagnosis · ICD-10</AppSectionLabel>
      {editing ? (
        <div style={{ marginTop:10 }}>
          <AppInput value={icdSearch} onChange={setIcdSearch} placeholder="Type code or description…"/>
          <div style={{ marginTop:8, display:'flex', flexDirection:'column', gap:4, maxHeight:240, overflow:'auto' }}>
            {filtered.map(c => (
              <div key={c.code} onClick={() => handlePick(c.code)} style={{
                padding:'8px 10px', borderRadius:6,
                background: c.code === claim.icd ? PCDT_t.c.brandSoft : PCDT_t.c.surface2,
                cursor:'pointer', display:'flex', gap:10, alignItems:'baseline',
              }}>
                <span style={{ fontFamily: PCDT_t.f.mono, fontSize:11, fontWeight:600, color: PCDT_t.c.text, minWidth:50 }}>{c.code}</span>
                <span style={{ fontSize:12, color: PCDT_t.c.textMuted }}>{c.label}</span>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div style={{ marginTop:12 }}>
          <div style={{ display:'flex', alignItems:'baseline', gap:8 }}>
            <span style={{
              fontFamily: PCDT_t.f.mono, fontSize:13, fontWeight:600,
              padding:'2px 7px', background: PCDT_t.c.surface2,
              borderRadius:5, color: PCDT_t.c.text,
            }}>{claim.icd}</span>
            <span style={{ fontSize:12.5, fontWeight:500 }}>{claim.icdLabel}</span>
          </div>
          <div style={{
            marginTop:10, fontSize:11.5, color: PCDT_t.c.textMuted, lineHeight:1.5,
            padding:'8px 10px', background: PCDT_t.c.surface2, borderRadius:6,
          }}>
            <div style={{ fontFamily: PCDT_t.f.mono, fontSize:9, fontWeight:600, color: PCDT_t.c.textDim, letterSpacing:'.1em', textTransform:'uppercase', marginBottom:4 }}>
              Symptom onset
            </div>
            {claim.symptomOnset}
          </div>
        </div>
      )}
    </AppCard>
  );
}

function SchemaValidatorCard({ insurer, claim }) {
  // Surface the insurer's special rules + sequence note
  return (
    <AppCard>
      <AppSectionLabel>Schema rules engine</AppSectionLabel>
      <div style={{ marginTop:12 }}>
        <RuleItem icon="check" tone={PCDT_t.c.success} text={`Insurer matched: ${insurer.name}`}/>
        <RuleItem icon="check" tone={PCDT_t.c.success} text={`Claim type: ${claim.claimType.toLowerCase()}`}/>
        <RuleItem icon={claim.estimatedCost >= 100000 ? 'alert' : 'check'} tone={claim.estimatedCost >= 100000 ? PCDT_t.c.warning : PCDT_t.c.success}
                  text={claim.estimatedCost >= 100000 ? 'High-value · KYC docs required' : 'Standard value · no KYC trigger'}/>
        <RuleItem icon="check" tone={PCDT_t.c.success} text={`ROHINI ${PCDT_d.tenant.rohini} stamped on all PDFs`}/>
        <RuleItem icon="check" tone={PCDT_t.c.success} text={`Aadhaar masked (first 8 digits blacked out)`}/>
      </div>
      {insurer.sequenceNote && (
        <div style={{
          marginTop:14, padding:'10px 12px',
          background: PCDT_t.c.accentTint, borderRadius:6,
          fontSize:11, color:'#075985', lineHeight:1.55,
          display:'flex', gap:8, alignItems:'flex-start',
        }}>
          <AppIcon name="info" size={13} color={PCDT_t.c.accent}/>
          <span><strong>Sequence note:</strong> {insurer.sequenceNote}</span>
        </div>
      )}
    </AppCard>
  );
}

function RuleItem({ icon, tone, text }) {
  return (
    <div style={{
      display:'flex', gap:8, alignItems:'flex-start',
      padding:'6px 0', borderBottom: `1px solid ${PCDT_t.c.border}`,
    }}>
      <AppIcon name={icon} size={13} color={tone}/>
      <span style={{ fontSize:12, color: PCDT_t.c.text, lineHeight:1.4 }}>{text}</span>
    </div>
  );
}

Object.assign(window, { DocumentsTab });
