"use client"

import { useState } from "react"
import { cn } from "@/lib/utils"
import { PageHeader } from "@/components/ui/page-header"
import { StatusBadge, type StatusTone } from "@/components/ui/status-badge"
import { WorkflowTimeline, type WorkflowDefinition } from "@/components/workflow"

export type DetailTab = {
  key: string
  label: { en: string; ar: string }
  content: React.ReactNode
  badge?: number
}

type Props = {
  title: string
  description?: string
  breadcrumbs?: { label: string; href?: string }[]
  status: string
  statusLabel: { en: string; ar: string }
  statusTone: StatusTone
  workflow?: WorkflowDefinition
  language: "ar" | "en"
  tabs: DetailTab[]
  actions?: React.ReactNode
  headerExtra?: React.ReactNode
}

export function EntityDetailPage({
  title,
  description,
  breadcrumbs,
  status,
  statusLabel,
  statusTone,
  workflow,
  language,
  tabs,
  actions,
  headerExtra,
}: Props) {
  const [activeTab, setActiveTab] = useState(tabs[0]?.key ?? "")

  return (
    <div className="space-y-6">
      <PageHeader
        title={title}
        description={description}
        breadcrumbs={breadcrumbs}
        actions={actions}
      />

      <div className="flex flex-wrap items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <StatusBadge tone={statusTone}>{statusLabel[language]}</StatusBadge>
          {headerExtra}
        </div>
        {workflow && (
          <WorkflowTimeline
            definition={workflow}
            currentStatus={status}
            language={language}
          />
        )}
      </div>

      <div className="border-b border-border">
        <div className="flex flex-wrap gap-1">
          {tabs.map(tab => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className={cn(
                "relative px-4 py-2.5 text-sm font-medium transition-colors",
                activeTab === tab.key
                  ? "text-gold-600"
                  : "text-muted-foreground hover:text-foreground",
              )}
            >
              {tab.label[language]}
              {tab.badge !== undefined && tab.badge > 0 && (
                <span className="ml-1.5 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-gold-100 px-1 text-[10px] font-bold text-gold-700">
                  {tab.badge}
                </span>
              )}
              {activeTab === tab.key && (
                <span className="absolute inset-x-0 -bottom-px h-0.5 bg-gold-500" />
              )}
            </button>
          ))}
        </div>
      </div>

      <div>
        {tabs.find(tab => tab.key === activeTab)?.content}
      </div>
    </div>
  )
}