/**
 * 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";
}

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

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

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

export const DashboardSectionHeader: React.FC<DashboardSectionHeaderProps> = ({
  title,
  description,
  lastUpdated,
  lastUpdatedFormat = defaultLastUpdatedFormat,
  loading = false,
  timeSelector,
  actions,
  className,
  compact = false,
  size = "default",
}) => {
  const paddingClass = compact ? "p-4 pb-2" : "p-6 pb-2";
  const titleClass = size === "large"
    ? "text-xl font-semibold text-foreground"
    : "text-lg font-semibold text-foreground";

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

  const hasRightContent = timeSelector || actions || (lastUpdated && !loading);

  return (
    <CardHeader className={cn(paddingClass, className)}>
      <div className="flex justify-between items-start gap-4">
        {/* Left side: Title and description */}
        <div className="min-w-0 flex-1">
          <CardTitle className={titleClass}>{title}</CardTitle>
          {description && (
            <CardDescription className={cn(TYPOGRAPHY.cardDescription, "mt-1")}>
              {description}
            </CardDescription>
          )}
          {lastUpdated && !loading && (
            <p className="text-xs text-muted-foreground mt-1">
              Last updated: {lastUpdatedFormat(lastUpdated)}
            </p>
          )}
        </div>

        {/* Right side: Time selector and actions */}
        {hasRightContent && (
          <div className="flex items-center gap-2 flex-shrink-0">
            {timeSelector}
            {actions}
          </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 ? "p-4 pb-2" : "p-6 pb-4";

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

export default DashboardSectionHeader;
