import React from 'react'

import { COLUMNS, type BoardColumn, type BoardIssue, type IssueRef } from '../../data/fixtures.js'
import { Card, Tag, Badge, Tabs, IconButton, Input, Icon } from '../ui/index.js'
import { EmptyState } from '../shell/states.js'
import { GanttView } from './gantt-view.js'
import { DepsGraph } from './deps-graph.js'

// Board — kanban over inferred lifecycle, with Gantt/Dependencies stubs.
// `columns` defaults to demo fixtures; the shell passes real reconciled data
// when gitea is configured. `loading` covers the first reconcile.
export function BoardScreen({
  onOpenIssue,
  columns = COLUMNS,
  loading = false,
}: {
  onOpenIssue: (issue: IssueRef) => void
  columns?: BoardColumn[]
  loading?: boolean
}) {
  const [tab, setTab] = React.useState('board');
  const [query, setQuery] = React.useState('');
  const q = query.trim().toLowerCase();
  const filtered = columns.map((c) => ({ ...c, issues: q ? c.issues.filter((i) => (i.title + ' #' + i.id).toLowerCase().includes(q)) : c.issues }));
  const anyMatch = filtered.some((c) => c.issues.length > 0);
  const openCount = columns.reduce((n, c) => n + (c.id === 'done' ? 0 : c.issues.length), 0);

  const IssueCard = ({ issue }: { issue: BoardIssue }) => (
    <div
      onClick={() => onOpenIssue(issue)}
      style={{
        background: 'var(--surface-card)', border: '1px solid var(--line-1)',
        borderRadius: 'var(--radius-2)', padding: '10px 12px', cursor: 'pointer',
        boxShadow: 'var(--shadow-1)', display: 'flex', flexDirection: 'column', gap: 8,
      }}
      onMouseEnter={(e: React.MouseEvent<HTMLDivElement>) => { e.currentTarget.style.borderColor = 'var(--line-2)'; }}
      onMouseLeave={(e: React.MouseEvent<HTMLDivElement>) => { e.currentTarget.style.borderColor = 'var(--line-1)'; }}
    >
      <div style={{ font: 'var(--text-small)', fontWeight: 500, color: 'var(--ink-1)' }}>{issue.title}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
        <span style={{ font: '400 11.5px var(--font-mono)', color: 'var(--ink-3)' }}>#{issue.id}</span>
        {issue.labels.map((l) => <Tag key={l} label={l} style={{ transform: 'scale(0.95)', transformOrigin: 'left center' }} />)}
        {issue.days ? <span style={{ font: '400 11px var(--font-mono)', color: 'var(--warn)' }}>{issue.days}</span> : null}
        {issue.pr ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, font: '400 11px var(--font-mono)', color: 'var(--info)' }}><Icon name="git-pull-request" size={12} />{issue.pr}</span> : null}
        <span style={{
          marginLeft: 'auto', width: 20, height: 20, borderRadius: '50%',
          background: 'var(--spruce-2)', color: 'var(--accent-text)',
          font: '600 9px/20px var(--font-sans)', textAlign: 'center', flexShrink: 0,
        }}>{issue.who}</span>
      </div>
    </div>
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14, height: '100%', minHeight: 0 }}>
      <header style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12 }}>
        <h1 style={{ font: 'var(--text-display)', color: 'var(--ink-1)', margin: 0, whiteSpace: 'nowrap' }}>The pot</h1>
        <div style={{ width: 240 }}><Input icon="search" placeholder="Search the pot…" value={query} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setQuery(e.target.value)} /></div>
      </header>
      <Tabs
        items={[
          { id: 'board', label: 'Board', icon: 'square-kanban', count: openCount },
          { id: 'gantt', label: 'Gantt', icon: 'chart-no-axes-gantt' },
          { id: 'deps', label: 'Dependencies', icon: 'network' },
        ]}
        active={tab} onChange={setTab}
      />
      {tab === 'board' ? (
        loading ? (
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, color: 'var(--ink-3)' }}>
            <Icon name="loader-circle" size={16} />
            <span style={{ font: 'var(--text-small)' }}>Reconciling with gitea…</span>
          </div>
        ) : anyMatch ? (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, alignItems: 'start', flex: 1, minHeight: 0, overflow: 'auto' }}>
          {filtered.map((col) => (
            <div key={col.id} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '2px 2px 4px', borderBottom: '1px solid var(--line-1)', whiteSpace: 'nowrap' }}>
                <span style={{ font: 'var(--text-overline)', letterSpacing: 'var(--letter-spacing-wide)', textTransform: 'uppercase', color: 'var(--ink-2)' }}>{col.label}</span>
                <span style={{ font: '400 11px var(--font-mono)', color: 'var(--ink-3)' }}>{col.issues.length}</span>
              </div>
              {col.issues.map((i) => <IssueCard key={i.id} issue={i} />)}
            </div>
          ))}
        </div>
        ) : (
          <div style={{ flex: 1, border: '1px dashed var(--line-2)', borderRadius: 'var(--radius-3)' }}>
            <EmptyState icon="search" title="Nothing by that name"
              line={`The pot holds ${columns.reduce((n, c) => n + c.issues.length, 0)} issues; none of them answer to “${query.trim()}”.`} />
          </div>
        )
      ) : tab === 'deps' ? (
        <DepsGraph onOpenIssue={onOpenIssue} />
      ) : (
        <GanttView onOpenIssue={onOpenIssue} />
      )}
    </div>
  );
}
