"use client"

import { useState, useMemo, useCallback } from "react"
import { useRouter } from "next/navigation"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Button } from "@/components/ui/button"
import { Plus } from "lucide-react"
import { RouteTable } from "./route-table"
import { DeleteRouteDialog } from "./delete-route-dialog"
import { routeDataStore, type Route } from "@/lib/data/routes"
import { useToastEnhanced } from "@/hooks/use-toast-enhanced"

export function RoutesClient() {
  const router = useRouter()
  const toast = useToastEnhanced()
  const [currentTab, setCurrentTab] = useState("active")

  const [routes, setRoutes] = useState<Route[]>(routeDataStore.getAllRoutes())
  const [deletingRoute, setDeletingRoute] = useState<Route | null>(null)

  const activeRoutes = useMemo(() => routes.filter((r) => r.status === "active"), [routes])
  const inactiveRoutes = useMemo(() => routes.filter((r) => r.status === "inactive"), [routes])

  const handleTabChange = (value: string) => {
    setCurrentTab(value)
  }

  const handleEditRoute = useCallback(
    (route: Route) => {
      router.push(`/admin/routes-listing/add-new?id=${route.id}`)
    },
    [router],
  )

  const handleToggleStatus = useCallback(
    (route: Route) => {
      const updated = routeDataStore.toggleRouteStatus(route.id)
      if (updated) {
        setRoutes(routeDataStore.getAllRoutes())
        const action = updated.status === "active" ? "activated" : "deactivated"
        toast.success({
          title: `Route ${action.charAt(0).toUpperCase() + action.slice(1)}`,
          description: `${route.origin} to ${route.destination} has been ${action}.`,
        })
      }
    },
    [toast],
  )

  const handleDeleteRoute = useCallback(() => {
    if (!deletingRoute) return

    const deleted = routeDataStore.deleteRoute(deletingRoute.id)
    if (deleted) {
      setRoutes(routeDataStore.getAllRoutes())
      toast.success({
        title: "Route Deleted",
        description: `Route from ${deletingRoute.origin} to ${deletingRoute.destination} has been deleted.`,
      })
    }
    setDeletingRoute(null)
  }, [deletingRoute, toast])

  const getDisplayRoutes = () => {
    switch (currentTab) {
      case "inactive":
        return inactiveRoutes
      default:
        return activeRoutes
    }
  }

  return (
    <section aria-labelledby="routes-heading" className="admin-section">
      <header className="admin-page-header flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 id="routes-heading" className="admin-page-title">
            Routes Listing
          </h1>
          <p className="admin-page-description">Manage vehicle routes with origin, destination, and pricing.</p>
        </div>
        <Button onClick={() => router.push("/admin/routes-listing/add-new")} className="w-full sm:w-auto">
          <Plus className="mr-2 h-4 w-4" aria-hidden="true" />
          Add New Route
        </Button>
      </header>

      <Tabs value={currentTab} onValueChange={handleTabChange} className="w-full">
        <TabsList className="mb-6 h-auto p-1.5 bg-muted/50 rounded-xl border border-border/50">
          <TabsTrigger
            value="active"
            className="rounded-lg data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2"
          >
            Active Routes ({activeRoutes.length})
          </TabsTrigger>
          <TabsTrigger
            value="inactive"
            className="rounded-lg data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2"
          >
            Inactive Routes ({inactiveRoutes.length})
          </TabsTrigger>
        </TabsList>

        <TabsContent value="active" className="mt-0">
          <RouteTable
            routes={getDisplayRoutes()}
            onEdit={handleEditRoute}
            onDelete={setDeletingRoute}
            onToggleStatus={handleToggleStatus}
          />
        </TabsContent>

        <TabsContent value="inactive" className="mt-0">
          <RouteTable
            routes={getDisplayRoutes()}
            onEdit={handleEditRoute}
            onDelete={setDeletingRoute}
            onToggleStatus={handleToggleStatus}
          />
        </TabsContent>
      </Tabs>

      <DeleteRouteDialog
        route={deletingRoute}
        open={!!deletingRoute}
        onOpenChange={(open) => !open && setDeletingRoute(null)}
        onConfirm={handleDeleteRoute}
      />
    </section>
  )
}
