"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import {
  Plus,
  Search,
  Edit,
  Trash2,
  Eye,
  Monitor,
  Tablet,
  Smartphone,
  ChevronLeft,
  ChevronRight,
  Loader2,
  ToggleLeft,
  ToggleRight,
} from "lucide-react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  getAdminBannersAction,
  deleteBannerAction,
  updateBannerAction,
} from "@/features/banners/api";
import type { Banner } from "@/features/banners/api";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { getStorageUrl } from "@/lib/utils";

// ─── Image URL helper ────────────────────────────────────────────────────────

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

// ─── Skeleton Row ─────────────────────────────────────────────────────────────

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 bg-muted rounded animate-pulse" />
          <div className="h-3 w-20 bg-muted rounded animate-pulse" />
        </div>
      </TableCell>
      <TableCell>
        <div className="h-5 w-16 bg-muted rounded-full animate-pulse" />
      </TableCell>
      <TableCell>
        <div className="h-4 w-8 bg-muted rounded animate-pulse" />
      </TableCell>
      <TableCell>
        <div className="h-4 w-28 bg-muted rounded animate-pulse" />
      </TableCell>
      <TableCell></TableCell>
    </TableRow>
  );
}

// ─── Main Component ──────────────────────────────────────────────────────────

const ITEMS_PER_PAGE = 10;

export function BannerListClient() {
  const toast = useToastEnhanced();
  const lastFetchKeyRef = useRef<string>("");

  const [banners, setBanners] = useState<Banner[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [deleteId, setDeleteId] = useState<number | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  // Debounce search
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(searchTerm);
      setCurrentPage(1);
    }, 400);
    return () => clearTimeout(timer);
  }, [searchTerm]);

  // Fetch banners
  const fetchBanners = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await getAdminBannersAction(
        debouncedSearch || undefined,
        currentPage
      );
      if (result.success && result.data) {
        setBanners(result.data);
      } else {
        toast.error({
          title: "Failed to load banners",
          description: result.error,
        });
      }
    } catch {
      toast.error({
        title: "Network error",
        description: "Could not reach the server.",
      });
    } finally {
      setIsLoading(false);
    }
  }, [debouncedSearch, currentPage]);

  useEffect(() => {
    const fetchKey = `${debouncedSearch}::${currentPage}`;
    if (lastFetchKeyRef.current === fetchKey) return;

    lastFetchKeyRef.current = fetchKey;
    fetchBanners();
  }, [debouncedSearch, currentPage, fetchBanners]);

  // Local search filter (the API returns all, we filter client-side)
  const filtered = banners.filter((b) => {
    if (!debouncedSearch) return true;
    const q = debouncedSearch.toLowerCase();
    return (
      b.title.toLowerCase().includes(q) || b.subtitle?.toLowerCase().includes(q)
    );
  });

  // Pagination
  const totalPages = Math.max(1, Math.ceil(filtered.length / ITEMS_PER_PAGE));
  const paginated = filtered.slice(
    (currentPage - 1) * ITEMS_PER_PAGE,
    currentPage * ITEMS_PER_PAGE
  );

  // Delete
  const handleDelete = async () => {
    if (!deleteId) return;
    setIsDeleting(true);
    try {
      const result = await deleteBannerAction(deleteId);
      if (result.success) {
        toast.success({
          title: "Banner deleted",
          description: "The banner has been removed.",
        });
        setBanners((prev) => prev.filter((b) => b.id !== deleteId));
      } else {
        toast.error({ title: "Delete failed", description: result.error });
      }
    } catch {
      toast.error({
        title: "Network error",
        description: "Could not delete banner.",
      });
    } finally {
      setIsDeleting(false);
      setDeleteId(null);
    }
  };

  const handleToggleStatus = async (banner: Banner) => {
    const newStatus = banner.status === "active" ? "inactive" : "active";
    try {
      const result = await updateBannerAction(banner.id, { status: newStatus });
      if (result.success) {
        toast.success({
          title: "Status updated",
          description: `Banner is now ${newStatus}.`,
        });
        setBanners((prev) =>
          prev.map((b) =>
            b.id === banner.id ? { ...b, status: newStatus } : b
          )
        );
      } else {
        toast.error({
          title: "Update failed",
          description: result.error,
        });
      }
    } catch {
      toast.error({
        title: "Network error",
        description: "Could not update banner status.",
      });
    }
  };

  return (
    <section className="admin-section space-y-6">
      <header className="admin-page-header flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="admin-page-title text-3xl font-bold tracking-tight">
            Website Banners
          </h1>
          <p className="admin-page-description text-muted-foreground mt-1">
            Manage and organize promotional banners across your website.
          </p>
        </div>
        <Link href="/admin/banners/create">
          <Button className="rounded-xl shadow-lg shadow-primary/20">
            <Plus className="mr-2 h-4 w-4" />
            Add New Banner
          </Button>
        </Link>
      </header>

      {/* Search */}
      <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 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search by title or subtitle..."
            className="pl-9 rounded-xl border-none shadow-sm ring-1 ring-border focus-visible:ring-primary"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        {!isLoading && (
          <p className="text-sm text-muted-foreground">
            {filtered.length} banner{filtered.length !== 1 ? "s" : ""}
          </p>
        )}
      </div>

      {/* Table */}
      <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>Banner Info</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Order</TableHead>
                <TableHead>Last Updated</TableHead>
                <TableHead className="text-right w-56">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 4 }).map((_, i) => <SkeletonRow key={i} />)
              ) : paginated.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="py-20">
                    <div className="flex flex-col items-center text-muted-foreground">
                      <Monitor className="h-10 w-10 mb-3 opacity-30" />
                      <p className="text-sm font-medium">No banners found</p>
                      <p className="text-xs mt-1">
                        Try adjusting your search or add a new banner.
                      </p>
                    </div>
                  </TableCell>
                </TableRow>
              ) : (
                paginated.map((banner) => (
                  <TableRow
                    key={banner.id}
                    className="group hover:bg-muted/10 transition-colors"
                  >
                    {/* Preview thumbnail */}
                    <TableCell className="py-4">
                      <div className="h-12 w-20 rounded-lg overflow-hidden border border-border/50 shadow-sm relative group-hover:scale-105 transition-transform bg-muted">
                        {banner.desktop_image ? (
                          <img
                            src={getImageUrl(banner.desktop_image)}
                            alt={banner.title}
                            className="h-full w-full object-cover"
                          />
                        ) : (
                          <div className="h-full w-full flex items-center justify-center">
                            <Monitor className="h-5 w-5 text-muted-foreground/40" />
                          </div>
                        )}
                      </div>
                    </TableCell>

                    {/* Banner info */}
                    <TableCell>
                      <div className="space-y-1">
                        <h3 className="font-semibold text-sm leading-none">
                          {banner.title}
                        </h3>
                        {banner.subtitle && (
                          <p className="text-xs text-muted-foreground line-clamp-1">
                            {banner.subtitle}
                          </p>
                        )}
                        <div className="flex items-center gap-2 pt-1 opacity-0 group-hover:opacity-100 transition-opacity">
                          {banner.desktop_image && (
                            <Monitor
                              aria-label="Has desktop image"
                              className="h-3 w-3 text-muted-foreground"
                            />
                          )}
                          {banner.tablet_image && (
                            <Tablet
                              aria-label="Has tablet image"
                              className="h-3 w-3 text-muted-foreground"
                            />
                          )}
                          {banner.mobile_image && (
                            <Smartphone
                              aria-label="Has mobile image"
                              className="h-3 w-3 text-muted-foreground"
                            />
                          )}
                        </div>
                      </div>
                    </TableCell>

                    {/* Status */}
                    <TableCell>
                      <Badge
                        variant={
                          banner.status === "active" ? "secondary" : "outline"
                        }
                        className={
                          banner.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"
                        }
                      >
                        {banner.status === "active" ? "Active" : "Inactive"}
                      </Badge>
                    </TableCell>

                    {/* Sort order */}
                    <TableCell>
                      <span className="font-medium text-sm tabular-nums text-muted-foreground">
                        #{banner.sort_order}
                      </span>
                    </TableCell>

                    {/* Date */}
                    <TableCell>
                      <div className="text-xs text-muted-foreground">
                        {banner.updated_at
                          ? new Date(banner.updated_at).toLocaleDateString(
                              "en-IN",
                              {
                                day: "numeric",
                                month: "short",
                                year: "numeric",
                              }
                            )
                          : "—"}
                      </div>
                    </TableCell>

                    {/* Actions */}
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Button
                          variant={
                            banner.status === "active" ? "outline" : "default"
                          }
                          size="sm"
                          onClick={() => handleToggleStatus(banner)}
                          aria-label={`${banner.status === "active" ? "Deactivate" : "Activate"} ${banner.title}`}
                          title={
                            banner.status === "active"
                              ? "Deactivate"
                              : "Activate"
                          }
                        >
                          {banner.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"
                          aria-label={`Edit ${banner.title}`}
                          title="Edit"
                          asChild
                        >
                          <Link href={`/admin/banners/${banner.id}/edit`}>
                            <Edit className="h-4 w-4" aria-hidden="true" />
                          </Link>
                        </Button>
                        <Button
                          variant="destructive"
                          size="sm"
                          onClick={() => setDeleteId(banner.id)}
                          aria-label={`Delete ${banner.title}`}
                          title="Delete"
                        >
                          <Trash2 className="h-4 w-4" aria-hidden="true" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Pagination */}
      {!isLoading && filtered.length > ITEMS_PER_PAGE && (
        <div className="flex items-center justify-between text-xs text-muted-foreground px-2">
          <div>
            Showing{" "}
            {Math.min((currentPage - 1) * ITEMS_PER_PAGE + 1, filtered.length)}–
            {Math.min(currentPage * ITEMS_PER_PAGE, filtered.length)} of{" "}
            {filtered.length}
          </div>
          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="sm"
              className="h-8 rounded-lg"
              disabled={currentPage <= 1}
              onClick={() => setCurrentPage((p) => p - 1)}
            >
              <ChevronLeft className="h-3.5 w-3.5" />
            </Button>
            {Array.from(
              { length: Math.min(totalPages, 5) },
              (_, i) => i + 1
            ).map((page) => (
              <Button
                key={page}
                variant={currentPage === page ? "default" : "outline"}
                size="sm"
                className="h-8 w-8 rounded-lg text-xs"
                onClick={() => setCurrentPage(page)}
              >
                {page}
              </Button>
            ))}
            <Button
              variant="ghost"
              size="sm"
              className="h-8 rounded-lg"
              disabled={currentPage >= totalPages}
              onClick={() => setCurrentPage((p) => p + 1)}
            >
              <ChevronRight className="h-3.5 w-3.5" />
            </Button>
          </div>
        </div>
      )}

      {/* Delete Confirmation */}
      <AlertDialog
        open={!!deleteId}
        onOpenChange={(open) => !open && setDeleteId(null)}
      >
        <AlertDialogContent className="rounded-2xl">
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Banner?</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. The banner will be permanently
              removed from your website.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="rounded-xl">Cancel</AlertDialogCancel>
            <AlertDialogAction
              className="rounded-xl bg-destructive hover:bg-destructive/90"
              onClick={handleDelete}
              disabled={isDeleting}
            >
              {isDeleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              Delete Banner
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </section>
  );
}
