'use client'

import { useMemo, useState } from 'react'
import { Inbox } from 'lucide-react'
import { relativeTime, type Application, type Slot } from '@/lib/api/types'
import { Badge } from './Badge'
import { Pagination } from './Pagination'

interface AvailableSlotsProps {
  slots: Slot[]
  apps: Application[]
  onSelect: (application: Application) => void
}

const PAGE_SIZE = 6

export function AvailableSlots({ slots, apps, onSelect }: AvailableSlotsProps) {
  const [page, setPage] = useState(1)

  const available = useMemo(
    () => slots.filter((slot) => slot.available).sort((a, b) => +new Date(b.detectedAt) - +new Date(a.detectedAt)),
    [slots]
  )
  const start = (page - 1) * PAGE_SIZE
  const visible = available.slice(start, start + PAGE_SIZE)

  return (
    <section className="panel slots-page">
      <div className="panel-heading">
        <div>
          <h2>Available slots</h2>
          <p>Open appointment windows detected from your Amazon Jobs account.</p>
        </div>
        <Badge>{`${available.length} available`}</Badge>
      </div>

      {available.length === 0 ? (
        <div className="slots-empty">
          <Inbox size={28} />
          <b>No available slots yet</b>
          <p>
            When Amazon releases a shift or an appointment window for one of your applications, it will
            appear here the moment it is detected.
          </p>
        </div>
      ) : (
        <>
          <div className="slots-list">
            {visible.map((slot) => {
              const d = new Date(slot.date)
              const month = isNaN(d.getTime()) ? '—' : d.toLocaleString('en-GB', { month: 'short' }).toUpperCase()
              const day = isNaN(d.getTime()) ? '—' : d.getDate().toString()
              const app = apps.find((a) => a.id === slot.applicationId)
              return (
                <div className="slot-row" key={slot.id}>
                  <div className="slot-calendar">
                    <span>{month}</span>
                    <b>{day}</b>
                  </div>
                  <div>
                    <h3>{slot.location}</h3>
                    <p>
                      {slot.time} · {app?.jobTitle || slot.applicationId}
                    </p>
                  </div>
                  <div className="slot-detected">
                    <small>Detected</small>
                    <b suppressHydrationWarning>{relativeTime(slot.detectedAt)}</b>
                  </div>
                  <button
                    className="outline-button"
                    onClick={() => onSelect(app ?? apps[0])}
                  >
                    View application
                  </button>
                </div>
              )
            })}
          </div>
          <Pagination page={page} pageSize={PAGE_SIZE} total={available.length} onChange={setPage} />
        </>
      )}
    </section>
  )
}