// ═══════════════════════════════════════════════════════════════
//  Eshed Audit Workflow
// ═══════════════════════════════════════════════════════════════

const { useState: uSA, useEffect: uEA, useMemo: uMA, useRef: uRA } = React;

// ───────────────────────────────────────────────
//  Audit Dashboard (for Eshed users)
// ───────────────────────────────────────────────
window.AuditDashboard = function AuditDashboard() {
  const { state, currentUser, approveAudit, returnFromAudit, setState } = window.useApp();
  const { navigate } = window.useRouter();
  const toast = window.useToast();
  const [actionModal, setActionModal] = uSA(null);
  const [notes, setNotes] = uSA('');
  const [action, setAction] = uSA('approve');
  const [stampOpen, setStampOpen] = uSA(false);
  const stampFileRef = uRA();

  const eshedStamp = state.branding?.eshedStamp || null;

  const uploadStamp = (file) => {
    const validation = window.validateFile ? window.validateFile(file, 'image') : { ok: true };
    if (!validation.ok) { toast.push({ type: 'error', title: 'הקובץ נדחה', message: validation.error }); return; }
    const reader = new FileReader();
    reader.onload = e => {
      setState(s => ({ ...s, branding: { ...(s.branding || {}), eshedStamp: e.target.result, eshedStampUploadedAt: new Date().toISOString() } }));
      toast.push({ type: 'success', title: 'חותמת אשד הועלתה', message: 'תופיע על כל מסמך שאשד חותמת' });
    };
    reader.readAsDataURL(file);
  };

  const pending = state.activities.filter(a => a.auditStatus === 'pending');
  const approved = state.activities.filter(a => a.auditStatus === 'approved');
  const returned = state.activities.filter(a => a.auditStatus === 'returned');

  const [tab, setTab] = uSA('pending');

  const totalPending = pending.reduce((s, a) => s + (a.totalActualBudget || 0), 0);
  const totalApproved = approved.reduce((s, a) => s + (a.totalActualBudget || 0), 0);

  // Check for issues in an activity (rule-based)
  const validate = (act) => {
    const issues = [];
    if (!act.paymentEvidence || act.paymentEvidence.length === 0) issues.push('חסרות חשבוניות');
    if (!act.totalActualBudget || act.totalActualBudget <= 0) issues.push('חסר סך תקציב שמומש');
    if (act.executionApproval !== 'approved') issues.push('לא אושר ביצוע');
    const totalPlanned = (act.plannedBudget || 0) + (act.plannedCatering || 0) + (act.plannedPublicity || 0);
    if (act.totalActualBudget > totalPlanned * 1.1) issues.push(`חריגה של ${Math.round((act.totalActualBudget / totalPlanned - 1) * 100)}% מהתקציב`);
    if (!act.supplierName) issues.push('חסר שם ספק');
    if (act.activityCode === '0.3' && !act.paymentEvidence?.some(f => /66/.test(typeof f === 'string' ? f : f.name || ''))) issues.push('חסר דו"ח 66 לרכז');
    return issues;
  };

  const act = actionModal?.activity;
  const issues = act ? validate(act) : [];

  return (
    <div className="animate-fade-in">
      <window.PageHeader
        title="בקרת חברת אשד"
        subtitle="בחינה ואישור דרישות תשלום לפני העברה להרשות החרדית"
        actions={
          <window.Button variant="outline" icon={<window.Icon.Award size={14}/>} onClick={() => stampFileRef.current?.click()}>
            {eshedStamp ? 'החלף חותמת' : 'העלה חותמת אשד'}
          </window.Button>
        }
      />
      <input type="file" ref={stampFileRef} hidden accept="image/*" onChange={e => e.target.files[0] && uploadStamp(e.target.files[0])}/>

      {/* Stamp indicator */}
      {eshedStamp && (
        <div className="surface p-4 mb-5 flex items-center gap-4 bg-gradient-to-br from-emerald-50 to-teal-50 border border-emerald-200">
          <img src={eshedStamp} alt="חותמת אשד" className="h-16 w-auto object-contain bg-white rounded-lg p-1"/>
          <div className="flex-1">
            <div className="font-display font-bold text-sm text-emerald-900">חותמת אשד נטענה</div>
            <div className="text-xs text-emerald-700">תוטבע אוטומטית על כל מסמך שנחתם ע״י חברת הבקרה</div>
          </div>
          <window.Button variant="outline" size="sm" icon={<window.Icon.Trash size={12}/>} onClick={() => {
            if (!confirm('להסיר את החותמת?')) return;
            setState(s => { const b = { ...(s.branding||{}) }; delete b.eshedStamp; return { ...s, branding: b }; });
            toast.push({ message: 'החותמת הוסרה' });
          }}>הסר</window.Button>
        </div>
      )}

      {/* Stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-5">
        <window.StatCard icon="Clock"       label="בקרה ממתינה"      value={<window.AnimatedNumber value={pending.length}/>} sublabel="פעילויות" accent="#8b5cf6"/>
        <window.StatCard icon="Coins"       label="סכום בבקרה"        value={window.formatMoney(totalPending, { compact: true })} accent="#7c3aed"/>
        <window.StatCard icon="CheckCircle" label="אושרו לתשלום"     value={<window.AnimatedNumber value={approved.length}/>} accent="#6366f1"/>
        <window.StatCard icon="ArrowRight"  label="הוחזרו לתיקון"     value={<window.AnimatedNumber value={returned.length}/>} accent="#ec4899"/>
      </div>

      <div className="surface mb-5 p-2">
        <window.Tabs tabs={[
          { value: 'pending',  label: 'ממתינים לבקרה', count: pending.length },
          { value: 'approved', label: 'מאושרים',       count: approved.length },
          { value: 'returned', label: 'הוחזרו',         count: returned.length }
        ]} value={tab} onChange={setTab}/>
      </div>

      {(() => {
        const list = tab === 'pending' ? pending : tab === 'approved' ? approved : returned;
        if (!list.length) return <window.EmptyState icon="CheckCircle" title="אין פעילויות בקטגוריה זו"/>;

        return (
          <div className="space-y-3">
            {list.map(a => {
              const auth = state.authorities.find(x => x.id === a.authorityId);
              const coord = state.users.find(u => u.id === a.coordinatorId);
              const cluster = window.clusterById(a.cluster);
              const vIssues = validate(a);
              const ok = vIssues.length === 0;
              return (
                <div key={a.id} className="surface p-5 animate-fade-in">
                  <div className="flex items-start justify-between gap-4 flex-wrap">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap mb-2">
                        <span className="text-[11px] font-bold px-2 py-0.5 rounded" style={{ background: (cluster?.color || '#64748b') + '15', color: cluster?.color || '#64748b' }}>{a.activityCode}</span>
                        <window.AuthorityChip authority={auth} size="xs"/>
                        <span className="text-xs text-slate-500">· רכז: {coord?.name}</span>
                        <window.Badge status={window.deriveStatus(a)}/>
                      </div>
                      <h3 className="font-display font-bold text-lg">{a.activityName}</h3>
                      <div className="mt-2 grid grid-cols-2 md:grid-cols-4 gap-3 text-xs">
                        <div><span className="text-slate-500">ספק: </span><strong>{a.supplierName || '—'}</strong></div>
                        <div><span className="text-slate-500">רבעון: </span><strong>{a.quarter}</strong></div>
                        <div><span className="text-slate-500">יחידות: </span><strong>{a.completedUnits}/{a.units}</strong></div>
                        <div><span className="text-slate-500">סכום: </span><strong className="text-brand-700 ltr-num">{window.formatMoney(a.totalActualBudget)}</strong></div>
                      </div>

                      {/* Validation */}
                      <div className={`mt-3 p-3 rounded-lg ${ok ? 'bg-emerald-50 border border-emerald-200' : 'bg-amber-50 border border-amber-200'}`}>
                        <div className="flex items-start gap-2">
                          {ok ? (
                            <window.Icon.CheckCircle size={16} className="text-emerald-600 mt-0.5 shrink-0"/>
                          ) : (
                            <window.Icon.AlertCircle size={16} className="text-amber-600 mt-0.5 shrink-0"/>
                          )}
                          <div className="text-xs flex-1">
                            {ok ? (
                              <span className="text-emerald-800 font-semibold">בדיקה אוטומטית: כל הקריטריונים תקינים</span>
                            ) : (
                              <>
                                <div className="font-bold text-amber-800 mb-1">נמצאו {vIssues.length} נושאים לבדיקה:</div>
                                <ul className="space-y-0.5 text-amber-900">
                                  {vIssues.map((issue, i) => <li key={i}>· {issue}</li>)}
                                </ul>
                              </>
                            )}
                          </div>
                        </div>
                      </div>

                      {/* Notes if already audited */}
                      {a.auditStatus === 'approved' && a.auditNotes && (
                        <div className="mt-2 p-2 rounded-lg bg-indigo-50 text-xs text-indigo-900">
                          <strong>הערות בקרה:</strong> {a.auditNotes}
                        </div>
                      )}
                      {a.auditStatus === 'returned' && a.auditReturnReason && (
                        <div className="mt-2 p-2 rounded-lg bg-pink-50 text-xs text-pink-900">
                          <strong>סיבת החזרה:</strong> {a.auditReturnReason}
                        </div>
                      )}
                    </div>
                    <div className="flex flex-col gap-2">
                      <window.Button variant="outline" size="sm" icon={<window.Icon.Eye size={14}/>} onClick={() => navigate('activity-detail', { id: a.id })}>לצפייה מלאה</window.Button>
                      {tab === 'pending' && (
                        <>
                          <window.Button variant="outline" size="sm" icon={<window.Icon.ArrowRight size={14}/>} className="!text-pink-700 !border-pink-300 hover:!bg-pink-50"
                            onClick={() => { setActionModal({ activity: a }); setAction('return'); setNotes(''); }}>
                            החזרה לתיקון
                          </window.Button>
                          <window.Button variant="success" size="sm" icon={<window.Icon.CheckCircle size={14}/>}
                            onClick={() => { setActionModal({ activity: a }); setAction('approve'); setNotes(''); }}>
                            אישור לתשלום
                          </window.Button>
                        </>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        );
      })()}

      {/* Action modal */}
      {actionModal && (
        <window.Modal
          open={!!actionModal}
          onClose={() => setActionModal(null)}
          title={action === 'approve' ? 'אישור לתשלום · אשד' : 'החזרה לתיקון · אשד'}
          footer={
            <>
              <window.Button variant="outline" onClick={() => setActionModal(null)}>ביטול</window.Button>
              {action === 'approve' ? (
                <window.Button variant="success" icon={<window.Icon.CheckCircle size={16}/>} onClick={() => {
                  approveAudit(act.id, currentUser.id, notes);
                  toast.push({ type: 'success', title: 'אושר בבקרה', message: 'הפעילות מאושרת להעברה לתשלום' });
                  setActionModal(null);
                }}>אשר</window.Button>
              ) : (
                <window.Button variant="danger" icon={<window.Icon.ArrowRight size={16}/>} onClick={() => {
                  if (!notes.trim()) { toast.push({ type: 'error', message: 'נא לכתוב סיבת החזרה' }); return; }
                  returnFromAudit(act.id, currentUser.id, notes);
                  toast.push({ type: 'warning', title: 'הוחזר לתיקון', message: 'הרכז קיבל את ההערות' });
                  setActionModal(null);
                }}>החזר</window.Button>
              )}
            </>
          }
        >
          <div className="mb-3 p-3 rounded-lg bg-slate-50">
            <div className="font-semibold text-sm">{act.activityName}</div>
            <div className="text-xs text-slate-500 mt-0.5">{act.supplierName} · <span className="ltr-num">{window.formatMoney(act.totalActualBudget)}</span></div>
          </div>
          <window.Field
            label={action === 'approve' ? 'הערות (אופציונלי)' : 'סיבת החזרה'}
            required={action !== 'approve'}
            help={action === 'approve' ? 'הערות ייראו על ידי המערכת והרכז' : 'הרכז יקבל את ההסבר ויתקן'}
          >
            <textarea value={notes} onChange={e => setNotes(e.target.value)} className="textarea" autoFocus
              placeholder={action === 'approve'
                ? 'לדוגמה: כל החשבוניות תקינות, הסכומים תואמים.'
                : 'לדוגמה: נא לצרף חשבונית מספקx, הסכום חורג מ-10%...'}
            />
          </window.Field>
        </window.Modal>
      )}
    </div>
  );
};

// ───────────────────────────────────────────────
//  Send-to-Audit button integration (used from PaymentsPageV2)
// ───────────────────────────────────────────────
window.SendToAuditButton = function SendToAuditButton({ activityIds, disabled, onSent }) {
  const { sendToAudit } = window.useApp();
  const toast = window.useToast();
  return (
    <window.Button
      variant="primary"
      size="sm"
      icon={<window.Icon.Shield size={14}/>}
      disabled={disabled}
      onClick={() => {
        sendToAudit(activityIds);
        toast.push({ type: 'success', title: 'נשלח לבקרת אשד', message: `${activityIds.length} פעילויות ממתינות לאישור הבקרה` });
        onSent?.();
      }}
    >
      שליחה לבקרת אשד ({activityIds.length})
    </window.Button>
  );
};
