// TeamsTab.jsx — Takım Yönetimi
// Takım CRUD + üye atama arayüzü

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

  /* ── Team Modal ── */
  function TeamModal({ team, agents, onClose, onSave }) {
    const isEdit = !!team;
    const [name, setName] = useState(team?.name || '');
    const [leaderId, setLeaderId] = useState(team?.leader_id || '');
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');

    async function save() {
      setError('');
      if (!name.trim()) { setError('Takım adı zorunludur.'); return; }
      setSaving(true);
      try {
        const url = isEdit ? `/api/teams/${team.id}` : '/api/teams';
        const method = isEdit ? 'PUT' : 'POST';
        const body = { name: name.trim() };
        if (leaderId) body.leader_id = parseInt(leaderId);
        const r = await authFetch(url, {
          method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
        });
        if (!r.ok) { const err = await r.json(); throw new Error(err.detail || 'Hata olustu'); }
        onSave();
      } catch (e) { setError(e.message); } finally { setSaving(false); }
    }

    return (
      <div className="overlay" onClick={onClose}>
        <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 480 }}>
          <div className="modal-header">
            <span style={{ fontWeight:600, fontSize: 18 }}>{isEdit ? 'Takım Düzenle' : 'Yeni Takım'}</span>
            <button className="close-btn" onClick={onClose}>×</button>
          </div>
          <div className="modal-body">
            <div className="form-group">
              <label className="form-label">Takım Adı *</label>
              <input className="form-input" value={name} onChange={e =>setName(e.target.value)} placeholder="Örn: Satış Ekibi A" />
            </div>
            <div className="form-group">
              <label className="form-label">Takım Lideri</label>
              <select className="form-select" value={leaderId} onChange={e =>setLeaderId(e.target.value)}>
                <option value="">Lider Seçiniz</option>
                {agents.map(a => (
                  <option key={a.id} value={a.id}>{a.name} ({a.extension})</option>
                ))}
              </select>
            </div>
            {error && <div style={{ color: 'var(--red)', marginTop: 12 }}>! {error}</div>}
          </div>
          <div className="modal-footer">
            <button className="btn outline" onClick={onClose}>Iptal</button>
            <button className="btn primary" onClick={save} disabled={saving}>
              {saving ? 'Kaydediliyor...' : isEdit ? 'Güncelle' : 'Oluştur'}
            </button>
          </div>
        </div>
      </div>
    );
  }

  /* ── Members Modal ── */
  function MembersModal({ team, allAgents, onClose, onSave, toast }) {
    const [memberIds, setMemberIds] = useState(team.members ? team.members.map(m =>m.id) : []);
    const [search, setSearch] = useState('');
    const [saving, setSaving] = useState(false);

    const available = useMemo(() => {
      const q = search.toLowerCase();
      return allAgents.filter(a => {
        if (q && !a.name.toLowerCase().includes(q) && !a.extension.includes(q)) return false;
        return true;
      });
    }, [allAgents, search]);

    function toggle(id) {
      setMemberIds(prev =>prev.includes(id) ? prev.filter(x =>x !== id) : [...prev, id]);
    }

    async function save() {
      setSaving(true);
      try {
        const r = await authFetch(`/api/teams/${team.id}/members`, {
          method: 'PUT', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(memberIds),
        });
        if (!r.ok) { const err = await r.json(); throw new Error(err.detail || 'Hata'); }
        if (toast) toast('Takım üyeleri güncellendi', 'success');
        onSave();
      } catch (e) { if (toast) toast(e.message, 'error'); }
      finally { setSaving(false); }
    }

    return (
      <div className="overlay" onClick={onClose}>
        <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 600 }}>
          <div className="modal-header">
            <span style={{ fontWeight:600, fontSize: 18 }}>"{team.name}" Üyeleri</span>
            <button className="close-btn" onClick={onClose}>×</button>
          </div>
          <div className="modal-body">
            <div style={{ marginBottom: 12 }}>
              <input className="form-input" placeholder="Temsilci ara..." value={search}
                onChange={e =>setSearch(e.target.value)}
                style={{ width: '100%' }}
              />
            </div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 10 }}>
              {memberIds.length} üye seçili
            </div>
            <div style={{ maxHeight: 350, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 4 }}>
              {available.map(a => {
                const sel = memberIds.includes(a.id);
                const isLeader = team.leader_id === a.id;
                return (
                  <label key={a.id} style={{
                    display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px',
                    borderRadius: 8, cursor: 'pointer',
                    border: `1px solid ${sel ? 'rgba(88,166,255,.5)' : 'var(--border)'}`,
                    background: sel ? 'rgba(88,166,255,.08)' : 'var(--surface2)',
                    transition: 'all .15s',
                  }}>
                    <input type="checkbox" checked={sel} onChange={() =>toggle(a.id)}
                      style={{ accentColor: 'var(--blue)', width: 18, height: 18 }} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: sel ? 700 : 500, color: sel ? 'var(--blue)' : 'var(--text)', fontSize: 14 }}>
                        {a.name}
                        {isLeader && <span style={{ marginLeft: 8, fontSize: 11, color: '#f59e0b', fontWeight:600 }}>Lider</span>}
                      </div>
                      <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>
                        Dahili: {a.extension} {a.department ? `• ${a.department}` : ''}
                      </div>
                    </div>
                  </label>
                );
              })}
              {available.length === 0 && (
                <div style={{ padding: 20, textAlign: 'center', color: 'var(--text-dim)', fontSize: 13 }}>
                  Temsilci bulunamadı
                </div>
              )}
            </div>
          </div>
          <div className="modal-footer">
            <button className="btn outline" onClick={onClose}>Iptal</button>
            <button className="btn primary" onClick={save} disabled={saving}>
              {saving ? 'Kaydediliyor...' : 'Kaydet'}
            </button>
          </div>
        </div>
      </div>
    );
  }

  /* ═══════════════════════════════════════════════════════════════════════════
     MAIN: TeamsTab
     ═══════════════════════════════════════════════════════════════════════════ */
  function TeamsTab({ toast }) {
    const [teams, setTeams] = useState([]);
    const [agents, setAgents] = useState([]);
    const [loading, setLoading] = useState(true);
    const [teamModal, setTeamModal] = useState(null); // null | 'new' | team obj
    const [membersModal, setMembersModal] = useState(null); // null | team obj

    const loadData = useCallback(async () => {
      try {
        const [tR, aR] = await Promise.all([
          authFetch('/api/teams'),
          authFetch('/api/human-agents'),
        ]);
        const [tD, aD] = await Promise.all([
          tR.ok ? tR.json() : [],
          aR.ok ? aR.json() : [],
        ]);
        setTeams(Array.isArray(tD) ? tD : []);
        setAgents(Array.isArray(aD) ? aD.filter(a =>a.is_active) : []);
      } catch (e) { console.error('Teams load error:', e); }
      finally { setLoading(false); }
    }, []);

    useEffect(() => { loadData(); }, [loadData]);

    async function deleteTeam(id, name) {
      if (!confirm(`"${name}" takımını silmek istediğinize emin misiniz?`)) return;
      try {
        const r = await authFetch(`/api/teams/${id}`, { method: 'DELETE' });
        if (!r.ok && r.status !== 204) throw new Error('Silinemedi');
        if (toast) toast('Takım silindi', 'success');
        loadData();
      } catch (e) { if (toast) toast(e.message, 'error'); }
    }

    async function toggleActive(team) {
      try {
        const r = await authFetch(`/api/teams/${team.id}`, {
          method: 'PUT', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ is_active: !team.is_active }),
        });
        if (!r.ok) throw new Error('Güncellenemedi');
        loadData();
      } catch (e) { if (toast) toast(e.message, 'error'); }
    }

    if (loading) {
      return (
        <div className="fade-in" style={{ padding: 40, textAlign: 'center', color: 'var(--text-dim)' }}>
          Yükleniyor...
        </div>
      );
    }

    return (
      <div className="fade-in">
        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
          <div>
            <h2 style={{ fontSize: 24, fontWeight:600 }}>Takım Yönetimi</h2>
            <p style={{ fontSize: 14, color: 'var(--text-dim)', marginTop: 4 }}>
              {teams.length} takım tanımlı
            </p>
          </div>
          <button className="btn primary" onClick={() =>setTeamModal('new')}>
            + Yeni Takım
          </button>
        </div>

        {/* Teams Table */}
        <div style={{ overflowX: 'auto' }}>
          <table className="agent-table">
            <thead>
              <tr>
                <th>Takım Adı</th>
                <th>Lider</th>
                <th style={{ textAlign: 'center' }}>Üye Sayısı</th>
                <th>Üyeler</th>
                <th style={{ textAlign: 'center' }}>Durum</th>
                <th style={{ width: 260, minWidth: 260 }}>İşlem</th>
              </tr>
            </thead>
            <tbody>
              {teams.length === 0 && (
                <tr><td colSpan={6} className="dash-table-empty">Henüz takım tanımlanmamış.</td></tr>
              )}
              {teams.map(t => (
                <tr key={t.id}>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div style={{
                        width: 36, height: 36, borderRadius: 8,
                        background: t.is_active ? 'rgba(124,58,237,.1)' : 'rgba(100,116,139,.1)',
                        border: `2px solid ${t.is_active ? 'rgba(124,58,237,.3)' : 'rgba(100,116,139,.3)'}`,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: 16, flexShrink: 0,
                      }}></div>
                      <span style={{ fontWeight:600, fontSize: 15 }}>{t.name}</span>
                    </div>
                  </td>
                  <td>
                    {t.leader_name ? (
                      <span style={{ fontWeight: 600, color: '#f59e0b' }}>{t.leader_name}</span>
                    ) : (
                      <span style={{ color: 'var(--text-dim)', fontSize: 13 }}>Atanmamış</span>
                    )}
                  </td>
                  <td style={{ textAlign: 'center' }}>
                    <span style={{
                      display: 'inline-block', padding: '3px 12px', borderRadius: 20,
                      fontSize: 14, fontWeight:600,
                      background: t.member_count > 0 ? 'rgba(88,166,255,.1)' : 'var(--surface2)',
                      color: t.member_count > 0 ? 'var(--blue)' : 'var(--text-dim)',
                      border: `1px solid ${t.member_count > 0 ? 'rgba(88,166,255,.2)' : 'var(--border)'}`,
                    }}>{t.member_count}</span>
                  </td>
                  <td>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, maxWidth: 300 }}>
                      {t.members && t.members.length > 0
                        ? t.members.slice(0, 5).map(m => (
                            <span key={m.id} style={{
                              padding: '2px 8px', borderRadius: 5, fontSize: 11, fontWeight: 600,
                              background: t.leader_id === m.id ? 'rgba(245,158,11,.1)' : 'rgba(88,166,255,.1)',
                              color: t.leader_id === m.id ? '#f59e0b' : 'var(--blue)',
                              border: `1px solid ${t.leader_id === m.id ? 'rgba(245,158,11,.2)' : 'rgba(88,166,255,.2)'}`,
                            }}>
                              {m.name}{t.leader_id === m.id ? ' ' : ''}
                            </span>
                          ))
                        : <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>—</span>
                      }
                      {t.members && t.members.length > 5 && (
                        <span style={{ padding: '2px 8px', borderRadius: 5, fontSize: 11, fontWeight: 600, background: 'var(--surface2)', color: 'var(--text-dim)' }}>
                          +{t.members.length - 5}
                        </span>
                      )}
                    </div>
                  </td>
                  <td style={{ textAlign: 'center' }}>
                    <span style={{
                      display: 'inline-block', padding: '3px 10px', borderRadius: 6,
                      fontSize: 12, fontWeight:600,
                      background: t.is_active ? 'rgba(16,185,129,.1)' : 'rgba(239,68,68,.1)',
                      color: t.is_active ? '#10b981' : '#ef4444',
                      border: `1px solid ${t.is_active ? 'rgba(16,185,129,.2)' : 'rgba(239,68,68,.2)'}`,
                      cursor: 'pointer',
                    }} onClick={() =>toggleActive(t)} title="Durumu değiştirmek için tıklayın">
                      {t.is_active ? 'Aktif' : 'Pasif'}
                    </span>
                  </td>
                  <td style={{ whiteSpace: 'nowrap' }}>
                    <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                      <button onClick={() =>setMembersModal(t)}
                        style={{ padding: '6px 12px', borderRadius: 6, border: '1px solid rgba(124,58,237,.35)', background: 'rgba(124,58,237,.08)', cursor: 'pointer', fontSize: 12, fontWeight: 600, color: '#a78bfa', whiteSpace: 'nowrap' }}>
                         Üyeler
                      </button>
                      <button onClick={() =>setTeamModal(t)}
                        style={{ padding: '6px 12px', borderRadius: 6, border: '1px solid var(--border)', background: 'var(--surface)', cursor: 'pointer', fontSize: 12, fontWeight: 600, color: 'var(--text)', whiteSpace: 'nowrap' }}>
                         Düzenle
                      </button>
                      <button onClick={() =>deleteTeam(t.id, t.name)}
                        style={{ padding: '6px 12px', borderRadius: 6, border: '1px solid rgba(239,68,68,.35)', background: 'rgba(239,68,68,.06)', cursor: 'pointer', fontSize: 12, fontWeight: 600, color: '#ef4444', whiteSpace: 'nowrap' }}>
                         Sil
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Modals */}
        {teamModal && (
          <TeamModal
            team={teamModal === 'new' ? null : teamModal}
            agents={agents}
            onClose={() =>setTeamModal(null)}
            onSave={() => { if (toast) toast('Takım kaydedildi', 'success'); setTeamModal(null); loadData(); }}
          />
        )}
        {membersModal && (
          <MembersModal
            team={membersModal}
            allAgents={agents}
            onClose={() =>setMembersModal(null)}
            onSave={() => { setMembersModal(null); loadData(); }}
            toast={toast}
          />
        )}
      </div>
    );
  }

  window.TeamsTab = TeamsTab;
})();
