"use client";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import {
  Edit,
  Trash2,
  Search,
  ChevronLeft,
  ChevronRight,
  Car,
  ArrowRight,
  ToggleLeft,
  ToggleRight,
} from "lucide-react";
import { useState, useMemo } from "react";
import type { RouteListItem } from "@/features/routes/actions/routes-actions";

const ROUTE_TYPE_LABELS: Record<string, string> = {
  one_way: "One Way",
  round_trip: "Round Trip",
  multi_city: "Multi City",
};

interface RouteTableProps {
  routes: RouteListItem[];
  cityMap: Map<number, string>;
  isLoading: boolean;
  currentPage: number;
  totalPages: number;
  total: number;
  perPage: number;
  onToggleStatus: (route: RouteListItem) => void;
  onEdit: (route: RouteListItem) => void;
  onDelete: (route: RouteListItem) => void;
  onPageChange: (page: number) => void;
}

function CitiesCell({
  route,
  cityMap,
}: {
  route: RouteListItem;
  cityMap: Map<number, string>;
}) {
  const start =
    cityMap.get(route.start_point_city_id) ??
    `City #${route.start_point_city_id}`;
  const end =
    cityMap.get(route.end_point_city_id) ?? `City #${route.end_point_city_id}`;

  if (route.route_type === "multi_city" && route.multi_cities?.length) {
    const stops = route.multi_cities
      .slice()
      .sort((a, b) => a.sort_order - b.sort_order)
      .map(
        (s) => cityMap.get(s.stopage_city_id) ?? `City #${s.stopage_city_id}`
      );

    return (
      <div className="flex flex-wrap items-center gap-1 text-sm">
        <span className="font-medium">{start}</span>
        {stops.map((stop, i) => (
          <span
            key={i}
            className="flex items-center gap-1 text-muted-foreground"
          >
            <ArrowRight className="h-3 w-3 shrink-0" />
            {stop}
          </span>
        ))}
        <span className="flex items-center gap-1 text-muted-foreground">
          <ArrowRight className="h-3 w-3 shrink-0" />
          <span className="font-medium text-foreground">{end}</span>
        </span>
      </div>
    );
  }

  return (
    <div className="flex items-center gap-1 text-sm">
      <span className="font-medium">{start}</span>
      <ArrowRight className="h-3 w-3 shrink-0 text-muted-foreground" />
      <span className="font-medium">{end}</span>
    </div>
  );
}

function toNumber(value: string | number | null | undefined) {
  if (value == null || value === "") return 0;
  const amount = Number(value);
  return Number.isFinite(amount) ? amount : 0;
}

function formatCurrency(value: string | number | null | undefined) {
  const amount = toNumber(value);
  if (amount <= 0) return "—";
  return new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
    maximumFractionDigits: 0,
  }).format(amount);
}

function getRoutePricing(route: RouteListItem) {
  const originalPrice = toNumber(route.total_price);
  const discountedPrice = toNumber(route.discount_price);
  const hasDiscount =
    originalPrice > 0 && discountedPrice > 0 && discountedPrice < originalPrice;

  return {
    originalPrice,
    displayPrice: hasDiscount ? discountedPrice : originalPrice,
    hasDiscount,
    discountPercent: hasDiscount
      ? Math.round(((originalPrice - discountedPrice) / originalPrice) * 100)
      : 0,
  };
}

export function RouteTable({
  routes,
  cityMap,
  isLoading,
  currentPage,
  totalPages,
  total,
  perPage,
  onToggleStatus,
  onEdit,
  onDelete,
  onPageChange,
}: RouteTableProps) {
  const [search, setSearch] = useState("");

  const filtered = useMemo(() => {
    const q = search.toLowerCase().trim();
    if (!q) return routes;
    return routes.filter(
      (r) =>
        r.name.toLowerCase().includes(q) ||
        r.route_type.toLowerCase().includes(q) ||
        (cityMap.get(r.start_point_city_id) ?? "").toLowerCase().includes(q) ||
        (cityMap.get(r.end_point_city_id) ?? "").toLowerCase().includes(q)
    );
  }, [routes, search, cityMap]);

  const startItem = (currentPage - 1) * perPage + 1;
  const endItem = Math.min(currentPage * perPage, total);

  return (
    <div className="space-y-4">
      {/* Search */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="relative max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search by name or city…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-9"
          />
        </div>
        <p className="text-sm text-muted-foreground">
          {total > 0
            ? `Showing ${startItem}–${endItem} of ${total} routes`
            : "No routes"}
        </p>
      </div>

      {/* Table */}
      <div className="rounded-md border overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-14 text-center">S.No</TableHead>
              <TableHead>Route Name</TableHead>
              <TableHead>Route Type</TableHead>
              <TableHead>Cities</TableHead>
              <TableHead className="text-center">Distance</TableHead>
              <TableHead className="text-center">Duration</TableHead>
              <TableHead className="text-right">Price</TableHead>
              <TableHead className="text-center">Status</TableHead>
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              Array.from({ length: 5 }).map((_, i) => (
                <TableRow key={i}>
                  {Array.from({ length: 9 }).map((_, j) => (
                    <TableCell key={j}>
                      <div className="h-4 w-full animate-pulse rounded bg-muted" />
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : filtered.length === 0 ? (
              <TableRow>
                <TableCell colSpan={9} className="h-24 text-center">
                  <div className="flex flex-col items-center gap-2">
                    <Car className="h-8 w-8 text-muted-foreground/50" />
                    <p className="text-muted-foreground">
                      {search
                        ? `No routes matching "${search}"`
                        : "No routes found"}
                    </p>
                  </div>
                </TableCell>
              </TableRow>
            ) : (
              filtered.map((route, index) => {
                const pricing = getRoutePricing(route);

                return (
                  <TableRow key={route.id}>
                    <TableCell className="text-center font-medium text-muted-foreground">
                      {(currentPage - 1) * perPage + index + 1}
                    </TableCell>
                    <TableCell className="font-medium">{route.name}</TableCell>
                    <TableCell>
                      <Badge variant="outline" className="whitespace-nowrap">
                        {ROUTE_TYPE_LABELS[route.route_type] ??
                          route.route_type}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <CitiesCell route={route} cityMap={cityMap} />
                    </TableCell>
                    <TableCell className="text-center text-sm text-muted-foreground">
                      {route.total_distance
                        ? `${route.total_distance} km`
                        : "—"}
                    </TableCell>
                    <TableCell className="text-center text-sm text-muted-foreground">
                      {route.total_duration ?? "—"}
                    </TableCell>
                    <TableCell className="text-right text-sm">
                      <div className="flex flex-col items-end">
                        <span className="font-semibold text-green-600">
                          {formatCurrency(pricing.displayPrice)}
                        </span>
                        {pricing.hasDiscount ? (
                          <div className="flex items-center justify-end gap-1.5">
                            <span className="text-xs text-muted-foreground line-through">
                              {formatCurrency(pricing.originalPrice)}
                            </span>
                            <Badge
                              variant="outline"
                              className="h-4 border-green-200 bg-green-50 px-1 py-0 text-[10px] text-green-700"
                            >
                              {pricing.discountPercent}% OFF
                            </Badge>
                          </div>
                        ) : null}
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <Badge
                        variant={
                          route.status === "active" ? "default" : "secondary"
                        }
                      >
                        {route.status === "active" ? "Active" : "Inactive"}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center justify-end gap-2">
                        <Button
                          variant={
                            route.status === "active" ? "outline" : "default"
                          }
                          size="sm"
                          onClick={() => onToggleStatus(route)}
                          aria-label={`${route.status === "active" ? "Deactivate" : "Activate"} ${route.name}`}
                          title={
                            route.status === "active"
                              ? "Deactivate"
                              : "Activate"
                          }
                        >
                          {route.status === "active" ? (
                            <ToggleRight
                              className="h-4 w-4"
                              aria-hidden="true"
                            />
                          ) : (
                            <ToggleLeft
                              className="h-4 w-4"
                              aria-hidden="true"
                            />
                          )}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => onEdit(route)}
                          title="Edit"
                          aria-label={`Edit ${route.name}`}
                        >
                          <Edit className="h-4 w-4" aria-hidden="true" />
                        </Button>
                        <Button
                          variant="destructive"
                          size="sm"
                          onClick={() => onDelete(route)}
                          title="Delete"
                          aria-label={`Delete ${route.name}`}
                        >
                          <Trash2 className="h-4 w-4" aria-hidden="true" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">
            Page {currentPage} of {totalPages}
          </p>
          <div className="flex items-center gap-1">
            <Button
              variant="outline"
              size="icon"
              onClick={() => onPageChange(currentPage - 1)}
              disabled={currentPage === 1 || isLoading}
              aria-label="Previous page"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <div className="hidden sm:flex items-center gap-1">
              {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                let pageNum: number;
                if (totalPages <= 5) pageNum = i + 1;
                else if (currentPage <= 3) pageNum = i + 1;
                else if (currentPage >= totalPages - 2)
                  pageNum = totalPages - 4 + i;
                else pageNum = currentPage - 2 + i;
                return (
                  <Button
                    key={pageNum}
                    variant={currentPage === pageNum ? "default" : "outline"}
                    size="icon"
                    onClick={() => onPageChange(pageNum)}
                    disabled={isLoading}
                    aria-label={`Go to page ${pageNum}`}
                    aria-current={currentPage === pageNum ? "page" : undefined}
                  >
                    {pageNum}
                  </Button>
                );
              })}
            </div>
            <Button
              variant="outline"
              size="icon"
              onClick={() => onPageChange(currentPage + 1)}
              disabled={currentPage === totalPages || isLoading}
              aria-label="Next page"
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
