// CallbackTab.jsx — Callback Request Management UI
// Exported as window.CallbackTab

(function () {
  const { useState, useEffect, useCallback, useRef } = React;

  const STATUS_LABELS = {
    pending: 'Bekleyen',
    calling: 'Arıyor',
    done: 'Tamamlandı',
    failed: 'Başarısız',
    cancelled: 'İptal',
  };

  const STATUS_COLORS = {
    pending: { bg: '#92400e20', border: '#f59e0b', text: '#fbbf24' },
    calling: { bg: '#1e3a8a20', border: '#3b82f6', text: '#60a5fa' },
    done: { bg: '#064e3b20', border: '#10b981', text: '#34d399' },
    failed: { bg: '#7f1d1d20', border: '#ef4444', text: '#f87171' },
    cancelled: { bg: '#1f2937', border: '#6b7280', text: '#9ca3af' },
  };

  const FILTER_TABS = [
    { key: 'all', label: 'Tümü' },
    { key: 'pending', label: 'Bekleyen' },
    { key: 'calling', label: 'Arıyor' },
    { key: 'done', label: 'Tamamlandı' },
    { key: 'failed', label: 'Başarısız' },
    { key: 'cancelled', label: 'İptal' },
  ];

  function StatusBadge({ status }) {
    const s = STATUS_COLORS[status] || STATUS_COLORS.cancelled;
    return (
      <span style={{
        display: 'inline-block',
        background: s.bg,
        border: `1px solid ${s.border}`,
        color: s.text,
        borderRadius: 20,
        padding: '2px 10px',
        fontSize: 12,
        fontWeight: 600,
        whiteSpace: 'nowrap',
      }}>
        {STATUS_LABELS[status] || status}
      </span>
    );
  }

  function formatTR(iso) {
    if (!iso) return '--';
    // Backend naive UTC döndürebilir → parseUTC ile yerel saate çevir.
    return fmtDateTime(iso, {
      day: '2-digit', month: '2-digit', year: 'numeric',
      hour: '2-digit', minute: '2-digit',
    });
  }

  // ── Stat card ───────────────────────────────────────────────────────────────
  function StatCard({ label, value, color }) {
    return (
      <div className="card" style={{
        flex: 1, minWidth: 120, textAlign: 'center',
        padding: '16px 12px',
        borderTop: `3px solid ${color}`,
      }}>
        <div style={{ fontSize: 32, fontWeight:600, color }}>{value ?? '—'}</div>
        <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 4 }}>{label}</div>
      </div>
    );
  }

  // ── New / Edit modal ─────────────────────────────────────────────────────────
  function CallbackModal({ mode, initial, queues, onClose, onSaved, toast }) {
    const isEdit = mode === 'edit';
    const [form, setForm] = useState(
      isEdit
        ? {
            notes: initial.notes || '',
            scheduled_at: initial.scheduled_at ? initial.scheduled_at.slice(0, 16) : '',
            status: initial.status || 'pending',
          }
        : {
            phone: '',
            caller_name: '',
            queue_id: '',
            scheduled_at: '',
            notes: '',
          }
    );
    const [saving, setSaving] = useState(false);

    const set = (key, val) =>setForm(f => ({ ...f, [key]: val }));

    const handleSubmit = async (e) => {
      e.preventDefault();
      setSaving(true);
      try {
        let res;
        if (isEdit) {
          res = await authFetch(`/api/callbacks/${initial.id}/status`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              status: form.status,
              notes: form.notes,
              scheduled_at: form.scheduled_at || null,
            }),
          });
        } else {
          const q = queues.find(q =>String(q.id) === String(form.queue_id));
          res = await authFetch('/api/callbacks', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              phone: form.phone,
              caller_name: form.caller_name,
              queue_id: form.queue_id || null,
              queue_name: q ? q.name : '',
              scheduled_at: form.scheduled_at || null,
              notes: form.notes,
            }),
          });
        }
        if (!res.ok) throw new Error('İstek başarısız');
        toast(isEdit ? 'Callback güncellendi' : 'Callback oluşturuldu', 'success');
        onSaved();
      } catch (err) {
        toast(err.message || 'Hata oluştu', 'error');
      } finally {
        setSaving(false);
      }
    };

    const inputStyle = {
      width: '100%', padding: '8px 12px', borderRadius: 8,
      border: '1px solid var(--border)', background: 'var(--bg-card)',
      color: 'inherit', fontSize: 14, boxSizing: 'border-box',
    };

    return (
      <div style={{
        position: 'fixed', inset: 0,
        background: '#00000080',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        zIndex: 1000,
      }} onClick={e =>e.target === e.currentTarget && onClose()}>
        <div className="card" style={{
          width: '100%', maxWidth: 480, padding: 24,
          maxHeight: '90vh', overflowY: 'auto',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
            <h3 style={{ margin: 0, fontSize: 18, fontWeight:600 }}>
              {isEdit ? ' Callback Düzenle' : ' Yeni Callback'}
            </h3>
            <button onClick={onClose} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              color: 'var(--text-dim)', fontSize: 20, lineHeight: 1,
            }}>×</button>
          </div>

          <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {!isEdit && (
              <>
                <div>
                  <label style={{ fontSize: 13, color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>
                    Telefon *
                  </label>
                  <input
                    className="form-input"
                    style={inputStyle}
                    type="tel"
                    required
                    placeholder="+90 5xx xxx xx xx"
                    value={form.phone}
                    onChange={e =>set('phone', e.target.value)}
                  />
                </div>
                <div>
                  <label style={{ fontSize: 13, color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>
                    Müşteri Adı
                  </label>
                  <input
                    className="form-input"
                    style={inputStyle}
                    type="text"
                    placeholder="Bilinmiyor"
                    value={form.caller_name}
                    onChange={e =>set('caller_name', e.target.value)}
                  />
                </div>
                <div>
                  <label style={{ fontSize: 13, color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>
                    Kuyruk
                  </label>
                  <select
                    className="form-select"
                    style={inputStyle}
                    value={form.queue_id}
                    onChange={e =>set('queue_id', e.target.value)}
                  >
                    <option value="">— Seçiniz —</option>
                    {queues.map(q => (
                      <option key={q.id} value={q.id}>{q.name}</option>
                    ))}
                  </select>
                </div>
              </>
            )}

            {isEdit && (
              <div>
                <label style={{ fontSize: 13, color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>
                  Durum
                </label>
                <select
                  className="form-select"
                  style={inputStyle}
                  value={form.status}
                  onChange={e =>set('status', e.target.value)}
                >
                  {Object.entries(STATUS_LABELS).map(([k, v]) => (
                    <option key={k} value={k}>{v}</option>
                  ))}
                </select>
              </div>
            )}

            <div>
              <label style={{ fontSize: 13, color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>
                Planlanan Saat
              </label>
              <input
                className="form-input"
                style={inputStyle}
                type="datetime-local"
                value={form.scheduled_at}
                onChange={e =>set('scheduled_at', e.target.value)}
              />
            </div>

            <div>
              <label style={{ fontSize: 13, color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>
                Notlar
              </label>
              <textarea
                className="form-input"
                style={{ ...inputStyle, minHeight: 80, resize: 'vertical' }}
                placeholder="Notlar..."
                value={form.notes}
                onChange={e =>set('notes', e.target.value)}
              />
            </div>

            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 4 }}>
              <button type="button" className="btn btn-secondary" onClick={onClose}>
                İptal
              </button>
              <button type="submit" className="btn btn-primary" disabled={saving}>
                {saving ? 'Kaydediliyor...' : (isEdit ? 'Güncelle' : 'Oluştur')}
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }

  // ── Main CallbackTab ────────────────────────────────────────────────────────
  function CallbackTab({ toast }) {
    const [callbacks, setCallbacks] = useState([]);
    const [stats, setStats] = useState({});
    const [queues, setQueues] = useState([]);
    const [filterStatus, setFilter] = useState('all');
    const [loading, setLoading] = useState(true);
    const [modal, setModal] = useState(null); // null | {mode:'new'} | {mode:'edit', item}
    const timerRef = useRef(null);

    const fetchAll = useCallback(async () => {
      try {
        const [cbRes, stRes, qRes] = await Promise.all([
          authFetch(`/api/callbacks?status=all&page=1&per_page=50`),
          authFetch('/api/callbacks/stats'),
          authFetch('/api/queues'),
        ]);
        const cbData = await cbRes.json().catch(() => ({ callbacks: [] }));
        const stData = await stRes.json().catch(() => ({}));
        const qData = await qRes.json().catch(() => []);

        setCallbacks(Array.isArray(cbData.callbacks) ? cbData.callbacks : []);
        setStats(stData);
        setQueues(Array.isArray(qData) ? qData : []);
      } catch (e) {
        console.error('CallbackTab fetch error:', e);
      } finally {
        setLoading(false);
      }
    }, []);

    useEffect(() => {
      fetchAll();
      timerRef.current = setInterval(fetchAll, 15000);
      return () =>clearInterval(timerRef.current);
    }, [fetchAll]);

    const handleCall = async (id) => {
      try {
        const res = await authFetch(`/api/callbacks/${id}/call`, { method: 'POST' });
        if (!res.ok) throw new Error('Arama başlatılamadı');
        toast('Arama başlatıldı', 'success');
        fetchAll();
      } catch (e) {
        toast(e.message || 'Hata', 'error');
      }
    };

    const handleDelete = async (id) => {
      if (!window.confirm('Bu callback\'i silmek istediğinize emin misiniz?')) return;
      try {
        const res = await authFetch(`/api/callbacks/${id}`, { method: 'DELETE' });
        if (!res.ok) throw new Error('Silinemedi');
        toast('Callback silindi', 'success');
        fetchAll();
      } catch (e) {
        toast(e.message || 'Hata', 'error');
      }
    };

    const filtered = callbacks.filter(c =>
      filterStatus === 'all' ? true : c.status === filterStatus
    );

    const thStyle = {
      padding: '10px 12px',
      textAlign: 'left',
      fontSize: 12,
      fontWeight:600,
      color: 'var(--text-dim)',
      textTransform: 'uppercase',
      letterSpacing: 0.5,
      borderBottom: '1px solid var(--border)',
      whiteSpace: 'nowrap',
    };

    const tdStyle = {
      padding: '10px 12px',
      fontSize: 13,
      borderBottom: '1px solid var(--border)',
      verticalAlign: 'middle',
    };

    return (
      <div style={{ padding: 0, display: 'flex', flexDirection: 'column', gap: 20 }}>
        {/* ── Stats row ── */}
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <StatCard label="Bekleyen" value={stats.pending} color="#f59e0b" />
          <StatCard label="Arıyor" value={stats.calling} color="#3b82f6" />
          <StatCard label="Bugün Tamamlanan" value={stats.done_today} color="#10b981" />
          <StatCard label="Başarısız" value={stats.failed_today} color="#ef4444" />
        </div>

        {/* ── Toolbar ── */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10 }}>
          {/* Filter tabs */}
          <div style={{
            display: 'flex', gap: 4, background: 'var(--bg-card)',
            border: '1px solid var(--border)', borderRadius: 10, padding: 4,
            flexWrap: 'wrap',
          }}>
            {FILTER_TABS.map(tab => (
              <button
                key={tab.key}
                onClick={() =>setFilter(tab.key)}
                style={{
                  padding: '5px 14px',
                  borderRadius: 7,
                  border: 'none',
                  cursor: 'pointer',
                  fontSize: 13,
                  fontWeight: 600,
                  background: filterStatus === tab.key ? 'var(--primary)' : 'transparent',
                  color: filterStatus === tab.key ? '#fff' : 'var(--text-dim)',
                  transition: 'all 0.15s',
                }}
              >
                {tab.label}
              </button>
            ))}
          </div>

          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>
              {filtered.length} kayıt
            </span>
            <button className="btn btn-secondary" onClick={fetchAll} style={{ padding: '6px 12px', fontSize: 13 }}>
              ↻ Yenile
            </button>
            <button className="btn btn-primary" onClick={() =>setModal({ mode: 'new' })} style={{ padding: '6px 14px', fontSize: 13 }}>
               Yeni Callback
            </button>
          </div>
        </div>

        {/* ── Table ── */}
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ overflowX: 'auto' }}>
            {loading ? (
              <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-dim)' }}>
                Yükleniyor...
              </div>
            ) : filtered.length === 0 ? (
              <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-dim)' }}>
                Kayıt bulunamadı
              </div>
            ) : (
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                  <tr style={{ background: 'var(--bg-hover)' }}>
                    <th style={thStyle}>Talep Saati</th>
                    <th style={thStyle}>Numara</th>
                    <th style={thStyle}>Müşteri Adı</th>
                    <th style={thStyle}>Kuyruk</th>
                    <th style={thStyle}>Planlanan Saat</th>
                    <th style={thStyle}>Durum</th>
                    <th style={{ ...thStyle, textAlign: 'center' }}>Denemeler</th>
                    <th style={{ ...thStyle, textAlign: 'center' }}>İşlemler</th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.map((cb, idx) => (
                    <tr
                      key={cb.id}
                      style={{
                        background: idx % 2 === 0 ? 'transparent' : 'var(--bg-hover)',
                        transition: 'background 0.1s',
                      }}
                    >
                      <td style={tdStyle}>
                        <span style={{ fontFamily: 'monospace', fontSize: 12 }}>
                          {formatTR(cb.requested_at)}
                        </span>
                      </td>
                      <td style={tdStyle}>
                        <span style={{ fontWeight: 600, fontFamily: 'monospace' }}>{cb.phone}</span>
                      </td>
                      <td style={tdStyle}>
                        {cb.caller_name || <span style={{ color: 'var(--text-dim)', fontStyle: 'italic' }}>Bilinmiyor</span>}
                      </td>
                      <td style={tdStyle}>
                        {cb.queue_name
                          ? <span style={{
                              background: 'var(--bg-hover)',
                              border: '1px solid var(--border)',
                              borderRadius: 6, padding: '2px 8px', fontSize: 12,
                            }}>{cb.queue_name}</span>
                          : <span style={{ color: 'var(--text-dim)' }}>—</span>
                        }
                      </td>
                      <td style={tdStyle}>
                        <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>
                          {formatTR(cb.scheduled_at)}
                        </span>
                      </td>
                      <td style={tdStyle}>
                        <StatusBadge status={cb.status} />
                      </td>
                      <td style={{ ...tdStyle, textAlign: 'center' }}>
                        <span style={{
                          display: 'inline-block',
                          background: cb.attempts > 0 ? '#7f1d1d20' : 'var(--bg-hover)',
                          border: `1px solid ${cb.attempts > 0 ? '#ef444460' : 'var(--border)'}`,
                          color: cb.attempts > 0 ? '#f87171' : 'var(--text-dim)',
                          borderRadius: 20, padding: '2px 10px', fontSize: 12, fontWeight:600,
                        }}>
                          {cb.attempts ?? 0}
                        </span>
                      </td>
                      <td style={{ ...tdStyle, textAlign: 'center' }}>
                        <div style={{ display: 'flex', gap: 4, justifyContent: 'center' }}>
                          <button
                            onClick={() =>handleCall(cb.id)}
                            title="Ara"
                            style={{
                              background: '#064e3b30',
                              border: '1px solid #10b98150',
                              color: '#34d399',
                              borderRadius: 6, padding: '4px 8px',
                              cursor: 'pointer', fontSize: 13,
                              fontWeight: 600,
                            }}
                            disabled={cb.status === 'calling'}
                          >
                             Ara
                          </button>
                          <button
                            onClick={() =>setModal({ mode: 'edit', item: cb })}
                            title="Düzenle"
                            style={{
                              background: '#1e3a8a30',
                              border: '1px solid #3b82f650',
                              color: '#60a5fa',
                              borderRadius: 6, padding: '4px 8px',
                              cursor: 'pointer', fontSize: 13,
                            }}
                          >
                            
                          </button>
                          <button
                            onClick={() =>handleDelete(cb.id)}
                            title="Sil"
                            style={{
                              background: '#7f1d1d30',
                              border: '1px solid #ef444450',
                              color: '#f87171',
                              borderRadius: 6, padding: '4px 8px',
                              cursor: 'pointer', fontSize: 13,
                            }}
                          >
                            
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>

        {/* ── Modal ── */}
        {modal && (
          <CallbackModal
            mode={modal.mode}
            initial={modal.item || {}}
            queues={queues}
            toast={toast}
            onClose={() =>setModal(null)}
            onSaved={() => { setModal(null); fetchAll(); }}
          />
        )}
      </div>
    );
  }

  window.CallbackTab = CallbackTab;
})();
