import { Link } from '@tanstack/react-router'
import { usePOSStore } from '@/stores/pos.store'
import { useStationStore } from '@/stores/station.store'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { ArrowLeft, Lock, DollarSign, Receipt, FileText, ShoppingCart, Wrench, GraduationCap } from 'lucide-react'
import type { DrawerSession } from '@/api/pos'
import { useState } from 'react'
import { POSDrawerDialog } from '@/components/pos/pos-drawer-dialog'

type StationTab = 'pos' | 'repairs' | 'lessons'

const TAB_CONFIG: { key: StationTab; label: string; icon: typeof ShoppingCart; permission: string; module: string }[] = [
  { key: 'pos', label: 'POS', icon: ShoppingCart, permission: 'pos.view', module: 'pos' },
  { key: 'repairs', label: 'Repairs', icon: Wrench, permission: 'repairs.view', module: 'repairs' },
  { key: 'lessons', label: 'Lessons', icon: GraduationCap, permission: 'lessons.view', module: 'lessons' },
]

interface StationTopBarProps {
  locations: { id: string; name: string }[]
  locationId: string | null
  onLocationChange: (id: string) => void
  drawer: DrawerSession | null
  permissions: string[]
  enabledModules: Set<string>
}

export function StationTopBar({ locations, locationId, onLocationChange, drawer, permissions, enabledModules }: StationTopBarProps) {
  const cashier = usePOSStore((s) => s.cashier)
  const lockFn = usePOSStore((s) => s.lock)
  const receiptFormat = usePOSStore((s) => s.receiptFormat)
  const setReceiptFormat = usePOSStore((s) => s.setReceiptFormat)
  const { activeTab, setActiveTab } = useStationStore()
  const [drawerDialogOpen, setDrawerDialogOpen] = useState(false)

  const drawerOpen = drawer?.status === 'open'
  const isThermal = receiptFormat === 'thermal'

  const hasPermission = (perm: string) => permissions.includes(perm)
  const visibleTabs = TAB_CONFIG.filter(t => hasPermission(t.permission) && enabledModules.has(t.module))

  return (
    <>
      <div className="h-12 border-b border-border bg-card flex items-center px-3 shrink-0 gap-2">
        {/* Left: back link */}
        <Link to="/login" className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground mr-2">
          <ArrowLeft className="h-4 w-4" />
          <span className="hidden sm:inline">Admin</span>
        </Link>

        {/* Tabs */}
        <div className="flex items-center gap-1 bg-muted rounded-lg p-0.5">
          {visibleTabs.map((tab) => (
            <Button
              key={tab.key}
              variant={activeTab === tab.key ? 'default' : 'ghost'}
              size="sm"
              className={`h-8 gap-1.5 text-xs ${activeTab === tab.key ? '' : 'text-muted-foreground hover:text-foreground'}`}
              onClick={() => setActiveTab(tab.key)}
            >
              <tab.icon className="h-3.5 w-3.5" />
              {tab.label}
            </Button>
          ))}
        </div>

        {/* Spacer */}
        <div className="flex-1" />

        {/* Location */}
        {locations.length > 1 ? (
          <Select value={locationId ?? ''} onValueChange={onLocationChange}>
            <SelectTrigger className="h-8 w-40 text-sm">
              <SelectValue placeholder="Location" />
            </SelectTrigger>
            <SelectContent>
              {locations.map((loc) => (
                <SelectItem key={loc.id} value={loc.id}>{loc.name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        ) : locations.length === 1 ? (
          <span className="text-sm text-muted-foreground">{locations[0].name}</span>
        ) : null}

        {/* POS-specific controls */}
        {activeTab === 'pos' && (
          <>
            <Button
              variant="ghost"
              size="sm"
              className="h-8 gap-1.5 text-xs text-muted-foreground"
              onClick={() => setReceiptFormat(isThermal ? 'full' : 'thermal')}
              title={isThermal ? 'Thermal' : 'Full Page'}
            >
              {isThermal ? <Receipt className="h-3.5 w-3.5" /> : <FileText className="h-3.5 w-3.5" />}
            </Button>

            <Button variant="ghost" size="sm" className="gap-1.5" onClick={() => setDrawerDialogOpen(true)}>
              <DollarSign className="h-4 w-4" />
              {drawerOpen ? (
                <Badge variant="default" className="text-xs">Open</Badge>
              ) : (
                <Badge variant="outline" className="text-xs">Closed</Badge>
              )}
            </Button>
          </>
        )}

        {/* Cashier + Lock */}
        {cashier && (
          <span className="text-sm text-muted-foreground">{cashier.firstName}</span>
        )}
        <Button variant="ghost" size="icon" className="h-8 w-8" onClick={lockFn} title="Lock Station">
          <Lock className="h-4 w-4" />
        </Button>
      </div>

      <POSDrawerDialog
        open={drawerDialogOpen}
        onOpenChange={setDrawerDialogOpen}
        drawer={drawer}
      />
    </>
  )
}
