"use client";

import {
  ChevronLeft,
  ChevronRight,
  Edit,
  Image as ImageIcon,
  Search,
  ToggleLeft,
  ToggleRight,
  Trash2,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { getStorageUrl } from "@/lib/utils";

import type { AdminSightseeing } from "./types";

function getImageUrl(path: string | null): string {
  if (!path) return "";
  return path.startsWith("http") ? path : getStorageUrl(path);
}

function SkeletonRow() {
  return (
    <TableRow>
      <TableCell>
        <div className="h-12 w-20 rounded-lg bg-muted animate-pulse" />
      </TableCell>
      <TableCell>
        <div className="space-y-2">
          <div className="h-4 w-32 rounded bg-muted animate-pulse" />
          <div className="h-3 w-20 rounded bg-muted animate-pulse" />
        </div>
      </TableCell>
      <TableCell>
        <div className="h-5 w-16 rounded-full bg-muted animate-pulse" />
      </TableCell>
      <TableCell>
        <div className="h-4 w-28 rounded bg-muted animate-pulse" />
      </TableCell>
      <TableCell />
    </TableRow>
  );
}

interface SightseeingTableProps {
  sightseeings: AdminSightseeing[];
  isLoading: boolean;
  searchTerm: string;
  totalCount: number;
  currentPage: number;
  totalPages: number;
  onEdit: (sightseeing: AdminSightseeing) => void;
  onDelete: (sightseeing: AdminSightseeing) => void;
  onToggleStatus: (sightseeing: AdminSightseeing) => void;
  onSearchChange: (value: string) => void;
  onPageChange: (page: number) => void;
}

export function SightseeingTable({
  sightseeings,
  isLoading,
  searchTerm,
  totalCount,
  currentPage,
  totalPages,
  onEdit,
  onDelete,
  onToggleStatus,
  onSearchChange,
  onPageChange,
}: SightseeingTableProps) {
  const [localSearchTerm, setLocalSearchTerm] = useState(searchTerm);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      if (localSearchTerm === searchTerm) return;
      onSearchChange(localSearchTerm);
    }, 400);

    return () => window.clearTimeout(timer);
  }, [localSearchTerm, onSearchChange, searchTerm]);

  useEffect(() => {
    setLocalSearchTerm(searchTerm);
  }, [searchTerm]);

  const pageStart = useMemo(() => {
    if (sightseeings.length === 0) return 0;
    return (currentPage - 1) * sightseeings.length + 1;
  }, [currentPage, sightseeings.length]);

  const pageEnd = useMemo(() => {
    if (sightseeings.length === 0) return 0;
    return Math.min(pageStart + sightseeings.length - 1, totalCount);
  }, [pageStart, sightseeings.length, totalCount]);

  const visiblePages = useMemo(() => {
    if (totalPages <= 5) {
      return Array.from({ length: totalPages }, (_, index) => index + 1);
    }

    if (currentPage <= 3) {
      return [1, 2, 3, 4, 5];
    }

    if (currentPage >= totalPages - 2) {
      return Array.from({ length: 5 }, (_, index) => totalPages - 4 + index);
    }

    return Array.from({ length: 5 }, (_, index) => currentPage - 2 + index);
  }, [currentPage, totalPages]);

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4 flex-wrap">
        <div className="relative flex-1 min-w-[300px]">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search by location name..."
            className="pl-9 rounded-xl border-none shadow-sm ring-1 ring-border focus-visible:ring-primary"
            value={localSearchTerm}
            onChange={(e) => setLocalSearchTerm(e.target.value)}
          />
        </div>
        {!isLoading && (
          <p className="text-sm text-muted-foreground">
            {totalCount} sightseeing{totalCount !== 1 ? "s" : ""}
          </p>
        )}
      </div>

      <Card className="rounded-2xl border-none shadow-sm ring-1 ring-border overflow-hidden">
        <CardContent className="p-0">
          <Table>
            <TableHeader className="bg-muted/30">
              <TableRow>
                <TableHead className="w-[100px] py-4">Preview</TableHead>
                <TableHead>Location Name</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Last Updated</TableHead>
                <TableHead className="text-right w-56">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 4 }).map((_, index) => (
                  <SkeletonRow key={index} />
                ))
              ) : sightseeings.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="py-20">
                    <div className="flex flex-col items-center text-muted-foreground">
                      <ImageIcon className="mb-3 h-10 w-10 opacity-30" />
                      <p className="text-sm font-medium">
                        No sightseeings found
                      </p>
                      <p className="mt-1 text-xs">
                        Try adjusting your search or add a new sightseeing.
                      </p>
                    </div>
                  </TableCell>
                </TableRow>
              ) : (
                sightseeings.map((sightseeing) => (
                  <TableRow
                    key={sightseeing.id}
                    className="group hover:bg-muted/10 transition-colors"
                  >
                    <TableCell className="py-4">
                      <div className="relative h-12 w-20 overflow-hidden rounded-lg border border-border/50 bg-muted shadow-sm transition-transform group-hover:scale-105">
                        {sightseeing.image ? (
                          <img
                            src={getImageUrl(sightseeing.image)}
                            alt={sightseeing.name}
                            className="h-full w-full object-cover"
                          />
                        ) : (
                          <div className="flex h-full w-full items-center justify-center">
                            <ImageIcon className="h-5 w-5 text-muted-foreground/40" />
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <h3 className="text-sm font-semibold leading-none">
                          {sightseeing.name}
                        </h3>
                        <p className="text-xs text-muted-foreground">
                          ID #{sightseeing.id}
                        </p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant={
                          sightseeing.status === "active"
                            ? "secondary"
                            : "outline"
                        }
                        className={
                          sightseeing.status === "active"
                            ? "bg-emerald-50 text-emerald-700 border-none px-2.5 py-0.5"
                            : "text-muted-foreground px-2.5 py-0.5"
                        }
                      >
                        {sightseeing.status === "active"
                          ? "Active"
                          : "Inactive"}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs text-muted-foreground">
                        {sightseeing.updatedAt
                          ? new Date(sightseeing.updatedAt).toLocaleDateString(
                              "en-IN",
                              {
                                day: "numeric",
                                month: "short",
                                year: "numeric",
                              }
                            )
                          : "—"}
                      </div>
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Button
                          variant={
                            sightseeing.status === "active"
                              ? "outline"
                              : "default"
                          }
                          size="sm"
                          onClick={() => onToggleStatus(sightseeing)}
                          title={
                            sightseeing.status === "active"
                              ? "Deactivate"
                              : "Activate"
                          }
                        >
                          {sightseeing.status === "active" ? (
                            <ToggleRight className="h-4 w-4" />
                          ) : (
                            <ToggleLeft className="h-4 w-4" />
                          )}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => onEdit(sightseeing)}
                          title="Edit"
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="destructive"
                          size="sm"
                          onClick={() => onDelete(sightseeing)}
                          title="Delete"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {!isLoading && totalPages > 1 && (
        <div className="flex items-center justify-between px-2 text-xs text-muted-foreground">
          <div>
            Showing {pageStart}–{pageEnd} of {totalCount}
          </div>
          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="sm"
              className="h-8 rounded-lg"
              disabled={currentPage <= 1}
              onClick={() => onPageChange(currentPage - 1)}
            >
              <ChevronLeft className="h-3.5 w-3.5" />
            </Button>
            {visiblePages.map((page) => (
              <Button
                key={page}
                variant={currentPage === page ? "default" : "outline"}
                size="sm"
                className="h-8 w-8 rounded-lg text-xs"
                onClick={() => onPageChange(page)}
              >
                {page}
              </Button>
            ))}
            <Button
              variant="ghost"
              size="sm"
              className="h-8 rounded-lg"
              disabled={currentPage >= totalPages}
              onClick={() => onPageChange(currentPage + 1)}
            >
              <ChevronRight className="h-3.5 w-3.5" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
