import { useEffect, useState } from 'react'
import { CircleCheck, AlertTriangle, Plug, Bookmark as BookmarkIcon, LogIn } from 'lucide-react'
import { api, type Event, type Resource, type Integration } from '../lib/api'

const cardBase: React.CSSProperties = {
  backgroundColor: 'rgba(10, 10, 12, 0.92)',
  border: '1px solid rgba(200, 164, 52, 0.08)',
  borderRadius: '12px',
  padding: '20px',
  boxShadow: '0 0 20px rgba(200, 164, 52, 0.03)',
  transition: 'border-color 0.2s ease',
  position: 'relative',
  overflow: 'hidden',
  height: '100%',
  display: 'flex',
  flexDirection: 'column',
}

const statusColor: Record<string, string> = {
  healthy: '#C8A434',
  warning: '#E67E22',
  critical: '#E74C3C',
  unknown: '#7A7D85',
}

const eventIcons: Record<string, typeof CircleCheck> = {
  integration_created: Plug,
  integration_tested: CircleCheck,
  integration_deleted: Plug,
  bookmark_created: BookmarkIcon,
  bookmark_deleted: BookmarkIcon,
  user_login: LogIn,
  account_created: LogIn,
}

function timeAgo(iso: string) {
  const diffMs = Date.now() - new Date(iso.replace(' ', 'T') + 'Z').getTime()
  const mins = Math.floor(diffMs / 60000)
  if (mins < 1) return 'just now'
  if (mins < 60) return `${mins}m ago`
  const hours = Math.floor(mins / 60)
  if (hours < 24) return `${hours}h ago`
  return `${Math.floor(hours / 24)}d ago`
}

export default function MiddleRow() {
  const [resources, setResources] = useState<Resource[] | null>(null)
  const [events, setEvents] = useState<Event[] | null>(null)
  const [integrations, setIntegrations] = useState<Integration[] | null>(null)

  useEffect(() => {
    api.listResources().then(({ resources }) => setResources(resources))
    api.listEvents(5).then(({ events }) => setEvents(events))
    api.listIntegrations().then(({ integrations }) => setIntegrations(integrations))
  }, [])

  const erroredIntegrations = integrations?.filter((i) => i.status === 'error') ?? []
  const problemResources = resources?.filter((r) => r.status === 'warning' || r.status === 'critical') ?? []

  return (
    <div className="grid h-full w-full grid-cols-[1fr_1.4fr_1fr] gap-6">
      {/* Resource Overview */}
      <div style={cardBase} className="hover:!border-gold/15 group">
        <div style={{ position: 'absolute', inset: 0, opacity: 0.03, backgroundImage: 'radial-gradient(circle, #C8A434 1px, transparent 1px)', backgroundSize: '20px 20px', pointerEvents: 'none' }} />
        <div style={{ position: 'absolute', top: 0, left: '10%', right: '10%', height: '1px', background: 'linear-gradient(90deg, transparent, rgba(200,164,52,0.15), transparent)', pointerEvents: 'none' }} />

        <div className="relative z-10 flex flex-1 flex-col">
          <h3 style={{ fontSize: '11px', textTransform: 'uppercase', letterSpacing: '1.5px', color: '#7A7D85', fontWeight: 500, marginBottom: '16px' }}>
            Resource Overview
          </h3>
          {resources === null ? (
            <p style={{ fontSize: '12px', color: '#7A7D85' }}>Loading…</p>
          ) : resources.length === 0 ? (
            <p style={{ fontSize: '12px', color: '#7A7D85' }}>Connect an integration in Settings to see live resources here.</p>
          ) : (
            <div className="flex flex-1 flex-col justify-around gap-3" style={{ overflowY: 'auto' }}>
              {resources.slice(0, 6).map((r, i) => (
                <div key={i} className="flex items-center gap-2.5">
                  <span style={{ width: '7px', height: '7px', borderRadius: '50%', backgroundColor: statusColor[r.status], flexShrink: 0 }} />
                  <span style={{ fontSize: '13px', color: '#E8E6E0', flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.name}</span>
                  <span style={{ fontSize: '10px', color: '#7A7D85', flexShrink: 0 }}>{r.integration}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Recent Activity */}
      <div style={cardBase} className="hover:!border-gold/15 group">
        <div style={{ position: 'absolute', inset: 0, opacity: 0.02, backgroundImage: 'linear-gradient(rgba(200,164,52,0.3) 1px, transparent 1px), linear-gradient(90deg, rgba(200,164,52,0.3) 1px, transparent 1px)', backgroundSize: '40px 40px', pointerEvents: 'none' }} />
        <div style={{ position: 'absolute', top: 0, left: '5%', right: '5%', height: '1px', background: 'linear-gradient(90deg, transparent, rgba(200,164,52,0.2), transparent)', pointerEvents: 'none' }} />

        <div className="relative z-10 flex flex-1 flex-col">
          <h3 style={{ fontSize: '11px', textTransform: 'uppercase', letterSpacing: '1.5px', color: '#7A7D85', fontWeight: 500, marginBottom: '16px' }}>
            Recent Activity
          </h3>
          {events === null ? (
            <p style={{ fontSize: '12px', color: '#7A7D85' }}>Loading…</p>
          ) : events.length === 0 ? (
            <p style={{ fontSize: '12px', color: '#7A7D85' }}>No activity yet.</p>
          ) : (
            <div className="flex flex-1 flex-col justify-around gap-3">
              {events.map((item) => {
                const Icon = eventIcons[item.type] ?? CircleCheck
                return (
                  <div key={item.id} className="flex items-start gap-3">
                    <div style={{ width: '28px', height: '28px', borderRadius: '6px', backgroundColor: 'rgba(200,164,52,0.06)', border: '1px solid rgba(200,164,52,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, boxShadow: '0 0 8px rgba(200,164,52,0.04)' }}>
                      <Icon size={13} style={{ color: '#C8A434' }} />
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <p style={{ fontSize: '13px', color: '#E8E6E0', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.title}</p>
                      {item.source && <p style={{ fontSize: '11px', color: '#7A7D85', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.source}</p>}
                    </div>
                    <span style={{ fontSize: '11px', color: '#7A7D85', flexShrink: 0 }}>{timeAgo(item.created_at)}</span>
                  </div>
                )
              })}
            </div>
          )}
        </div>
      </div>

      {/* Top Alerts */}
      <div style={cardBase} className="hover:!border-gold/15 group">
        <div style={{ position: 'absolute', top: 0, left: '10%', right: '10%', height: '1px', background: 'linear-gradient(90deg, transparent, rgba(231,126,34,0.15), transparent)', pointerEvents: 'none' }} />

        <div className="relative z-10 flex flex-1 flex-col">
          <h3 style={{ fontSize: '11px', textTransform: 'uppercase', letterSpacing: '1.5px', color: '#7A7D85', fontWeight: 500, marginBottom: '16px' }}>
            Top Alerts
          </h3>
          {erroredIntegrations.length === 0 && problemResources.length === 0 ? (
            <p style={{ fontSize: '12px', color: '#7A7D85' }}>No alerts — everything connected is healthy.</p>
          ) : (
            <div className="flex flex-1 flex-col justify-around gap-3">
              {erroredIntegrations.map((i) => (
                <div key={`int-${i.id}`} className="flex items-start gap-3">
                  <AlertTriangle size={14} style={{ color: '#E74C3C', flexShrink: 0, marginTop: '2px' }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <p style={{ fontSize: '13px', color: '#E8E6E0', fontWeight: 500 }}>Connection failing</p>
                    <p style={{ fontSize: '11px', color: '#7A7D85' }}>{i.name}</p>
                  </div>
                </div>
              ))}
              {problemResources.map((r, idx) => (
                <div key={`res-${idx}`} className="flex items-start gap-3">
                  <AlertTriangle size={14} style={{ color: r.status === 'critical' ? '#E74C3C' : '#E67E22', flexShrink: 0, marginTop: '2px' }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <p style={{ fontSize: '13px', color: '#E8E6E0', fontWeight: 500 }}>{r.name}</p>
                    <p style={{ fontSize: '11px', color: '#7A7D85' }}>{r.integration} · {r.detail ?? r.status}</p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
