'use client'

import React, { useState, useEffect, useCallback } from 'react'
import Link from 'next/link'
import { useParams } from 'next/navigation'
import { AggregatePanel } from './_components/AggregatePanel'
import { StationCard } from './_components/StationCard'
import { TransferLine } from './_components/TransferLine'
import type { LineDashboard, StationDashboard, TransferInfo } from '../_types'
import { TRANSFER_COLORS } from '../_types'

/** Number of stations per visual row before wrapping */
const STATIONS_PER_ROW = 4

export default function LineDashboardPage() {
  const params = useParams()
  const lineId = params.lineId as string
  const [dashboard, setDashboard] = useState<LineDashboard | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [expandedStation, setExpandedStation] = useState<string | null>(null)

  const fetchDashboard = useCallback(async () => {
    try {
      const res = await fetch(`/api/sdk/v1/iace/production-lines/${lineId}/dashboard`)
      if (!res.ok) {
        setError('Produktionslinie konnte nicht geladen werden')
        return
      }
      const json = await res.json()
      setDashboard(json)
    } catch (err) {
      console.error('Failed to fetch line dashboard:', err)
      setError('Verbindung zum Backend fehlgeschlagen')
    } finally {
      setLoading(false)
    }
  }, [lineId])

  useEffect(() => {
    fetchDashboard()
  }, [fetchDashboard])

  function handleToggle(stationId: string) {
    setExpandedStation((prev) => (prev === stationId ? null : stationId))
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
      </div>
    )
  }

  if (error || !dashboard) {
    return (
      <div className="text-center py-12 space-y-3">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
          {error || 'Produktionslinie nicht gefunden'}
        </h2>
        <Link href="/sdk/iace/lines" className="text-purple-600 hover:text-purple-700">
          Zurueck zur Uebersicht
        </Link>
      </div>
    )
  }

  const sortedStations = [...dashboard.stations].sort(
    (a, b) => a.station.sort_order - b.station.sort_order
  )

  // Build rows of stations for display
  const rows = buildStationRows(sortedStations, STATIONS_PER_ROW)

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      {/* Back link */}
      <Link
        href="/sdk/iace/lines"
        className="inline-flex items-center gap-1 text-sm text-purple-600 hover:text-purple-700 dark:text-purple-400 dark:hover:text-purple-300 font-medium"
      >
        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
        </svg>
        Alle Produktionslinien
      </Link>

      {/* Aggregate panel */}
      <AggregatePanel dashboard={dashboard} />

      {/* Station flow */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
        <h2 className="text-sm font-semibold text-gray-900 dark:text-white mb-4">
          Stationsuebersicht
        </h2>

        <div className="space-y-6 overflow-x-auto">
          {rows.map((row, rowIndex) => (
            <StationRow
              key={rowIndex}
              stations={row}
              transfers={dashboard.transfers}
              expandedStation={expandedStation}
              onToggle={handleToggle}
              reversed={rowIndex % 2 === 1}
            />
          ))}
        </div>
      </div>
    </div>
  )
}

/** Split sorted stations into rows of N for layout */
function buildStationRows(
  stations: StationDashboard[],
  perRow: number
): StationDashboard[][] {
  const rows: StationDashboard[][] = []
  for (let i = 0; i < stations.length; i += perRow) {
    rows.push(stations.slice(i, i + perRow))
  }
  return rows
}

/** Find the transfer between two adjacent station sort orders */
function findTransfer(
  transfers: TransferInfo[],
  fromOrder: number,
  toOrder: number
): TransferInfo | null {
  return (
    transfers.find(
      (t) => t.from_station === fromOrder && t.to_station === toOrder
    ) || null
  )
}

/** Default transfer for stations without an explicit transfer entry */
function defaultTransfer(from: number, to: number): TransferInfo {
  return { from_station: from, to_station: to, type: 'conveyor', label: '' }
}

interface StationRowProps {
  stations: StationDashboard[]
  transfers: TransferInfo[]
  expandedStation: string | null
  onToggle: (id: string) => void
  reversed: boolean
}

function StationRow({ stations, transfers, expandedStation, onToggle, reversed }: StationRowProps) {
  // Reverse even rows for a serpentine layout
  const ordered = reversed ? [...stations].reverse() : stations

  return (
    <div className="flex items-start gap-0 overflow-x-auto pb-2">
      {ordered.map((station, idx) => {
        const nextStation = ordered[idx + 1]
        const transfer = nextStation
          ? findTransfer(
              transfers,
              station.station.sort_order,
              nextStation.station.sort_order
            ) ||
            findTransfer(
              transfers,
              nextStation.station.sort_order,
              station.station.sort_order
            ) ||
            defaultTransfer(station.station.sort_order, nextStation.station.sort_order)
          : null

        const transferColor = transfer
          ? TRANSFER_COLORS[transfer.type] || TRANSFER_COLORS.conveyor
          : '#22C55E'

        return (
          <React.Fragment key={station.station.id}>
            <StationCard
              station={station}
              expanded={expandedStation === station.station.id}
              onToggle={() => onToggle(station.station.id)}
            />
            {transfer && (
              <TransferLine transfer={transfer} color={transferColor} />
            )}
          </React.Fragment>
        )
      })}
    </div>
  )
}
