"use client";

import { useMemo, useState } from "react";
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 {
  Pencil,
  Trash2,
  ToggleLeft,
  ToggleRight,
  Search,
  ChevronLeft,
  ChevronRight,
  ArrowUpDown,
  ArrowUp,
  ArrowDown,
  Eye,
} from "lucide-react";
import type { FixPackage } from "@/features/packages/services/fix-packages.service";
import { FIX_PACKAGES_ADMIN } from "@/lib/strings";

interface FixPackagesTableProps {
  packages: FixPackage[];
  searchQuery: string;
  onSearchChange: (value: string) => void;
  currentPage: number;
  totalPages: number;
  totalItems: number;
  pageSize: number;
  onPageChange: (page: number) => void;
  onView: (pkg: FixPackage) => void;
  onEdit: (pkg: FixPackage) => void;
  onDelete: (pkg: FixPackage) => void;
  onToggleStatus: (pkg: FixPackage) => void;
}

type SortField = "name" | "totalDays" | "discountedPrice";
type SortDirection = "asc" | "desc";

export function FixPackagesTable({
  packages,
  searchQuery,
  onSearchChange,
  currentPage,
  totalPages,
  totalItems,
  pageSize,
  onPageChange,
  onView,
  onEdit,
  onDelete,
  onToggleStatus,
}: FixPackagesTableProps) {
  const [sortField, setSortField] = useState<SortField>("name");
  const [sortDirection, setSortDirection] = useState<SortDirection>("asc");

  const formatCurrency = (amount: number): string => {
    return new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      maximumFractionDigits: 0,
    }).format(amount);
  };

  // Data is already paginated + filtered by server-side search.
  const sortedData = useMemo(() => {
    return [...packages].sort((a, b) => {
      let comparison = 0;
      switch (sortField) {
        case "name":
          comparison = a.name.localeCompare(b.name);
          break;
        case "totalDays":
          comparison = a.totalDays - b.totalDays;
          break;
        case "discountedPrice":
          comparison = a.discountedPrice - b.discountedPrice;
          break;
      }
      return sortDirection === "asc" ? comparison : -comparison;
    });
  }, [packages, sortField, sortDirection]);

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc");
      return;
    }
    setSortField(field);
    setSortDirection("asc");
  };

  const getSortIcon = (field: SortField) => {
    if (sortField !== field) {
      return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
    }
    return sortDirection === "asc" ? (
      <ArrowUp className="ml-1 h-3 w-3" />
    ) : (
      <ArrowDown className="ml-1 h-3 w-3" />
    );
  };

  const showingFrom = totalItems > 0 ? (currentPage - 1) * pageSize + 1 : 0;
  const showingTo =
    totalItems > 0 ? Math.min(currentPage * pageSize, totalItems) : 0;

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-12 gap-4 items-center">
        <div className="col-span-12 sm:col-span-10 relative flex justify-start">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder={FIX_PACKAGES_ADMIN.SEARCH_PLACEHOLDER_TABLE}
            value={searchQuery}
            onChange={(e) => onSearchChange(e.target.value)}
            className="pl-9"
            aria-label={FIX_PACKAGES_ADMIN.SEARCH_ARIA}
          />
        </div>
        <div className="col-span-12 sm:col-span-2 flex items-center justify-end gap-2">
          <span
            className="text-sm text-muted-foreground whitespace-nowrap"
            aria-label={FIX_PACKAGES_ADMIN.GO_TO_PAGE}
          >
            {FIX_PACKAGES_ADMIN.PAGE} {currentPage}/{Math.max(1, totalPages)}
          </span>
        </div>
      </div>

      <div className="flex items-center justify-between text-sm text-muted-foreground">
        <p>
          {FIX_PACKAGES_ADMIN.SHOWING_TO_OF} {showingFrom}{" "}
          {FIX_PACKAGES_ADMIN.TO} {showingTo} {FIX_PACKAGES_ADMIN.OF}{" "}
          {totalItems} {FIX_PACKAGES_ADMIN.PACKAGES}
        </p>
        <Badge variant="secondary" className="font-normal">
          {FIX_PACKAGES_ADMIN.FILTERED_FROM_TOTAL} {totalItems}{" "}
          {FIX_PACKAGES_ADMIN.TOTAL}
        </Badge>
      </div>

      <div className="rounded-md border overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-16 text-center">
                {FIX_PACKAGES_ADMIN.S_NO}
              </TableHead>
              <TableHead>
                <Button
                  variant="ghost"
                  size="sm"
                  className="-ml-3 h-8 data-[state=open]:bg-accent"
                  onClick={() => handleSort("name")}
                >
                  {FIX_PACKAGES_ADMIN.PACKAGE_NAME}
                  {getSortIcon("name")}
                </Button>
              </TableHead>
              <TableHead className="w-32">
                {FIX_PACKAGES_ADMIN.DETAILS}
              </TableHead>
              <TableHead>
                <Button
                  variant="ghost"
                  size="sm"
                  className="-ml-3 h-8 data-[state=open]:bg-accent"
                  onClick={() => handleSort("discountedPrice")}
                >
                  {FIX_PACKAGES_ADMIN.PRICE}
                  {getSortIcon("discountedPrice")}
                </Button>
              </TableHead>
              <TableHead>
                <Button
                  variant="ghost"
                  size="sm"
                  className="-ml-3 h-8 data-[state=open]:bg-accent"
                  onClick={() => handleSort("totalDays")}
                >
                  {FIX_PACKAGES_ADMIN.TOTAL_DAYS}
                  {getSortIcon("totalDays")}
                </Button>
              </TableHead>
              <TableHead className="w-28">
                {FIX_PACKAGES_ADMIN.STATUS}
              </TableHead>
              <TableHead className="text-right w-56">
                {FIX_PACKAGES_ADMIN.ACTIONS}
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sortedData.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="h-24 text-center">
                  <p className="text-muted-foreground">
                    {searchQuery
                      ? `${FIX_PACKAGES_ADMIN.NO_PACKAGES_MATCHING}${searchQuery}"`
                      : FIX_PACKAGES_ADMIN.NO_PACKAGES_FOUND}
                  </p>
                </TableCell>
              </TableRow>
            ) : (
              sortedData.map((pkg, index) => (
                <TableRow key={pkg.id}>
                  <TableCell className="text-center font-medium text-muted-foreground">
                    {(currentPage - 1) * pageSize + index + 1}
                  </TableCell>
                  <TableCell className="font-medium max-w-xs">
                    <div className="truncate" title={pkg.name}>
                      {pkg.name}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => onView(pkg)}
                      aria-label={`${FIX_PACKAGES_ADMIN.VIEW} ${pkg.name}`}
                    >
                      <Eye className="h-4 w-4 mr-1" aria-hidden="true" />
                      {FIX_PACKAGES_ADMIN.VIEW}
                    </Button>
                  </TableCell>
                  <TableCell>
                    <div className="flex flex-col">
                      <span className="font-semibold text-green-600">
                        {formatCurrency(pkg.discountedPrice)}
                      </span>
                      {pkg.originalPrice > pkg.discountedPrice && (
                        <div className="flex items-center gap-1.5">
                          <span className="text-xs text-muted-foreground line-through">
                            {formatCurrency(pkg.originalPrice)}
                          </span>
                          <Badge
                            variant="outline"
                            className="text-[10px] px-1 py-0 h-4 border-green-200 text-green-700 bg-green-50"
                          >
                            {Math.round(
                              ((pkg.originalPrice - pkg.discountedPrice) /
                                pkg.originalPrice) *
                                100
                            )}
                            % OFF
                          </Badge>
                        </div>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <span className="font-medium">
                      {pkg.totalDays} {FIX_PACKAGES_ADMIN.DAYS}
                    </span>
                  </TableCell>
                  <TableCell>
                    <Badge
                      variant={
                        pkg.status === "active" ? "default" : "secondary"
                      }
                    >
                      {pkg.status === "active"
                        ? FIX_PACKAGES_ADMIN.ACTIVE
                        : FIX_PACKAGES_ADMIN.INACTIVE}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2">
                      <Button
                        variant={
                          pkg.status === "active" ? "outline" : "default"
                        }
                        size="sm"
                        onClick={() => onToggleStatus(pkg)}
                        aria-label={`${pkg.status === "active" ? FIX_PACKAGES_ADMIN.DEACTIVATE : FIX_PACKAGES_ADMIN.ACTIVATE} ${pkg.name}`}
                        title={
                          pkg.status === "active"
                            ? FIX_PACKAGES_ADMIN.DEACTIVATE
                            : FIX_PACKAGES_ADMIN.ACTIVATE
                        }
                      >
                        {pkg.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(pkg)}
                        aria-label={`${FIX_PACKAGES_ADMIN.EDIT} ${pkg.name}`}
                        title={FIX_PACKAGES_ADMIN.EDIT}
                      >
                        <Pencil className="h-4 w-4" aria-hidden="true" />
                      </Button>
                      <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => onDelete(pkg)}
                        aria-label={`${FIX_PACKAGES_ADMIN.DELETE} ${pkg.name}`}
                        title={FIX_PACKAGES_ADMIN.DELETE}
                      >
                        <Trash2 className="h-4 w-4" aria-hidden="true" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">
            {FIX_PACKAGES_ADMIN.PAGE} {currentPage} {FIX_PACKAGES_ADMIN.OF}{" "}
            {totalPages}
          </p>
          <div className="flex items-center gap-1">
            <Button
              variant="outline"
              size="icon"
              onClick={() =>
                onPageChange(Math.max(1, Math.min(currentPage - 1, totalPages)))
              }
              disabled={currentPage === 1}
              aria-label={FIX_PACKAGES_ADMIN.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)}
                    aria-label={`${FIX_PACKAGES_ADMIN.GO_TO_PAGE} ${pageNum}`}
                    aria-current={currentPage === pageNum ? "page" : undefined}
                  >
                    {pageNum}
                  </Button>
                );
              })}
            </div>
            <Button
              variant="outline"
              size="icon"
              onClick={() =>
                onPageChange(Math.max(1, Math.min(currentPage + 1, totalPages)))
              }
              disabled={currentPage === totalPages}
              aria-label={FIX_PACKAGES_ADMIN.NEXT_PAGE}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
