import { useState, useEffect } from 'react';
import { sheets } from '../lib/api';

const STATUS_META = {
  done:        { label: 'Done',        cls: 'done',   color: 'var(--green-text)', bg: 'var(--green-bg)' },
  in_progress: { label: 'In progress', cls: 'inprog', color: 'var(--blue-text)',  bg: 'var(--blue-bg)'  },
  in_review:   { label: 'In review',   cls: 'review', color: 'var(--amber-text)', bg: 'var(--amber-bg)' },
  todo:        { label: 'To do',       cls: 'todo',   color: 'var(--text2)',      bg: 'var(--surface2)' },
  other:       { label: '—',           cls: 'todo',   color: 'var(--text3)',      bg: 'var(--surface2)' },
};

const PRIORITY_COLOR = {
  high:   'var(--red-text)',
  medium: 'var(--amber-text)',
  low:    'var(--text3)',
};

function StatusBadge({ status, rawStatus }) {
  const m = STATUS_META[status] || STATUS_META.other;
  return (
    <span style={{ fontSize: 11, fontWeight: 500, padding: '2px 8px', borderRadius: 20, background: m.bg, color: m.color, whiteSpace: 'nowrap' }}>
      {rawStatus || m.label}
    </span>
  );
}

function ProgressBar({ summary }) {
  const { total, done, inProgress, inReview, todo, pctDone } = summary;
  if (total === 0) return null;
  const pctIp  = Math.round((inProgress / total) * 100);
  const pctRev = Math.round((inReview   / total) * 100);
  const pctTd  = Math.round((todo       / total) * 100);
  return (
    <div>
      <div style={{ display: 'flex', height: 6, borderRadius: 3, overflow: 'hidden', background: 'var(--surface2)', marginBottom: 6 }}>
        <div style={{ width: pctDone + '%', background: 'var(--green)',  transition: 'width .4s' }} />
        <div style={{ width: pctIp   + '%', background: 'var(--blue)',   transition: 'width .4s' }} />
        <div style={{ width: pctRev  + '%', background: 'var(--amber)',  transition: 'width .4s' }} />
        <div style={{ width: pctTd   + '%', background: 'var(--border2)',transition: 'width .4s' }} />
      </div>
      <div style={{ display: 'flex', gap: 12, fontSize: 11, color: 'var(--text2)', flexWrap: 'wrap' }}>
        <span style={{ color: 'var(--green-text)', fontWeight: 500 }}>{pctDone}% done</span>
        {inProgress > 0 && <span>{inProgress} in progress</span>}
        {inReview   > 0 && <span>{inReview} in review</span>}
        {todo       > 0 && <span>{todo} to do</span>}
        <span style={{ marginLeft: 'auto', color: 'var(--text3)' }}>{total} total</span>
      </div>
    </div>
  );
}

function SheetTable({ rows, headers }) {
  const [statusFilter, setStatusFilter] = useState('all');

  const filtered = statusFilter === 'all' ? rows : rows.filter(r => r.status === statusFilter);

  // Decide which raw columns to show in the table
  // Skip columns we already show as dedicated fields (task, status, assignee, dueDate, priority)
  const skipCols = new Set(['task', 'title', 'name', 'item', 'description', 'topic',
    'status', 'state', 'progress', 'done', 'completed',
    'assignee', 'owner', 'assigned to', 'person', 'who',
    'due date', 'due', 'deadline',
    'priority', 'importance', 'level',
  ].map(s => s.toLowerCase()));

  const extraHeaders = headers.filter(h => !skipCols.has(h.toLowerCase()));

  return (
    <div>
      {/* Status filter pills */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 10, flexWrap: 'wrap' }}>
        {['all','todo','in_progress','in_review','done'].map(s => {
          const m = STATUS_META[s] || { label: 'All', bg: 'var(--surface2)', color: 'var(--text2)' };
          const count = s === 'all' ? rows.length : rows.filter(r => r.status === s).length;
          if (s !== 'all' && count === 0) return null;
          return (
            <button key={s} onClick={() => setStatusFilter(s)}
              style={{ fontSize: 11, padding: '3px 10px', borderRadius: 20, border: '0.5px solid var(--border2)', cursor: 'pointer',
                background: statusFilter === s ? (s === 'all' ? 'var(--surface)' : m.bg) : 'transparent',
                color:      statusFilter === s ? (s === 'all' ? 'var(--text)'    : m.color) : 'var(--text2)',
                fontWeight: statusFilter === s ? 500 : 400 }}>
              {s === 'all' ? 'All' : m.label} ({count})
            </button>
          );
        })}
      </div>

      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', tableLayout: 'auto' }}>
          <thead>
            <tr>
              <th style={thStyle}>Task</th>
              <th style={thStyle}>Status</th>
              {extraHeaders.slice(0, 5).map(h => <th key={h} style={thStyle}>{h}</th>)}
              {rows.some(r => r.assignee) && <th style={{ ...thStyle, textAlign: 'right' }}>Assignee</th>}
              {rows.some(r => r.dueDate)  && <th style={{ ...thStyle, textAlign: 'right' }}>Due</th>}
              {rows.some(r => r.priority) && <th style={{ ...thStyle, textAlign: 'right' }}>Priority</th>}
            </tr>
          </thead>
          <tbody>
            {filtered.map((row, i) => (
              <tr key={i} style={{ borderBottom: '0.5px solid var(--border)', transition: 'background .1s' }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--surface2)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <td style={tdStyle}>
                  <div style={{ fontWeight: 500, fontSize: 12, color: 'var(--text)', lineHeight: 1.4 }}>
                    {row.task || '—'}
                  </div>
                  {row.overdue && (
                    <span style={{ fontSize: 10, color: 'var(--red-text)', marginTop: 2, display: 'block' }}>⚠ Overdue</span>
                  )}
                  {row.notes && (
                    <div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 2, lineHeight: 1.3 }}>{row.notes}</div>
                  )}
                </td>
                <td style={tdStyle}><StatusBadge status={row.status} rawStatus={row.rawStatus} /></td>
                {extraHeaders.slice(0, 5).map(h => (
                  <td key={h} style={{ ...tdStyle, fontSize: 11, color: 'var(--text2)', maxWidth: 160 }}>
                    {row._raw[h] || '—'}
                  </td>
                ))}
                {rows.some(r => r.assignee) && (
                  <td style={{ ...tdStyle, textAlign: 'right', fontSize: 11, color: 'var(--text2)' }}>
                    {row.assignee || '—'}
                  </td>
                )}
                {rows.some(r => r.dueDate) && (
                  <td style={{ ...tdStyle, textAlign: 'right', fontSize: 11, color: row.overdue ? 'var(--red-text)' : 'var(--text2)', whiteSpace: 'nowrap' }}>
                    {row.dueDate || '—'}
                  </td>
                )}
                {rows.some(r => r.priority) && (
                  <td style={{ ...tdStyle, textAlign: 'right', fontSize: 11,
                    color: PRIORITY_COLOR[row.priority?.toLowerCase()] || 'var(--text2)', fontWeight: 500 }}>
                    {row.priority || '—'}
                  </td>
                )}
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan={20} style={{ padding: '20px 0', textAlign: 'center', fontSize: 12, color: 'var(--text3)' }}>No rows match.</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

const thStyle = { fontSize: 11, fontWeight: 500, color: 'var(--text2)', textAlign: 'left', padding: '0 8px 8px', borderBottom: '0.5px solid var(--border)', whiteSpace: 'nowrap' };
const tdStyle = { padding: '8px 8px', verticalAlign: 'top' };

export default function SheetsPanel() {
  const [sheetsData, setSheetsData] = useState([]);
  const [loading, setLoading]       = useState(true);
  const [error, setError]           = useState(null);
  const [activeSheet, setActiveSheet] = useState(null);
  const [expanded, setExpanded]     = useState({});

  useEffect(() => {
    setLoading(true);
    sheets.all()
      .then(data => {
        setSheetsData(data);
        if (data.length > 0) setActiveSheet(data[0].id);
        setError(null);
      })
      .catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return (
    <div>
      {[0,1,2].map(i => <div key={i} className="skeleton" style={{ height: 80, borderRadius: 8, marginBottom: 10 }} />)}
    </div>
  );

  if (error || sheetsData.length === 0) return (
    <div style={{ background: 'var(--surface)', border: '0.5px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: 24 }}>
      <div style={{ fontWeight: 500, marginBottom: 8, fontSize: 14 }}>Connect your Google Sheets</div>
      <p style={{ fontSize: 13, color: 'var(--text2)', lineHeight: 1.6, marginBottom: 16 }}>
        Add your spreadsheet IDs to <code style={{ background: 'var(--surface2)', padding: '1px 5px', borderRadius: 4 }}>.env</code> to see your weekly plan, content calendar, and link building tracker here.
      </p>
      <div style={{ background: 'var(--surface2)', borderRadius: 'var(--radius)', padding: '12px 14px', fontFamily: 'monospace', fontSize: 12, color: 'var(--text)', lineHeight: 1.8 }}>
        <div style={{ color: 'var(--text3)', marginBottom: 4 }}># In your .env file:</div>
        <div>GOOGLE_SHEETS='[</div>
        <div>&nbsp;&nbsp;{'{'}{"\"id\":\"1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms\",\"name\":\"Weekly Plan\",\"tab\":\"Sheet1\",\"color\":\"#378ADD\""}{'}'},</div>
        <div>&nbsp;&nbsp;{'{'}{"\"id\":\"your_content_sheet_id\",\"name\":\"Content Calendar\",\"tab\":\"Sheet1\",\"color\":\"#1D9E75\""}{'}'},</div>
        <div>&nbsp;&nbsp;{'{'}{"\"id\":\"your_links_sheet_id\",\"name\":\"Link Building\",\"tab\":\"Sheet1\",\"color\":\"#D85A30\""}{'}'}</div>
        <div>]'</div>
      </div>
      <div style={{ marginTop: 12, fontSize: 12, color: 'var(--text2)', lineHeight: 1.6 }}>
        Then share each spreadsheet with your service account email and enable the <strong>Google Sheets API</strong> in Google Cloud Console.
      </div>
    </div>
  );

  const activeData = sheetsData.find(s => s.id === activeSheet);

  return (
    <div>
      {/* Summary cards across all sheets */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px,1fr))', gap: 10, marginBottom: 16 }}>
        {sheetsData.map(s => (
          <div key={s.id}
            onClick={() => setActiveSheet(s.id)}
            style={{ background: activeSheet === s.id ? 'var(--surface)' : 'var(--surface2)', border: `0.5px solid ${activeSheet === s.id ? (s.color || 'var(--blue)') : 'var(--border)'}`, borderRadius: 'var(--radius-lg)', padding: '12px 14px', cursor: 'pointer', transition: 'all .15s' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 8 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: s.color || '#378ADD', flexShrink: 0 }} />
              <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</span>
            </div>
            {s.error
              ? <span style={{ fontSize: 11, color: 'var(--red-text)' }}>⚠ {s.error.slice(0, 40)}</span>
              : <ProgressBar summary={s.summary} />
            }
          </div>
        ))}
      </div>

      {/* Active sheet detail */}
      {activeData && !activeData.error && (
        <div style={{ background: 'var(--surface)', border: '0.5px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 10, height: 10, borderRadius: '50%', background: activeData.color || '#378ADD' }} />
              <span style={{ fontWeight: 500, fontSize: 14 }}>{activeData.name}</span>
              <span style={{ fontSize: 11, color: 'var(--text3)' }}>· {activeData.sheetTab}</span>
            </div>
            <span style={{ fontSize: 11, color: 'var(--text3)' }}>{activeData.summary.total} rows</span>
          </div>

          <div style={{ marginBottom: 14 }}>
            <ProgressBar summary={activeData.summary} />
          </div>

          {activeData.rows.length > 0
            ? <SheetTable rows={activeData.rows} headers={activeData.headers} />
            : <p style={{ fontSize: 12, color: 'var(--text3)', padding: '12px 0' }}>No data rows found in this sheet.</p>
          }

          <div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 12 }}>
            Source: Google Sheets · Read-only · Auto-refreshes every 2 minutes
          </div>
        </div>
      )}

      {activeData?.error && (
        <div style={{ background: 'var(--red-bg)', border: '0.5px solid var(--red-text)', borderRadius: 'var(--radius)', padding: 14, fontSize: 12, color: 'var(--red-text)' }}>
          Could not load "{activeData.name}": {activeData.error}
          <div style={{ marginTop: 6, color: 'var(--text2)' }}>Make sure the spreadsheet is shared with your service account email and the Google Sheets API is enabled.</div>
        </div>
      )}
    </div>
  );
}
