/**
 * DashboardSectionHeader
 *
 * A reusable header component for dashboard sections/cards.
 * Provides consistent layout for title, description, time selectors, and action buttons.
 *
 * @example
 * // Basic usage
 * <DashboardSectionHeader title="Sales Overview" />
 *
 * @example
 * // With time selector and last updated
 * <DashboardSectionHeader
 *   title="Revenue Analytics"
 *   description="Track your daily revenue performance"
 *   lastUpdated={new Date()}
 *   timeSelector={
 *     <Select value={timeRange} onValueChange={setTimeRange}>
 *       <SelectTrigger className="w-[130px] h-9">
 *         <SelectValue />
 *       </SelectTrigger>
 *       <SelectContent>
 *         {TIME_RANGES.map(range => (
 *           <SelectItem key={range.value} value={range.value}>
 *             {range.label}
 *           </SelectItem>
 *         ))}
 *       </SelectContent>
 *     </Select>
 *   }
 * />
 *
 * @example
 * // With actions
 * <DashboardSectionHeader
 *   title="Orders"
 *   actions={
 *     <>
 *       <Button variant="outline" size="sm">Export</Button>
 *       <Button variant="outline" size="sm" onClick={handleRefresh}>
 *         <RefreshCcw className="h-4 w-4" />
 *       </Button>
 *     </>
 *   }
 * />
 */

import React from "react";
import { CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import { TYPOGRAPHY } from "@/lib/dashboard/designTokens";

// =============================================================================
// TYPES
// =============================================================================

export interface DashboardSectionHeaderProps {
  /** Section title */
  title: string;
  /** Optional description shown below title */
  description?: string;
  /** Last updated timestamp - shown as "Last updated: HH:MM AM/PM" */
  lastUpdated?: Date | null;
  /** Custom format function for lastUpdated */
  lastUpdatedFormat?: (date: Date) => string;
  /** Loading state - shows skeletons */
  loading?: boolean;
  /** Time/period selector component (flexible - accepts any selector UI) */
  timeSelector?: React.ReactNode;
  /** Action buttons or other controls */
  actions?: React.ReactNode;
  /** Additional className for the header */
  className?: string;
  /** Use compact padding */
  compact?: boolean;
  /** Size variant for title */
  size?: "default" | "large";
  /** Show the accent bar next to the title (turn off for nested cards) */
  accent?: boolean;
}

// =============================================================================
// HELPER FUNCTIONS
// =============================================================================

const defaultLastUpdatedFormat = (date: Date): string => {
  const time = date.toLocaleTimeString("en-US", {
    hour: "numeric",
    minute: "2-digit",
    hour12: true,
  });
  return `Updated ${time}`;
};

// =============================================================================
// MAIN COMPONENT
// =============================================================================

export const DashboardSectionHeader: React.FC<DashboardSectionHeaderProps> = ({
  title,
  description,
  lastUpdated,
  lastUpdatedFormat = defaultLastUpdatedFormat,
  loading = false,
  timeSelector,
  actions,
  className,
  compact = false,
  size = "default",
  accent = true,
}) => {
  const paddingClass = compact ? "px-4 py-2.5" : "px-4 py-3";
  const titleClass = size === "large"
    ? "text-[14px] font-semibold tracking-tight text-foreground"
    : "text-[12.5px] font-semibold tracking-tight text-foreground";
  void accent; // Studio design has no accent bar; prop kept for call-site compat

  // Loading skeleton
  if (loading) {
    return (
      <CardHeader className={cn("border-b border-muted", paddingClass, className)}>
        <div className="flex justify-between items-start">
          <div className="space-y-1">
            <Skeleton className="h-5 w-40 bg-muted" />
            {description && <Skeleton className="h-4 w-56 bg-muted/60" />}
          </div>
          <div className="flex items-center gap-2">
            {timeSelector && <Skeleton className="h-8 w-[130px] bg-muted rounded-full" />}
            {actions && <Skeleton className="h-8 w-20 bg-muted rounded-full" />}
          </div>
        </div>
      </CardHeader>
    );
  }

  const hasRightContent = timeSelector || actions;

  return (
    <CardHeader className={cn("border-b border-muted", paddingClass, className)}>
      <div className="flex flex-row items-center justify-between gap-3">
        {/* Left side: title (+ optional description / updated time inline) */}
        <div className="min-w-0 flex-1">
          <div className="flex flex-wrap items-baseline gap-x-2.5">
            <CardTitle className={titleClass}>{title}</CardTitle>
            {lastUpdated && !loading && (
              <span className="text-[10.5px] text-muted-foreground/75">
                {lastUpdatedFormat(lastUpdated)}
              </span>
            )}
          </div>
          {description && (
            <CardDescription className={cn(TYPOGRAPHY.cardDescription, "mt-0.5 hidden sm:block")}>
              {description}
            </CardDescription>
          )}
        </div>

        {/* Right side: actions (filters / Details) sit left of the date range
            selector for a consistent order across sections */}
        {hasRightContent && (
          <div className="flex flex-wrap items-center justify-end gap-1.5 flex-shrink-0">
            {actions}
            {timeSelector}
          </div>
        )}
      </div>
    </CardHeader>
  );
};

// =============================================================================
// SKELETON VARIANT
// =============================================================================

export interface DashboardSectionHeaderSkeletonProps {
  hasDescription?: boolean;
  hasTimeSelector?: boolean;
  hasActions?: boolean;
  compact?: boolean;
  className?: string;
}

export const DashboardSectionHeaderSkeleton: React.FC<DashboardSectionHeaderSkeletonProps> = ({
  hasDescription = false,
  hasTimeSelector = true,
  hasActions = false,
  compact = false,
  className,
}) => {
  const paddingClass = compact ? "px-4 py-2.5" : "px-4 py-3";

  return (
    <CardHeader className={cn("border-b border-muted", paddingClass, className)}>
      <div className="flex justify-between items-start">
        <div className="space-y-2">
          <Skeleton className="h-5 w-40 bg-muted" />
          {hasDescription && <Skeleton className="h-4 w-56 bg-muted/60" />}
        </div>
        <div className="flex items-center gap-2">
          {hasTimeSelector && <Skeleton className="h-8 w-[130px] bg-muted rounded-full" />}
          {hasActions && <Skeleton className="h-8 w-20 bg-muted rounded-full" />}
        </div>
      </div>
    </CardHeader>
  );
};

export default DashboardSectionHeader;
