// Table View — Tablo Görünümü
const TVIcons       = window.Icons;
const TVStatusPill  = window.UI.StatusPill;
const TVPriority    = window.UI.Priority;
const TVTag         = window.UI.Tag;
const TV_STATUS_META = window.UI.STATUS_META;
const TV_PRIO_META   = window.UI.PRIORITY_META;
const { isOverdue: tvOverdue } = window.PMStore;

function fmtMinsTv(mins) {
  if (!mins) return null;
  const h = Math.floor(mins / 60), m = mins % 60;
  return m > 0 ? `${h}s ${m}dk` : `${h}s`;
}

function fmtDateTv(dateStr) {
  if (!dateStr) return null;
  const d = new Date(dateStr + 'T00:00:00');
  return d.toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' });
}

const TV_STATUS_ORDER = ['todo', 'doing', 'review', 'done'];
const TV_PRIO_ORDER   = ['high', 'medium', 'low'];

function TableView({ state, onSelectTask, onUpdateTask, onAddTask }) {
  const [sortBy,       setSortBy]       = React.useState('due');
  const [sortDir,      setSortDir]      = React.useState('asc');
  const [filterProj,   setFilterProj]   = React.useState('all');
  const [filterStatus, setFilterStatus] = React.useState('all');
  const [selected,     setSelected]     = React.useState(new Set());
  const [search,       setSearch]       = React.useState('');
  const [groupBy,      setGroupBy]      = React.useState('none');
  const [openCell,     setOpenCell]     = React.useState(null); // {id, field}

  const projects = state.projects || [];
  const projById = Object.fromEntries(projects.map(p => [p.id, p]));

  // ── Filtrele ──────────────────────────────────────────────
  let tasks = (state.tasks || []).filter(t => !t.archived);
  if (filterProj !== 'all')   tasks = tasks.filter(t => t.projectId === filterProj);
  if (filterStatus !== 'all') tasks = tasks.filter(t => t.status === filterStatus);
  if (search.trim()) {
    const q = search.toLowerCase();
    tasks = tasks.filter(t => t.title.toLowerCase().includes(q));
  }

  // ── Sırala ───────────────────────────────────────────────
  tasks = [...tasks].sort((a, b) => {
    let va, vb;
    if (sortBy === 'title')    { va = a.title || ''; vb = b.title || ''; }
    if (sortBy === 'status')   { va = TV_STATUS_ORDER.indexOf(a.status); vb = TV_STATUS_ORDER.indexOf(b.status); }
    if (sortBy === 'priority') { va = TV_PRIO_ORDER.indexOf(a.priority || 'medium'); vb = TV_PRIO_ORDER.indexOf(b.priority || 'medium'); }
    if (sortBy === 'due')      { va = a.due || '9999'; vb = b.due || '9999'; }
    if (sortBy === 'firm')     { va = projById[a.projectId]?.name || ''; vb = projById[b.projectId]?.name || ''; }
    if (sortBy === 'time')     { va = (a.timeLog||[]).reduce((s,e)=>s+(e.duration||0),0); vb = (b.timeLog||[]).reduce((s,e)=>s+(e.duration||0),0); }
    if (va == null) va = '';
    if (vb == null) vb = '';
    const cmp = typeof va === 'string' ? va.localeCompare(vb, 'tr') : va - vb;
    return sortDir === 'asc' ? cmp : -cmp;
  });

  const handleSort = (col) => {
    if (sortBy === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortBy(col); setSortDir('asc'); }
  };

  // ── Seçim ────────────────────────────────────────────────
  const toggleSel = (id, e) => {
    e.stopPropagation();
    const s = new Set(selected);
    s.has(id) ? s.delete(id) : s.add(id);
    setSelected(s);
  };
  const selAll = () => setSelected(
    selected.size === tasks.length ? new Set() : new Set(tasks.map(t => t.id))
  );
  const bulkSetStatus = (status) => {
    [...selected].forEach(id => onUpdateTask(id, { status }));
    setSelected(new Set());
  };

  // ── Gruplama ─────────────────────────────────────────────
  let groups = [];
  if (groupBy === 'firm') {
    const map = {};
    tasks.forEach(t => {
      const key = t.projectId || '__none';
      if (!map[key]) map[key] = [];
      map[key].push(t);
    });
    groups = Object.entries(map).map(([key, ts]) => ({
      label: key === '__none' ? 'Firma yok' : (projById[key]?.name || key),
      color: projById[key]?.color,
      tasks: ts,
    }));
  } else if (groupBy === 'status') {
    TV_STATUS_ORDER.forEach(sid => {
      const m = TV_STATUS_META[sid];
      const ts = tasks.filter(t => t.status === sid);
      if (ts.length > 0) groups.push({ label: m?.label || sid, color: m?.fg, tasks: ts });
    });
  } else {
    groups = [{ label: null, tasks }];
  }

  const colCount = 7 - (groupBy === 'firm' ? 1 : 0) - (groupBy === 'status' ? 1 : 0);
  const hasFilters = filterProj !== 'all' || filterStatus !== 'all' || !!search.trim();

  // ── Sütun başlığı ─────────────────────────────────────────
  const SortTH = ({ id, label, style }) => {
    const active = sortBy === id;
    return (
      <th
        className={`tv-th tv-th-sortable${active ? ' tv-th-active' : ''}`}
        style={style}
        onClick={() => handleSort(id)}
      >
        {label}
        <span className="tv-sort-icon">
          {active ? (sortDir === 'asc' ? ' ↑' : ' ↓') : ''}
        </span>
      </th>
    );
  };

  // ── Satır render ──────────────────────────────────────────
  const renderRow = (t) => {
    const proj     = projById[t.projectId];
    const ov       = tvOverdue(t.due, t.status);
    const timeMins = (t.timeLog||[]).reduce((s,e) => s + (e.duration||0), 0);
    const taskTags = (t.tags||[]).map(tid => (state.tags||[]).find(x=>x.id===tid)).filter(Boolean);
    const isSel    = selected.has(t.id);
    const isDone   = t.status === 'done';
    const isStatusOpen   = openCell?.id === t.id && openCell?.field === 'status';
    const isPriorityOpen = openCell?.id === t.id && openCell?.field === 'priority';

    return (
      <tr
        key={t.id}
        className={`tv-row${isSel ? ' tv-row-sel' : ''}${ov ? ' tv-row-ov' : ''}`}
        onClick={() => { setOpenCell(null); onSelectTask(t.id); }}
      >
        {/* ─ Checkbox ─ */}
        <td className="tv-td tv-td-check" onClick={e => toggleSel(t.id, e)}>
          <div className={`checkbox${isSel ? ' checked' : ''}`} style={{ width: 16, height: 16 }}>
            {isSel && <TVIcons.Check size={10} style={{ color: 'white' }} />}
          </div>
        </td>

        {/* ─ Başlık ─ */}
        <td className="tv-td tv-td-title">
          <span className={`tv-task-name${isDone ? ' tv-task-done' : ''}`}>
            {t.title}
          </span>
          {(t.subtasks?.length > 0) && (
            <span className="tv-sub-pill">
              {t.subtasks.filter(s=>s.done).length}/{t.subtasks.length}
            </span>
          )}
        </td>

        {/* ─ Firma ─ */}
        {groupBy !== 'firm' && (
          <td className="tv-td tv-td-firm" onClick={e => e.stopPropagation()}>
            {proj ? (
              <span className="tv-proj-badge" style={{ '--pc': proj.color || '#94a3b8', background: (proj.color||'#94a3b8')+'1e' }}>
                <span className="tv-proj-dot" />
                <span className="tv-proj-name">{proj.name}</span>
              </span>
            ) : <span className="tv-nil">—</span>}
          </td>
        )}

        {/* ─ Durum ─ */}
        {groupBy !== 'status' && (
          <td
            className="tv-td tv-td-status"
            onClick={e => { e.stopPropagation(); setOpenCell(isStatusOpen ? null : {id:t.id,field:'status'}); }}
          >
            <div className="tv-pill-wrap">
              <TVStatusPill status={t.status} />
              {isStatusOpen && (
                <div className="tv-pop" onClick={e => e.stopPropagation()}>
                  {TV_STATUS_ORDER.map(sid => {
                    const m = TV_STATUS_META[sid];
                    return (
                      <button
                        key={sid}
                        className={`tv-pop-item${t.status===sid?' tv-pop-active':''}`}
                        onClick={() => { onUpdateTask(t.id, {status:sid}); setOpenCell(null); }}
                      >
                        <span className="tv-pop-dot" style={{background:m?.fg}} />
                        {m?.label}
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          </td>
        )}

        {/* ─ Öncelik ─ */}
        <td
          className="tv-td tv-td-prio"
          onClick={e => { e.stopPropagation(); setOpenCell(isPriorityOpen ? null : {id:t.id,field:'priority'}); }}
        >
          <div className="tv-pill-wrap">
            <TVPriority value={t.priority || 'medium'} />
            {isPriorityOpen && (
              <div className="tv-pop" onClick={e => e.stopPropagation()}>
                {TV_PRIO_ORDER.map(pid => {
                  const m = TV_PRIO_META[pid];
                  const pColors = { high:'var(--p-high)', medium:'var(--p-med)', low:'var(--p-low)' };
                  return (
                    <button
                      key={pid}
                      className={`tv-pop-item${(t.priority||'medium')===pid?' tv-pop-active':''}`}
                      onClick={() => { onUpdateTask(t.id, {priority:pid}); setOpenCell(null); }}
                    >
                      <span className="tv-pop-dot" style={{background:pColors[pid]}} />
                      {m?.label}
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        </td>

        {/* ─ Teslim tarihi ─ */}
        <td className={`tv-td tv-td-due${ov ? ' tv-td-ov' : ''}`} onClick={e => e.stopPropagation()}>
          <label className="tv-date-label">
            {t.due
              ? <span className={`tv-date-text${ov ? ' tv-date-ov' : ''}`}>{fmtDateTv(t.due)}</span>
              : <span className="tv-nil tv-nil-hover">Tarih ekle</span>
            }
            <input
              type="date"
              className="tv-date-input"
              value={t.due || ''}
              onChange={e => onUpdateTask(t.id, { due: e.target.value || null })}
            />
          </label>
        </td>

        {/* ─ Süre ─ */}
        <td className="tv-td tv-td-time">
          {timeMins > 0
            ? <span className="tv-time-badge"><TVIcons.Timer size={11} />{fmtMinsTv(timeMins)}</span>
            : <span className="tv-nil">—</span>
          }
        </td>

        {/* ─ Etiketler ─ */}
        <td className="tv-td tv-td-tags" onClick={e => e.stopPropagation()}>
          <div className="tv-tags">
            {taskTags.slice(0, 2).map(tg => <TVTag key={tg.id} tag={tg} />)}
            {taskTags.length > 2 && (
              <span className="tv-tags-more">+{taskTags.length - 2}</span>
            )}
          </div>
        </td>

        {/* ─ Aç ─ */}
        <td className="tv-td tv-td-open" onClick={e => { e.stopPropagation(); onSelectTask(t.id); }}>
          <button className="tv-open-btn" tabIndex={-1} title="Görevi aç">
            <TVIcons.ExternalLink size={13} />
          </button>
        </td>
      </tr>
    );
  };

  // ─────────────────────────────────────────────────────────
  return (
    <div className="content tv-root" onClick={() => setOpenCell(null)}>

      {/* ── Araç Çubuğu ── */}
      <div className="tv-toolbar">
        <div className="tv-toolbar-left">
          <div className="tv-search">
            <TVIcons.Search size={13} className="tv-search-icon" />
            <input
              className="tv-search-inp"
              placeholder="Görev ara..."
              value={search}
              onChange={e => setSearch(e.target.value)}
            />
            {search && (
              <button className="tv-search-clear" onClick={() => setSearch('')}>
                <TVIcons.X size={11} />
              </button>
            )}
          </div>

          <select
            className="tv-filter-sel"
            value={filterProj}
            onChange={e => setFilterProj(e.target.value)}
          >
            <option value="all">Tüm firmalar</option>
            {projects.filter(p=>!p.archived).map(p =>
              <option key={p.id} value={p.id}>{p.name}</option>
            )}
          </select>

          <select
            className="tv-filter-sel"
            value={filterStatus}
            onChange={e => setFilterStatus(e.target.value)}
          >
            <option value="all">Tüm durumlar</option>
            {TV_STATUS_ORDER.map(sid => (
              <option key={sid} value={sid}>{TV_STATUS_META[sid]?.label}</option>
            ))}
          </select>

          {hasFilters && (
            <button
              className="tv-clear-btn"
              onClick={() => { setSearch(''); setFilterProj('all'); setFilterStatus('all'); }}
            >
              <TVIcons.X size={11} /> Temizle
            </button>
          )}
        </div>

        <div className="tv-toolbar-right">
          <span className="tv-count-badge">{tasks.length} görev</span>
          <select
            className="tv-filter-sel"
            value={groupBy}
            onChange={e => setGroupBy(e.target.value)}
          >
            <option value="none">Gruplama yok</option>
            <option value="firm">Firmaya göre grupla</option>
            <option value="status">Duruma göre grupla</option>
          </select>
        </div>
      </div>

      {/* ── Toplu işlem çubuğu ── */}
      {selected.size > 0 && (
        <div className="tv-bulk-bar">
          <span className="tv-bulk-info">
            <TVIcons.CheckSquare size={14} />
            {selected.size} görev seçildi
          </span>
          <div className="tv-bulk-actions">
            <span className="tv-bulk-label">Durum değiştir:</span>
            {TV_STATUS_ORDER.map(sid => {
              const m = TV_STATUS_META[sid];
              return (
                <button
                  key={sid}
                  className="tv-bulk-btn"
                  style={{ color: m?.fg, background: m?.bg }}
                  onClick={() => bulkSetStatus(sid)}
                >
                  {m?.label}
                </button>
              );
            })}
          </div>
          <button className="tv-bulk-dismiss" onClick={() => setSelected(new Set())}>
            <TVIcons.X size={12} /> Seçimi kaldır
          </button>
        </div>
      )}

      {/* ── Tablo kartı ── */}
      <div className="tv-card">
        <div className="tv-scroll">
          <table className="tv-table">
            <thead>
              <tr>
                {/* Check-all */}
                <th className="tv-th tv-th-check">
                  <div
                    className={`checkbox${selected.size===tasks.length&&tasks.length>0?' checked':''}`}
                    style={{ width: 16, height: 16 }}
                    onClick={selAll}
                  >
                    {selected.size===tasks.length&&tasks.length>0 &&
                      <TVIcons.Check size={10} style={{ color: 'white' }} />}
                  </div>
                </th>
                <SortTH id="title"    label="Görev"    style={{ minWidth: 240 }} />
                {groupBy !== 'firm'   && <SortTH id="firm"   label="Firma"   style={{ minWidth: 140 }} />}
                {groupBy !== 'status' && <SortTH id="status" label="Durum"   style={{ minWidth: 120 }} />}
                <SortTH id="priority" label="Öncelik"  style={{ minWidth: 100 }} />
                <SortTH id="due"      label="Teslim"   style={{ minWidth: 100 }} />
                <SortTH id="time"     label="Süre"     style={{ minWidth: 80 }} />
                <th className="tv-th" style={{ minWidth: 100 }}>Etiket</th>
                <th className="tv-th tv-th-open" />
              </tr>
            </thead>

            <tbody>
              {groups.map((group, gi) => (
                <React.Fragment key={gi}>
                  {group.label && (
                    <tr className="tv-group-row">
                      <td colSpan={colCount + 2}>
                        <div className="tv-group-inner">
                          <span className="tv-group-dot" style={{ background: group.color || 'var(--text-faint)' }} />
                          <span className="tv-group-name">{group.label}</span>
                          <span className="tv-group-count">{group.tasks.length}</span>
                        </div>
                      </td>
                    </tr>
                  )}
                  {group.tasks.map(t => renderRow(t))}
                </React.Fragment>
              ))}

              {/* Yeni görev satırı */}
              <tr className="tv-add-row">
                <td colSpan={colCount + 2}>
                  <button
                    className="tv-add-btn"
                    onClick={e => {
                      e.stopPropagation();
                      onAddTask({
                        projectId: filterProj !== 'all' ? filterProj : (state.activeProjectId || projects[0]?.id),
                        status:    filterStatus !== 'all' ? filterStatus : 'todo',
                      });
                    }}
                  >
                    <TVIcons.Plus size={14} />
                    Yeni görev ekle
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        {/* Boş durum */}
        {tasks.length === 0 && (
          <div className="tv-empty">
            <TVIcons.Table size={40} style={{ color: 'var(--border-strong)' }} />
            <p className="tv-empty-title">Görev bulunamadı</p>
            <span className="tv-empty-sub">
              {hasFilters ? 'Filtreleri değiştir veya temizle' : 'Yeni görev ekleyerek başla'}
            </span>
          </div>
        )}
      </div>
    </div>
  );
}

window.TableView = TableView;
