'use client'

import Link from 'next/link'
import { ArrowLeft, Pencil } from 'lucide-react'
import { formatSupplierLine2 } from '@/lib/format/supplier'
import DemoBadge from '@/components/demo/demo-badge'
import { TYPE_LABELS } from '@/lib/project-types/labels'

interface SupplierMeta {
  supplier_name?: string | null
  supplier_number?: string | null
  city?: string | null
  country?: string | null
}

interface ProjectStatus {
  id: string
  code: string
  label: string
}

interface ProjectTypeAssignment {
  project_type_code: string
}

// Implementierte Auftragstypen → modul-spezifischer URL-Pfad
const IMPLEMENTED_TYPE_ROUTES: Record<string, (projectId: string) => string> = {
  lsc_workshop: (id) => `/lsc-workshop/${id}`,
  fabrikanalyse: (id) => `/fabrikanalyse/${id}`,
  kapa_workshop: (id) => `/lsc-workshop/${id}/kapa`,
}

const COMING_SOON_TYPES = new Set(['sonderauftrag', 'zdsc_campus', '360_workshop'])

const STATUS_HEADER_COLORS: Record<string, string> = {
  status_10: 'bg-blue-400/20 text-blue-200',
  status_20: 'bg-red-400/20 text-red-200',
  status_40: 'bg-amber-400/20 text-amber-200',
  status_70: 'bg-teal-400/20 text-teal-200',
  status_100: 'bg-green-400/20 text-green-200',
}

interface ProjectHeaderProps {
  project: {
    id: string
    project_code: string | null
    supplier_name: string
    plant_location?: string | null
    visit_date?: string | null
    is_demo?: boolean
    supplier_master_data: SupplierMeta | SupplierMeta[] | null
    project_statuses?: ProjectStatus | ProjectStatus[] | null
    project_type_assignments?: ProjectTypeAssignment[]
  }
  /** Default '/projektanlage'. Override e.g. '/lsc-workshop' or '/fabrikanalyse' */
  backHref?: string
  /** Default true. Hide for read-only contexts. */
  showEditButton?: boolean
  /** Type-Code to visually emphasize in the type-tag list (e.g. 'lsc_workshop' inside LSC module) */
  highlightedTypeCode?: string | null
  /** Optional slot for tab-bar (rendered as second row inside sticky header) */
  tabs?: React.ReactNode
  /** Optional slot for additional actions (next to edit button) */
  actions?: React.ReactNode
}

function resolveOne<T>(v: T | T[] | null | undefined): T | null {
  if (!v) return null
  return Array.isArray(v) ? (v[0] ?? null) : v
}

export default function ProjectHeader({
  project,
  backHref = '/projektanlage',
  showEditButton = true,
  highlightedTypeCode = null,
  tabs,
  actions,
}: ProjectHeaderProps) {
  const supplier = resolveOne(project.supplier_master_data)
  const status = resolveOne(project.project_statuses ?? null)
  const typeAssignments = project.project_type_assignments ?? []

  const supplierName = supplier?.supplier_name || project.supplier_name
  const supplierLine2 = supplier ? formatSupplierLine2(supplier) : ''

  const visitDate = project.visit_date
    ? new Date(project.visit_date).toLocaleDateString('de-DE', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
      })
    : null

  return (
    <header className="sticky top-0 z-20 bg-primary-dark text-white shadow-md">
      {/* Row 1: context */}
      <div className="px-4 py-3 flex items-center gap-3">
        <Link
          href={backHref}
          className="text-white/70 hover:text-white shrink-0 transition-colors"
          aria-label="Zurück"
        >
          <ArrowLeft size={20} />
        </Link>

        {project.project_code && (
          <span className="font-mono text-xs bg-card/15 text-white px-2 py-0.5 rounded font-semibold shrink-0">
            {project.project_code}
          </span>
        )}

        {project.is_demo && <DemoBadge />}

        <div className="flex-1 min-w-0">
          <p className="font-semibold truncate leading-tight">{supplierName}</p>
          {(supplierLine2 || project.plant_location || visitDate) && (
            <p className="text-xs text-white/60 truncate">
              {[
                supplierLine2,
                project.plant_location,
                visitDate ? `Besuch: ${visitDate}` : null,
              ]
                .filter(Boolean)
                .join(' · ')}
            </p>
          )}
        </div>

        {/* Type tags */}
        {typeAssignments.length > 0 && (
          <div className="hidden md:flex items-center gap-1 shrink-0">
            {typeAssignments.map((t) => {
              const code = t.project_type_code
              const label = TYPE_LABELS[code] ?? code
              const isHighlighted = code === highlightedTypeCode
              const isComingSoon = COMING_SOON_TYPES.has(code)
              const routeFn = IMPLEMENTED_TYPE_ROUTES[code]
              const isClickable = !!routeFn

              const baseClasses = 'text-[10px] font-medium px-2 py-0.5 rounded transition-colors'
              const stateClasses = isHighlighted
                ? 'bg-card/20 text-white'
                : 'bg-card/8 text-white/65'
              const interactionClasses = isClickable
                ? 'hover:bg-card/15 cursor-pointer'
                : 'cursor-not-allowed'

              const tooltip = isClickable
                ? `Zu ${label} wechseln`
                : isComingSoon
                  ? 'Workflow noch nicht implementiert'
                  : undefined

              if (isClickable) {
                return (
                  <Link
                    key={code}
                    href={routeFn(project.id)}
                    title={tooltip}
                    className={`${baseClasses} ${stateClasses} ${interactionClasses}`}
                  >
                    {label}
                  </Link>
                )
              }

              return (
                <span
                  key={code}
                  title={tooltip}
                  className={`${baseClasses} ${stateClasses} ${interactionClasses}`}
                >
                  {label}
                </span>
              )
            })}
          </div>
        )}

        {/* Status pill */}
        {status && (
          <span
            className={`text-xs font-medium px-2 py-0.5 rounded-full shrink-0 ${
              STATUS_HEADER_COLORS[status.code] ?? 'bg-card/10 text-white/70'
            }`}
          >
            {status.label}
          </span>
        )}

        {actions && <div className="shrink-0">{actions}</div>}

        {showEditButton && (
          <Link
            href={`/project/${project.id}/edit`}
            className="text-white/70 hover:text-white transition-colors shrink-0 p-1 rounded hover:bg-card/10"
            aria-label="Projekt bearbeiten"
          >
            <Pencil size={16} />
          </Link>
        )}
      </div>

      {/* Row 2: tabs (slot) */}
      {tabs && <div className="border-t border-white/10">{tabs}</div>}
    </header>
  )
}
