import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import Link from 'next/link'
import { STATIONS, LINE_COLOURS, LINE_LABELS, STATUS_COLOURS, STATUS_LABELS } from '@/lib/stations'

export async function generateStaticParams() {
  const seen = new Set<string>()
  return STATIONS.filter(s => {
    if (seen.has(s.slug)) return false
    seen.add(s.slug)
    return true
  }).map(s => ({ slug: s.slug }))
}

export async function generateMetadata({ params }: { params: { slug: string } }): Promise<Metadata> {
  const station = STATIONS.find(s => s.slug === params.slug)
  if (!station) return { title: 'Station not found' }
  return {
    title: `${station.name} — Plymouth Metro`,
    description: station.description,
  }
}

const STATUS_BG = {
  open:             'bg-green-50 border-green-200',
  'disused-station':'bg-amber-50 border-amber-200',
  'disused-trackbed':'bg-red-50 border-red-200',
  'new-build':       'bg-gray-50 border-gray-200',
}
const STATUS_TEXT = {
  open:             'text-green-800',
  'disused-station':'text-amber-800',
  'disused-trackbed':'text-red-800',
  'new-build':       'text-gray-700',
}

export default function StationPage({ params }: { params: { slug: string } }) {
  const station = STATIONS.find(s => s.slug === params.slug)
  if (!station) notFound()

  // Find all lines this station appears on
  const allLines = STATIONS.filter(s => s.slug === params.slug)
  // Find nearby stations on the same primary line
  const lineStations = STATIONS.filter(s => s.line === station.line)
  const idx = lineStations.findIndex(s => s.id === station.id)
  const prev = idx > 0 ? lineStations[idx - 1] : null
  const next = idx < lineStations.length - 1 ? lineStations[idx + 1] : null

  return (
    <>
      {/* Hero */}
      <section className="bg-hero-gradient text-white py-14 sm:py-18">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center gap-2 mb-4 text-sm text-white/60">
            <Link href="/stations" className="hover:text-white transition-colors">Stations</Link>
            <span>/</span>
            <span>{station.name}</span>
          </div>
          <div className="flex items-start gap-4">
            <div className="flex-shrink-0 mt-1">
              {allLines.map(l => (
                <div key={l.line} className="w-5 h-5 rounded-full mb-1 border-2 border-white"
                     style={{ background: LINE_COLOURS[l.line] }} />
              ))}
            </div>
            <div>
              <h1 className="text-4xl sm:text-5xl font-black mb-3">{station.name}</h1>
              <div className="flex flex-wrap gap-2">
                {allLines.map(l => (
                  <span key={l.line} className="text-sm font-semibold px-3 py-1 rounded-full bg-white/15 text-white">
                    {LINE_LABELS[l.line]}
                  </span>
                ))}
                <span className="text-sm px-3 py-1 rounded-full bg-white/10 text-white/75">Zone {station.zone}</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Status banner */}
      <div className={`py-4 px-4 border-b ${STATUS_BG[station.status]}`}>
        <div className="max-w-7xl mx-auto px-2 sm:px-4 flex items-center gap-3">
          <span className="w-3 h-3 rounded-full flex-shrink-0" style={{ background: STATUS_COLOURS[station.status] }} />
          <p className={`font-semibold text-sm ${STATUS_TEXT[station.status]}`}>
            {STATUS_LABELS[station.status]}
            {station.closedYear ? ` — closed ${station.closedYear}` : ''}
          </p>
        </div>
      </div>

      {/* Main content */}
      <section className="py-14 bg-white">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">

            {/* Left — description */}
            <div className="md:col-span-2">
              <h2 className="text-xl font-bold text-metro-navy mb-4">About this station</h2>
              <p className="text-metro-muted leading-relaxed mb-6">{station.description}</p>

              {station.notes && (
                <div className="bg-metro-light rounded-xl p-4 border border-metro-border mb-6">
                  <p className="text-sm font-semibold text-metro-navy mb-1">Key note</p>
                  <p className="text-sm text-metro-muted leading-relaxed">{station.notes}</p>
                </div>
              )}

              {/* What this means */}
              <h3 className="text-lg font-bold text-metro-navy mb-3 mt-8">What this means for Plymouth</h3>
              {station.status === 'open' && (
                <p className="text-metro-muted leading-relaxed">
                  This station is already open and operational. As part of Plymouth Metro, it would benefit from increased service frequencies, better connections to other parts of the network, and integration with the wider rapid transit system.
                </p>
              )}
              {station.status === 'disused-station' && (
                <p className="text-metro-muted leading-relaxed">
                  Because the mainline track still runs through this site, reopening a halt here is considerably cheaper than new-build infrastructure. The track, signalling, and much of the alignment is already in place — new platforms and station facilities are the main requirement. This station represents a genuine &quot;quick win&quot; for Plymouth Metro.
                </p>
              )}
              {station.status === 'disused-trackbed' && (
                <p className="text-metro-muted leading-relaxed">
                  This station closed some decades ago and the original infrastructure has been removed or built over. Reopening would require new track, platforms, and potentially new land acquisition. However, the historical precedent and existing community demand make it a viable long-term proposal.
                </p>
              )}
              {station.status === 'new-build' && (
                <p className="text-metro-muted leading-relaxed">
                  This is a completely new station proposal with no historical railway precedent at this location. It would require new infrastructure investment but would serve communities and destinations currently with no rail access at all — representing Plymouth Metro&apos;s most transformative and ambitious element.
                </p>
              )}
            </div>

            {/* Right — details panel */}
            <div className="space-y-4">
              <div className="card">
                <h3 className="font-bold text-metro-navy text-sm mb-3">Station details</h3>
                <div className="space-y-2.5 text-sm">
                  <div className="flex justify-between">
                    <span className="text-metro-muted">Zone</span>
                    <span className="font-medium text-metro-navy">{station.zone}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-metro-muted">Status</span>
                    <span className="font-medium" style={{ color: STATUS_COLOURS[station.status] }}>
                      {STATUS_LABELS[station.status]}
                    </span>
                  </div>
                  {station.closedYear && (
                    <div className="flex justify-between">
                      <span className="text-metro-muted">Closed</span>
                      <span className="font-medium text-metro-navy">{station.closedYear}</span>
                    </div>
                  )}
                  {station.interchange && (
                    <div className="flex justify-between">
                      <span className="text-metro-muted">Type</span>
                      <span className="font-medium text-metro-blue">Interchange</span>
                    </div>
                  )}
                </div>
              </div>

              {/* Lines serving */}
              <div className="card">
                <h3 className="font-bold text-metro-navy text-sm mb-3">Lines serving this station</h3>
                <div className="space-y-2">
                  {allLines.map(l => (
                    <div key={l.line} className="flex items-center gap-2">
                      <span className="w-3 h-3 rounded-full flex-shrink-0" style={{ background: LINE_COLOURS[l.line] }} />
                      <span className="text-xs text-metro-muted">{LINE_LABELS[l.line]}</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Sign CTA */}
              <div className="rounded-xl p-4 text-white text-center" style={{ background: LINE_COLOURS[station.line] }}>
                <p className="font-bold text-sm mb-1">Support this station</p>
                <p className="text-xs text-white/80 mb-3">Sign the petition to help make {station.name} part of Plymouth Metro.</p>
                <Link href="/support" className="block bg-white rounded-lg py-2 px-4 text-xs font-bold" style={{ color: LINE_COLOURS[station.line] }}>
                  Sign the Petition
                </Link>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Previous / Next navigation */}
      <section className="py-8 bg-metro-light border-t border-metro-border">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between gap-4">
            {prev ? (
              <Link href={`/stations/${prev.slug}`} className="flex items-center gap-2 text-sm font-semibold text-metro-sky hover:text-metro-blue transition-colors">
                ← {prev.name}
              </Link>
            ) : <span />}
            <Link href="/stations" className="text-sm text-metro-muted hover:text-metro-navy transition-colors">
              All stations
            </Link>
            {next ? (
              <Link href={`/stations/${next.slug}`} className="flex items-center gap-2 text-sm font-semibold text-metro-sky hover:text-metro-blue transition-colors">
                {next.name} →
              </Link>
            ) : <span />}
          </div>
        </div>
      </section>
    </>
  )
}
