"use client";

import { ReactNode } from "react";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableCell,
} from "@/components/ui/table";
import { Search, Plus, Loader2, AlertTriangle } from "lucide-react";
import { PaginationBar } from "@/components/common/PaginationBar";
import { PaginationMeta } from "@/lib/pagination";

export interface Stat {
  label: string;
  value: string | number;
  icon: React.ComponentType<{ className?: string }>;
  iconBg?: string;
  iconColor?: string;
  change?: string;
  changeColor?: string;
}

interface DataListLayoutProps {
  // Header
  title?: string;
  description?: string;
  addButton?: {
    label: string;
    onClick: () => void;
  };
  // Stats (optional summary cards above the table)
  stats?: Stat[];
  // Extra content between stats and table (e.g. filter dropdowns)
  children?: ReactNode;
  // Search
  search?: {
    value: string;
    onChange: (value: string) => void;
    placeholder?: string;
  };
  itemCountLabel?: string;
  // Table
  tableHeader: ReactNode;
  tableBody: ReactNode;
  colSpan?: number;
  skeletonRows?: number;
  // Pagination — reuses the shared PaginationBar component
  meta?: PaginationMeta;
  onPageChange?: (page: number) => void;
  // States — pass these straight from useQuery
  isLoading?: boolean; // true only on first load (no cached data yet)
  isFetching?: boolean; // true on every background refetch
  isError?: boolean;
  errorTitle?: string;
  errorMessage?: string;
  onRetry?: () => void;
  // Layout
  containerClassName?: string;
}

export function DataListLayout({
  title,
  description,
  addButton,
  stats,
  children,
  search,
  itemCountLabel,
  tableHeader,
  tableBody,
  colSpan = 6,
  skeletonRows = 6,
  meta,
  onPageChange,
  isLoading,
  isFetching,
  isError,
  errorTitle = "Failed to load data",
  errorMessage = "Please try again later.",
  onRetry,
  containerClassName = "space-y-6",
}: DataListLayoutProps) {
  return (
    <div className={containerClassName}>
      {/* Header */}
      {(title || addButton) && (
        <Card className="border-border bg-card shadow-sm">
          <CardHeader className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 py-4 px-5">
            <div>
              {title && (
                <h2 className="text-2xl font-bold tracking-tight text-foreground">
                  {title}
                </h2>
              )}
              {description && (
                <p className="text-muted-foreground text-sm mt-1">
                  {description}
                </p>
              )}
            </div>
            {addButton && (
              <Button
                onClick={addButton.onClick}
                className="bg-primary hover:bg-primary/90 text-primary-foreground font-semibold text-xs h-9 flex items-center gap-2"
              >
                <Plus className="h-4 w-4" /> {addButton.label}
              </Button>
            )}
          </CardHeader>
        </Card>
      )}

      {/* Stats */}
      {stats && stats.length > 0 && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {stats.map((s) => {
            const Icon = s.icon;
            return (
              <Card key={s.label} className="border-border bg-card shadow-sm">
                <CardContent className="p-5">
                  <div className="flex items-center justify-between mb-3">
                    <div
                      className={`w-11 h-11 rounded-xl flex items-center justify-center ${
                        s.iconBg || "bg-primary/10"
                      }`}
                    >
                      <Icon className={`h-5 w-5 ${s.iconColor || "text-primary"}`} />
                    </div>
                    {s.change && (
                      <span
                        className={`text-xs font-medium ${
                          s.changeColor || "text-green-600"
                        }`}
                      >
                        {s.change}
                      </span>
                    )}
                  </div>
                  <p className="text-2xl font-bold text-foreground">{s.value}</p>
                  <p className="text-muted-foreground text-sm mt-1">{s.label}</p>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      {/* Extra content — filters, tabs, etc. Stays static regardless of loading state */}
      {children}

      {/* Table Card */}
      <Card className="border-border bg-card shadow-sm overflow-hidden">
        {(search || itemCountLabel) && (
          <CardHeader className="border-b border-border py-3 px-5">
            <div className="flex flex-col sm:flex-row items-center justify-between gap-2">
              {search && (
                <div className="relative flex-1 sm:w-72">
                  {isFetching ? (
                    <Loader2 className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-primary animate-spin" />
                  ) : (
                    <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
                  )}
                  <Input
                    value={search.value}
                    onChange={(e) => search.onChange(e.target.value)}
                    placeholder={search.placeholder || "Search..."}
                    className="pl-8 h-9 text-sm bg-background border-border"
                  />
                </div>
              )}
              {itemCountLabel && (
                <span className="text-sm text-muted-foreground">
                  {itemCountLabel}
                </span>
              )}
            </div>
          </CardHeader>
        )}

        <CardContent className="p-0 relative">
          {/* Subtle corner indicator for background refetches — table content stays put */}
          {isFetching && !isLoading && (
            <div className="absolute top-3 right-3 z-10">
              <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
            </div>
          )}

          <div className="overflow-x-auto">
            <Table>
              <TableHeader>{tableHeader}</TableHeader>
              <TableBody className="divide-y divide-border">
                {isLoading ? (
                  Array.from({ length: skeletonRows }).map((_, i) => (
                    <TableRow key={`skeleton-${i}`}>
                      <TableCell colSpan={colSpan} className="py-3">
                        <Skeleton className="h-6 w-full" />
                      </TableCell>
                    </TableRow>
                  ))
                ) : isError ? (
                  <TableRow>
                    <TableCell colSpan={colSpan} className="py-16 text-center">
                      <div className="flex flex-col items-center justify-center gap-3">
                        <div className="w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center">
                          <AlertTriangle className="h-5 w-5 text-destructive" />
                        </div>
                        <div>
                          <p className="text-foreground font-semibold">{errorTitle}</p>
                          <p className="text-sm text-muted-foreground mt-1">{errorMessage}</p>
                        </div>
                        {onRetry && (
                          <Button size="sm" onClick={onRetry}>
                            Retry
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ) : (
                  tableBody
                )}
              </TableBody>
            </Table>
          </div>

          {/* Pagination — reuses the shared PaginationBar */}
          {meta && onPageChange && (
            <PaginationBar meta={meta} onPageChange={onPageChange} />
          )}
        </CardContent>
      </Card>
    </div>
  );
}