import { Link, useNavigate } from 'react-router-dom'
import { useQuery, useMutation } from '@tanstack/react-query'
import { useMemo, useState, useEffect, useRef } from 'react'
import {
  BarChart, Bar, AreaChart, Area, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
} from 'recharts'
import GridLayout, { WidthProvider } from 'react-grid-layout'
import 'react-grid-layout/css/styles.css'
import 'react-resizable/css/styles.css'
import { startOfWeek, format, subWeeks, eachWeekOfInterval, subDays, addDays } from 'date-fns'
import api from '../utils/api'
import StatCard from '../components/ui/StatCard'
import ActivityMap from '../components/activity/ActivityMap'
import {
  formatDuration, formatDistance, formatHeartRate, formatElevation,
  formatDate, sportIcon, formatSleep,
} from '../utils/format'
import { BB_INFERRED_COLOR, BB_INFERRED_LABEL, bbLevelColor, inferBBType } from '../utils/bodyBattery'

const Grid = WidthProvider(GridLayout)

const MEDALS = { 1: '🥇', 2: '🥈', 3: '🥉' }

const HRV_PALETTE = {
  balanced:   'text-green-400  bg-green-400/10  border-green-400/30',
  unbalanced: 'text-orange-400 bg-orange-400/10 border-orange-400/30',
  low:        'text-red-400    bg-red-400/10    border-red-400/30',
  poor:       'text-red-400    bg-red-400/10    border-red-400/30',
}

// Widget registry + default grid positions (12-col grid). minW/minH keep widgets usable.
const WIDGETS = [
  { id: 'stats',       default: { x: 0, y: 0,  w: 12, h: 1 }, minW: 4, minH: 1 },
  { id: 'weekly',      default: { x: 0, y: 1,  w: 6,  h: 3 }, minW: 4, minH: 2 },
  { id: 'bodyBattery', default: { x: 6, y: 1,  w: 3,  h: 3 }, minW: 3, minH: 2 },
  { id: 'vo2max',      default: { x: 9, y: 1,  w: 3,  h: 3 }, minW: 2, minH: 2 },
  { id: 'sleep',       default: { x: 0, y: 4,  w: 5,  h: 3 }, minW: 3, minH: 2 },
  { id: 'hrv',         default: { x: 5, y: 4,  w: 3,  h: 2 }, minW: 2, minH: 2 },
  { id: 'featured',    default: { x: 0, y: 7,  w: 8,  h: 5 }, minW: 4, minH: 3 },
  { id: 'recent',      default: { x: 8, y: 7,  w: 4,  h: 5 }, minW: 3, minH: 3 },
  { id: 'prs',         default: { x: 0, y: 12, w: 12, h: 2 }, minW: 4, minH: 2 },
]

// Merge a saved layout with the registry: keep saved positions for known widgets,
// fall back to defaults for any widget the saved layout doesn't include (e.g. new ones).
function buildLayout(saved) {
  const byId = Object.fromEntries((saved || []).map(l => [l.i, l]))
  return WIDGETS.map(w => {
    const s = byId[w.id]
    const pos = s ? { x: s.x, y: s.y, w: s.w, h: s.h } : w.default
    return { i: w.id, ...pos, minW: w.minW, minH: w.minH }
  })
}

// ── Widgets ──────────────────────────────────────────────────────────────────

function Card({ title, viewHref, children, className = '' }) {
  return (
    <div className={`bg-gray-900 rounded-xl border border-gray-800 p-4 h-full flex flex-col ${className}`}>
      {title && (
        <div className="flex items-center justify-between mb-2">
          <h3 className="text-sm font-medium text-gray-300">{title}</h3>
          {viewHref && <Link to={viewHref} className="text-xs text-blue-400 hover:underline">View →</Link>}
        </div>
      )}
      <div className="flex-1 min-h-0">{children}</div>
    </div>
  )
}

function Stat({ label, value }) {
  return (
    <div className="bg-gray-900 px-4 py-3 flex flex-col justify-center">
      <p className="text-xs text-gray-500">{label}</p>
      <p className="text-lg font-semibold text-white">{value}</p>
    </div>
  )
}

function StatsRow({ health, ytdStats }) {
  return (
    <div className="grid grid-cols-2 sm:grid-cols-5 gap-3 h-full">
      <StatCard label="Steps today" value={health.steps != null ? health.steps.toLocaleString() : '--'} accent="green" sub="goal 10,000" />
      <StatCard label="Running this year" value={ytdStats ? `${ytdStats.running_km.toFixed(0)} km` : '--'} accent="blue" />
      <StatCard label="Cycling this year" value={ytdStats ? `${ytdStats.cycling_km.toFixed(0)} km` : '--'} accent="orange" />
      <StatCard label="Resting HR" value={formatHeartRate(health.resting_hr)} accent="red" />
      <StatCard label="Sleep" value={formatSleep(health.sleep_duration_s)} />
    </div>
  )
}

function MiniBodyBattery({ bb, hires, sleepStart, sleepEnd }) {
  const raw = (hires?.length ? hires : bb?.values || []).map(([ts, level]) => ({ ts, level }))
  const sleepStartMs = sleepStart ? new Date(sleepStart).getTime() : null
  const sleepEndMs   = sleepEnd   ? new Date(sleepEnd).getTime()   : null
  const data = raw.map((d, i) => ({
    ...d,
    type: inferBBType(d.ts, d.level, i > 0 ? raw[i - 1].level : null, sleepStartMs, sleepEndMs),
  }))
  const charged = bb?.charged, drained = bb?.drained, end_level = bb?.end_level
  const peak = data.length ? Math.max(...data.map(d => d.level)) : end_level
  const hasGraph = data.length >= 2
  const presentTypes = [...new Set(data.map(d => d.type))]

  return (
    <Card title="Body Battery" viewHref="/health">
      <div className="flex items-baseline gap-3 flex-wrap">
        {peak != null && (
          <span className="text-3xl font-bold" style={{ color: bbLevelColor(peak) }}>{Math.round(peak)}</span>
        )}
        {charged != null && <span className="text-sm font-semibold text-green-400">+{charged}</span>}
        {drained != null && <span className="text-sm font-semibold text-orange-400">-{drained}</span>}
        {end_level != null && <span className="text-xs text-gray-500">now {Math.round(end_level)}</span>}
      </div>
      {hasGraph ? (
        <>
          <div className="mt-3 flex-1 min-h-0">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={data} margin={{ top: 2, right: 0, bottom: 0, left: 0 }} barCategoryGap={0}>
                <YAxis domain={[0, 100]} hide />
                <Tooltip
                  contentStyle={{ background: '#111827', border: '1px solid #374151', borderRadius: 6, fontSize: 11, color: '#fff' }}
                  itemStyle={{ color: '#fff' }} labelStyle={{ color: '#fff' }}
                  labelFormatter={ts => format(new Date(ts), 'HH:mm')}
                  formatter={v => [`${Math.round(v)}%`, 'Battery']}
                />
                <Bar dataKey="level" isAnimationActive={false} radius={0}>
                  {data.map((d, i) => <Cell key={i} fill={BB_INFERRED_COLOR[d.type]} />)}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
          <div className="flex flex-wrap gap-x-3 gap-y-1 mt-2">
            {presentTypes.map(type => (
              <div key={type} className="flex items-center gap-1">
                <div className="w-2 h-2 rounded-sm" style={{ backgroundColor: BB_INFERRED_COLOR[type] }} />
                <span className="text-xs text-gray-500">{BB_INFERRED_LABEL[type]}</span>
              </div>
            ))}
          </div>
        </>
      ) : (
        <p className="text-xs text-gray-600 mt-3">No body battery data today</p>
      )}
    </Card>
  )
}

function Vo2MaxWidget({ health, recentHealth }) {
  const series = useMemo(
    () => [...(recentHealth || [])]
      .filter(d => d.vo2max != null)
      .sort((a, b) => new Date(a.date) - new Date(b.date))
      .map(d => ({ date: d.date, v: d.vo2max })),
    [recentHealth],
  )
  return (
    <Card title="VO₂ Max" viewHref="/health">
      <div className="flex items-baseline gap-2">
        <span className="text-3xl font-bold text-blue-400">{health.vo2max != null ? health.vo2max.toFixed(1) : '--'}</span>
        <span className="text-xs text-gray-500">ml/kg/min</span>
      </div>
      {health.fitness_age != null && (
        <p className="text-xs text-gray-500 mt-0.5">Fitness age {health.fitness_age}</p>
      )}
      {series.length >= 2 && (
        <div className="flex-1 min-h-0 mt-2">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={series} margin={{ top: 4, right: 2, bottom: 0, left: 0 }}>
              <defs>
                <linearGradient id="grad-dash-vo2" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
                  <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                </linearGradient>
              </defs>
              <YAxis domain={['dataMin - 1', 'dataMax + 1']} hide />
              <Tooltip contentStyle={{ background: '#111827', border: '1px solid #374151', borderRadius: 6, fontSize: 11 }}
                labelFormatter={d => format(new Date(d), 'MMM d')} formatter={v => [v.toFixed(1), 'VO₂ max']} />
              <Area type="monotone" dataKey="v" stroke="#3b82f6" strokeWidth={2} fill="url(#grad-dash-vo2)"
                dot={false} connectNulls isAnimationActive={false} />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      )}
    </Card>
  )
}

const SLEEP_STAGES = [
  { key: 'sleep_deep_s',  label: 'Deep',  color: '#3b82f6' },
  { key: 'sleep_rem_s',   label: 'REM',   color: '#8b5cf6' },
  { key: 'sleep_light_s', label: 'Light', color: '#60a5fa' },
  { key: 'sleep_awake_s', label: 'Awake', color: '#6b7280' },
]

function SleepMini({ health }) {
  const total = SLEEP_STAGES.reduce((s, st) => s + (health[st.key] || 0), 0)
  return (
    <Card title="Sleep" viewHref="/health">
      <div className="flex items-baseline gap-3 flex-wrap">
        <span className="text-3xl font-bold text-indigo-300">{formatSleep(health.sleep_duration_s)}</span>
        {health.sleep_score != null && (
          <span className="text-sm text-gray-400">score <span className="text-white font-semibold">{Math.round(health.sleep_score)}</span></span>
        )}
      </div>
      {total > 0 ? (
        <>
          <div className="flex h-3 rounded-full overflow-hidden gap-0.5 mt-3">
            {SLEEP_STAGES.map(st => {
              const pct = ((health[st.key] || 0) / total) * 100
              if (pct < 0.5) return null
              return <div key={st.key} style={{ width: `${pct}%`, backgroundColor: st.color }} title={`${st.label}: ${formatSleep(health[st.key])}`} />
            })}
          </div>
          <div className="flex flex-wrap gap-x-3 gap-y-1 mt-2">
            {SLEEP_STAGES.map(st => (health[st.key] ? (
              <div key={st.key} className="flex items-center gap-1.5">
                <div className="w-2.5 h-2.5 rounded-sm" style={{ backgroundColor: st.color }} />
                <span className="text-xs text-gray-400">{st.label}</span>
                <span className="text-xs text-white">{formatSleep(health[st.key])}</span>
              </div>
            ) : null))}
          </div>
        </>
      ) : (
        <p className="text-xs text-gray-600 mt-3">No sleep stages for last night</p>
      )}
    </Card>
  )
}

function HrvWidget({ health }) {
  const status = health.hrv_status
  const cls = status ? (HRV_PALETTE[status.toLowerCase()] || 'text-gray-400 bg-gray-400/10 border-gray-400/30') : null
  return (
    <Card title="HRV status" viewHref="/health">
      <div className="flex flex-col items-start justify-center h-full gap-2">
        <div className="flex items-baseline gap-2">
          <span className="text-3xl font-bold text-violet-300">{health.hrv_nightly_avg != null ? Math.round(health.hrv_nightly_avg) : '--'}</span>
          <span className="text-xs text-gray-500">ms</span>
        </div>
        {status
          ? <span className={`text-xs px-2 py-0.5 rounded-full border ${cls}`}>{status}</span>
          : <span className="text-xs text-gray-600">No HRV status</span>}
      </div>
    </Card>
  )
}

function WeeklyChart({ activities }) {
  const navigate = useNavigate()
  if (!activities?.length) return (
    <div className="flex items-center justify-center h-full text-gray-600 text-sm">No activities yet</div>
  )
  const now = new Date()
  const weeks = eachWeekOfInterval({ start: subWeeks(startOfWeek(now), 7), end: startOfWeek(now) })
  const data = weeks.map(weekStart => {
    const weekEnd = addDays(weekStart, 7)
    const km = activities
      .filter(a => { const t = new Date(a.start_time); return t >= weekStart && t < weekEnd })
      .reduce((s, a) => s + (a.distance_m || 0) / 1000, 0)
    return {
      week: format(weekStart, 'MMM d'),
      km: parseFloat(km.toFixed(2)),
      weekStartISO: format(weekStart, 'yyyy-MM-dd'),
      weekEndISO: format(weekEnd, 'yyyy-MM-dd'),
    }
  })
  const handleBarClick = (entry) => {
    const p = entry?.activePayload?.[0]?.payload
    if (p) navigate(`/activities?from=${p.weekStartISO}&to=${p.weekEndISO}`)
  }
  return (
    <ResponsiveContainer width="100%" height="100%">
      <BarChart data={data} margin={{ top: 4, right: 4, bottom: 4, left: 0 }} barSize={20}
        onClick={handleBarClick} style={{ cursor: 'pointer' }}>
        <CartesianGrid strokeDasharray="3 3" stroke="#1f2937" vertical={false} />
        <XAxis dataKey="week" tick={{ fontSize: 10, fill: '#6b7280' }} axisLine={false} tickLine={false} />
        <YAxis tick={{ fontSize: 10, fill: '#6b7280' }} axisLine={false} tickLine={false} width={28}
          tickFormatter={v => `${v.toFixed(0)}`} />
        <Tooltip contentStyle={{ background: '#111827', border: '1px solid #374151', borderRadius: 8, fontSize: 12 }}
          formatter={(v) => [`${v.toFixed(1)} km`, 'Distance']} cursor={{ fill: 'rgba(59,130,246,0.1)' }} />
        <Bar dataKey="km" fill="#3b82f6" radius={[3, 3, 0, 0]} isAnimationActive={false} />
      </BarChart>
    </ResponsiveContainer>
  )
}

function FeaturedActivity({ activity, segments }) {
  if (!activity) return (
    <Card title="Latest activity"><div className="flex items-center justify-center h-full text-gray-600 text-sm">No activities yet</div></Card>
  )
  return (
    <div className="bg-gray-900 rounded-xl border border-gray-800 overflow-hidden h-full flex flex-col">
      <div className="flex items-center justify-between px-4 py-3 border-b border-gray-800">
        <div className="flex items-center gap-2 min-w-0">
          <span className="text-xl">{sportIcon(activity.sport_type)}</span>
          <div className="min-w-0">
            <Link to={`/activities/${activity.id}`} className="text-sm font-semibold text-white hover:text-blue-400 transition-colors truncate block">
              {activity.name}
            </Link>
            <p className="text-xs text-gray-500">{formatDate(activity.start_time)}</p>
          </div>
        </div>
        <Link to={`/activities/${activity.id}`} className="text-xs text-blue-400 hover:underline flex-shrink-0">Open →</Link>
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-3 flex-1 min-h-0">
        <div className="lg:col-span-2 min-h-[180px] bg-gray-950">
          {activity.polyline
            ? <ActivityMap polyline={activity.polyline} sportType={activity.sport_type} colorMode="solid" />
            : <div className="flex items-center justify-center h-full text-gray-600 text-sm">No GPS track</div>}
        </div>
        <div className="grid grid-cols-2 lg:grid-cols-1 gap-px bg-gray-800/50 content-start">
          <Stat label="Distance" value={formatDistance(activity.distance_m)} />
          <Stat label="Elevation ↑" value={formatElevation(activity.elevation_gain_m)} />
          <Stat label="Moving time" value={formatDuration(activity.moving_time_s ?? activity.duration_s)} />
          <Stat label="Calories" value={activity.calories ? `${Math.round(activity.calories)} kcal` : '--'} />
        </div>
      </div>
      {segments?.length > 0 && (
        <div className="border-t border-gray-800 px-4 py-3">
          <div className="flex items-center justify-between mb-2">
            <h4 className="text-xs font-medium text-gray-400 uppercase tracking-wide">Segments</h4>
            <Link to={`/activities/${activity.id}`} className="text-xs text-blue-400 hover:underline">Details →</Link>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-1.5">
            {segments.map(seg => {
              const isPodium = seg.rank && seg.rank <= 3
              const delta = seg.best_s != null ? seg.duration_s - seg.best_s : null
              return (
                <div key={seg.segment_id} className="flex items-center gap-2 text-sm">
                  <span className="flex-1 text-gray-300 text-xs truncate">{seg.name}</span>
                  <span className={`font-mono text-xs ${isPodium ? 'text-yellow-400 font-semibold' : 'text-gray-200'}`}>
                    {formatDuration(seg.duration_s)}
                  </span>
                  <span className="w-8 text-right text-xs">
                    {isPodium
                      ? <span title={`#${seg.rank} of ${seg.effort_count}`}>{MEDALS[seg.rank]}</span>
                      : delta != null
                        ? <span className="text-red-400 font-mono">+{formatDuration(delta)}</span>
                        : <span className="text-gray-700">--</span>}
                  </span>
                </div>
              )
            })}
          </div>
        </div>
      )}
    </div>
  )
}

function RecentActivities({ activities }) {
  return (
    <Card title="Recent activities" viewHref="/activities">
      <div className="space-y-2 overflow-auto h-full">
        {activities?.slice(0, 6).map(activity => (
          <Link key={activity.id} to={`/activities/${activity.id}`}
            className="flex items-center gap-3 py-2 border-b border-gray-800/50 hover:bg-gray-800/30 rounded-lg px-2 -mx-2 transition-colors">
            <span className="text-lg">{sportIcon(activity.sport_type)}</span>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-medium text-white truncate">{activity.name}</p>
              <p className="text-xs text-gray-500">{formatDate(activity.start_time)}</p>
            </div>
            <div className="text-right text-sm">
              <p className="text-gray-200">{formatDistance(activity.distance_m)}</p>
              <p className="text-xs text-red-400">{formatHeartRate(activity.avg_heart_rate)}</p>
            </div>
          </Link>
        ))}
        {!activities?.length && (
          <p className="text-gray-600 text-sm text-center py-8">
            No activities yet — <Link to="/upload" className="text-blue-400 hover:underline">import some data</Link>
          </p>
        )}
      </div>
    </Card>
  )
}

function RunningPRs({ records }) {
  return (
    <Card title="Running PRs" viewHref="/records">
      {records?.length > 0 ? (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
          {records.slice(0, 5).map(rec => (
            <div key={rec.id} className="bg-gray-800/60 rounded-lg p-3 text-center">
              <p className="text-xs text-gray-500 mb-1">{rec.distance_label}</p>
              <p className="font-mono font-semibold text-yellow-400">{formatDuration(rec.duration_s)}</p>
            </div>
          ))}
        </div>
      ) : (
        <div className="flex items-center justify-center h-full text-gray-600 text-sm">No running records yet</div>
      )}
    </Card>
  )
}

// ── Page ───────────────────────────────────────────────────────────────────

export default function DashboardPage() {
  const { data: recentActivities } = useQuery({
    queryKey: ['activities-recent'],
    queryFn: () => api.get('/activities/', { params: { per_page: 10 } }).then(r => r.data),
  })

  const { data: allActivities } = useQuery({
    queryKey: ['activities-all-chart'],
    queryFn: () =>
      api.get('/activities/', { params: { per_page: 100, from_date: subDays(new Date(), 60).toISOString() } }).then(r => r.data),
  })

  const { data: recentHealth } = useQuery({
    queryKey: ['health-metrics', 'dash'],
    queryFn: () => api.get('/health-metrics/', { params: { limit: 365 } }).then(r => r.data),
  })

  const { data: profile } = useQuery({
    queryKey: ['profile'],
    queryFn: () => api.get('/profile/').then(r => r.data),
  })

  const health = useMemo(() => {
    const rows = [...(recentHealth || [])].sort((a, b) => new Date(b.date) - new Date(a.date))
    const pick = f => rows.find(d => d[f] != null)?.[f] ?? null
    const latest = rows[0] || {}
    return {
      date: rows[0]?.date ? rows[0].date.slice(0, 10) : null,
      resting_hr: pick('resting_hr'),
      sleep_duration_s: pick('sleep_duration_s'),
      sleep_start: latest.sleep_start ?? null,
      sleep_end: latest.sleep_end ?? null,
      // Sleep stages + score for the latest night (same row as sleep_start).
      sleep_deep_s: latest.sleep_deep_s ?? null,
      sleep_rem_s: latest.sleep_rem_s ?? null,
      sleep_light_s: latest.sleep_light_s ?? null,
      sleep_awake_s: latest.sleep_awake_s ?? null,
      sleep_score: pick('sleep_score'),
      hrv_nightly_avg: pick('hrv_nightly_avg'),
      hrv_status: pick('hrv_status'),
      steps: pick('steps'),
      vo2max: pick('vo2max'),
      fitness_age: pick('fitness_age'),
      avg_stress: pick('avg_stress'),
    }
  }, [recentHealth])

  const { data: intraday } = useQuery({
    queryKey: ['health-intraday-dash', health.date],
    queryFn: () => api.get('/health-metrics/intraday', { params: { date: health.date } }).then(r => r.data),
    enabled: !!health.date,
  })

  const { data: records } = useQuery({
    queryKey: ['records-running'],
    queryFn: () => api.get('/records/', { params: { sport_type: 'running' } }).then(r => r.data),
  })

  const { data: ytdStats } = useQuery({
    queryKey: ['ytd-stats'],
    queryFn: () => api.get('/activities/stats/ytd').then(r => r.data),
  })

  const featured = recentActivities?.[0]
  const { data: featuredSegments } = useQuery({
    queryKey: ['activity-segments', featured?.id],
    queryFn: () => api.get(`/segments/by-activity/${featured.id}`).then(r => r.data),
    enabled: !!featured?.id,
  })

  // ── Layout state ──────────────────────────────────────────────────────────
  const [editMode, setEditMode] = useState(false)
  const [layout, setLayout] = useState(() => buildLayout(null))
  const saveTimer = useRef(null)
  const loadedRef = useRef(false)

  // Apply the saved layout once the profile loads.
  useEffect(() => {
    if (profile && !loadedRef.current) {
      loadedRef.current = true
      setLayout(buildLayout(profile.dashboard_layout))
    }
  }, [profile])

  const saveLayout = useMutation({
    mutationFn: (lay) =>
      api.put('/profile/dashboard-layout', { layout: lay.map(({ i, x, y, w, h }) => ({ i, x, y, w, h })) }),
  })

  const handleLayoutChange = (next) => {
    setLayout(next)
    if (editMode) {
      clearTimeout(saveTimer.current)
      saveTimer.current = setTimeout(() => saveLayout.mutate(next), 700)
    }
  }

  const finishEditing = () => {
    clearTimeout(saveTimer.current)
    saveLayout.mutate(layout)
    setEditMode(false)
  }

  const resetLayout = () => {
    const def = buildLayout(null)
    setLayout(def)
    saveLayout.mutate(def)
  }

  const WIDGET_CONTENT = {
    stats:       <StatsRow health={health} ytdStats={ytdStats} />,
    weekly:      <Card title="Weekly distance (km)"><WeeklyChart activities={allActivities} /></Card>,
    bodyBattery: <MiniBodyBattery bb={intraday?.body_battery} hires={intraday?.body_battery_hires} sleepStart={health.sleep_start} sleepEnd={health.sleep_end} />,
    vo2max:      <Vo2MaxWidget health={health} recentHealth={recentHealth} />,
    sleep:       <SleepMini health={health} />,
    hrv:         <HrvWidget health={health} />,
    featured:    <FeaturedActivity activity={featured} segments={featuredSegments} />,
    recent:      <RecentActivities activities={recentActivities} />,
    prs:         <RunningPRs records={records} />,
  }

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-4">
        <h1 className="text-2xl font-bold text-white">Dashboard</h1>
        <div className="flex items-center gap-3">
          {editMode && (
            <button onClick={resetLayout} className="text-xs text-gray-400 hover:text-white transition-colors">Reset layout</button>
          )}
          <button
            onClick={() => (editMode ? finishEditing() : setEditMode(true))}
            className={`text-sm font-medium px-3 py-1.5 rounded-lg transition-colors ${
              editMode ? 'bg-blue-600 hover:bg-blue-500 text-white' : 'bg-gray-800 hover:bg-gray-700 text-gray-200'
            }`}>
            {editMode ? '✓ Done' : '✎ Edit dashboard'}
          </button>
          <Link to="/upload" className="text-sm text-blue-400 hover:text-blue-300 transition-colors">+ Import data</Link>
        </div>
      </div>

      {editMode && (
        <p className="text-xs text-gray-500 mb-3">Drag widgets to move them, or drag a corner to resize. Changes save automatically.</p>
      )}

      <Grid
        className="layout"
        layout={layout}
        cols={12}
        rowHeight={80}
        margin={[16, 16]}
        isDraggable={editMode}
        isResizable={editMode}
        onLayoutChange={handleLayoutChange}
        compactType="vertical"
      >
        {WIDGETS.map(w => (
          <div key={w.id}
            className={`rounded-xl ${editMode ? 'ring-2 ring-blue-500/40 cursor-move' : ''}`}>
            <div className={`h-full ${editMode ? 'pointer-events-none select-none' : ''}`}>
              {WIDGET_CONTENT[w.id]}
            </div>
          </div>
        ))}
      </Grid>
    </div>
  )
}
