import React from 'react';
import { Lock } from 'lucide-react';
import { clsx } from 'clsx';
import { PageHeader } from '../layout';
import { Card, Button, StatsGrid, Tabs } from '../ui';
import { ActionButton } from '../layout/PageHeader/PageHeader';

export interface AnalyticsPageLayoutProps {
  /**
   * Page title
   */
  title: string;
  /**
   * Page description
   */
  description: string;
  /**
   * Action buttons for the page header
   */
  actions?: ActionButton[];
  /**
   * Key metrics to display in stats grid
   */
  stats?: Array<{
    title: string;
    value: number | string;
    variant?: 'success' | 'error' | 'warning' | 'info';
    icon?: React.ComponentType<{ className?: string }>;
    subtitle?: string;
    formatter?: (value: any) => string;
  }>;
  /**
   * Number of columns for stats grid (4 or 6)
   */
  statsColumns?: 4 | 6;
  /**
   * Tab configuration
   */
  tabs?: Array<{
    id: string;
    label: string;
    icon?: React.ComponentType<{ className?: string }>;
  }>;
  /**
   * Active tab ID
   */
  activeTab?: string;
  /**
   * Tab change handler
   */
  onTabChange?: (tabId: string) => void;
  /**
   * Optional filters/controls section
   */
  filters?: React.ReactNode;
  /**
   * Loading state for subscription check
   */
  subscriptionLoading?: boolean;
  /**
   * Whether user has access to advanced analytics
   */
  hasAccess?: boolean;
  /**
   * Loading state for data
   */
  dataLoading?: boolean;
  /**
   * Main content (tab content)
   */
  children: React.ReactNode;
  /**
   * Custom className for container
   */
  className?: string;
  /**
   * Show mobile optimization notice
   */
  showMobileNotice?: boolean;
  /**
   * Custom mobile notice text
   */
  mobileNoticeText?: string;
}

/**
 * AnalyticsPageLayout - Standardized layout for analytics pages
 *
 * Provides consistent structure across all analytics pages:
 * 1. Page header with title, description, and actions
 * 2. Optional filters/controls section
 * 3. Key metrics (StatsGrid with 4 or 6 metrics)
 * 4. Tab navigation
 * 5. Tab content area
 * 6. Subscription checks and access control
 * 7. Loading states
 */
export const AnalyticsPageLayout: React.FC<AnalyticsPageLayoutProps> = ({
  title,
  description,
  actions,
  stats,
  statsColumns = 4,
  tabs,
  activeTab,
  onTabChange,
  filters,
  subscriptionLoading = false,
  hasAccess = true,
  dataLoading = false,
  children,
  className,
  showMobileNotice = false,
  mobileNoticeText,
}) => {
  // Show loading state while subscription data is being fetched
  if (subscriptionLoading) {
    return (
      <div className="space-y-6">
        <PageHeader title={title} description={description} />
        <Card className="p-8 text-center">
          <div className="flex flex-col items-center gap-4">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[var(--color-primary)]"></div>
            <p className="text-[var(--text-secondary)]">
              Cargando información de suscripción...
            </p>
          </div>
        </Card>
      </div>
    );
  }

  // If user doesn't have access to advanced analytics, show upgrade message
  if (!hasAccess) {
    return (
      <div className="space-y-6">
        <PageHeader title={title} description={description} />
        <Card className="p-8 text-center">
          <Lock className="mx-auto h-12 w-12 text-[var(--text-tertiary)] mb-4" />
          <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
            Funcionalidad Exclusiva para Profesionales y Empresas
          </h3>
          <p className="text-[var(--text-secondary)] mb-4">
            El análisis avanzado está disponible solo para planes Professional y Enterprise.
            Actualiza tu plan para acceder a métricas avanzadas, análisis detallados y optimización operativa.
          </p>
          <Button
            variant="primary"
            size="md"
            onClick={() => (window.location.hash = '#/app/settings/profile')}
          >
            Actualizar Plan
          </Button>
        </Card>
      </div>
    );
  }

  return (
    <div className={clsx('space-y-6', className)}>
      {/* Page Header */}
      <PageHeader title={title} description={description} actions={actions} />

      {/* Optional Filters/Controls */}
      {filters && <Card className="p-6">{filters}</Card>}

      {/* Key Metrics - StatsGrid */}
      {stats && stats.length > 0 && (
        <StatsGrid
          stats={stats}
          columns={statsColumns}
          loading={dataLoading}
        />
      )}

      {/* Tabs Navigation */}
      {tabs && tabs.length > 0 && activeTab && onTabChange && (
        <Tabs
          items={tabs.map((tab) => ({ id: tab.id, label: tab.label }))}
          activeTab={activeTab}
          onTabChange={onTabChange}
        />
      )}

      {/* Main Content (Tab Content) */}
      <div className="space-y-6">{children}</div>

      {/* Mobile Optimization Notice */}
      {showMobileNotice && (
        <div className="md:hidden p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
          <div className="flex items-start space-x-3">
            <svg
              className="w-5 h-5 mt-0.5 text-blue-600 flex-shrink-0"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
            <div>
              <p className="text-sm font-medium text-blue-600">
                Experiencia Optimizada para Móvil
              </p>
              <p className="text-xs text-[var(--text-secondary)] mt-1">
                {mobileNoticeText ||
                  'Desliza, desplázate e interactúa con los gráficos para explorar los datos.'}
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
