// ================================================================
// frontend/src/pages/app/NewDashboardPage.tsx
// ================================================================
/**
 * JTBD-Aligned Dashboard Page
 *
 * Complete redesign based on Jobs To Be Done methodology.
 * Focused on answering: "What requires my attention right now?"
 *
 * Key principles:
 * - Automation-first (show what system did)
 * - Action-oriented (prioritize tasks)
 * - Progressive disclosure (show 20% that matters 80%)
 * - Mobile-first (one-handed operation)
 * - Trust-building (explain system reasoning)
 */

import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { RefreshCw, ExternalLink } from 'lucide-react';
import { useTenant } from '../../stores/tenant.store';
import {
  useBakeryHealthStatus,
  useOrchestrationSummary,
  useActionQueue,
  useProductionTimeline,
  useInsights,
  useApprovePurchaseOrder,
  useStartProductionBatch,
  usePauseProductionBatch,
} from '../../api/hooks/newDashboard';
import { HealthStatusCard } from '../../components/dashboard/HealthStatusCard';
import { ActionQueueCard } from '../../components/dashboard/ActionQueueCard';
import { OrchestrationSummaryCard } from '../../components/dashboard/OrchestrationSummaryCard';
import { ProductionTimelineCard } from '../../components/dashboard/ProductionTimelineCard';
import { InsightsGrid } from '../../components/dashboard/InsightsGrid';
import { ErrorBoundary } from '../../components/ErrorBoundary';

export function NewDashboardPage() {
  const navigate = useNavigate();
  const { currentTenant } = useTenant();
  const tenantId = currentTenant?.id || '';

  // Data fetching
  const {
    data: healthStatus,
    isLoading: healthLoading,
    refetch: refetchHealth,
  } = useBakeryHealthStatus(tenantId);

  const {
    data: orchestrationSummary,
    isLoading: orchestrationLoading,
    refetch: refetchOrchestration,
  } = useOrchestrationSummary(tenantId);

  const {
    data: actionQueue,
    isLoading: actionQueueLoading,
    refetch: refetchActionQueue,
  } = useActionQueue(tenantId);

  const {
    data: productionTimeline,
    isLoading: timelineLoading,
    refetch: refetchTimeline,
  } = useProductionTimeline(tenantId);

  const {
    data: insights,
    isLoading: insightsLoading,
    refetch: refetchInsights,
  } = useInsights(tenantId);

  // Debug logging for data
  useEffect(() => {
    console.log('🔍 Dashboard Data:', {
      healthStatus: healthStatus,
      orchestrationSummary: orchestrationSummary,
      actionQueue: actionQueue,
      productionTimeline: productionTimeline,
      insights: insights,
      loading: {
        health: healthLoading,
        orchestration: orchestrationLoading,
        actionQueue: actionQueueLoading,
        timeline: timelineLoading,
        insights: insightsLoading
      }
    });
  }, [healthStatus, orchestrationSummary, actionQueue, productionTimeline, insights,
      healthLoading, orchestrationLoading, actionQueueLoading, timelineLoading, insightsLoading]);

  // Mutations
  const approvePO = useApprovePurchaseOrder();
  const startBatch = useStartProductionBatch();
  const pauseBatch = usePauseProductionBatch();

  // Handlers
  const handleApprove = async (actionId: string) => {
    try {
      await approvePO.mutateAsync({ tenantId, poId: actionId });
      // Refetch to update UI
      refetchActionQueue();
      refetchHealth();
    } catch (error) {
      console.error('Error approving PO:', error);
    }
  };

  const handleViewDetails = (actionId: string) => {
    // Navigate to appropriate detail page based on action type
    navigate(`/app/operations/procurement`);
  };

  const handleModify = (actionId: string) => {
    navigate(`/app/operations/procurement`);
  };

  const handleStartBatch = async (batchId: string) => {
    try {
      await startBatch.mutateAsync({ tenantId, batchId });
      refetchTimeline();
      refetchHealth();
    } catch (error) {
      console.error('Error starting batch:', error);
    }
  };

  const handlePauseBatch = async (batchId: string) => {
    try {
      await pauseBatch.mutateAsync({ tenantId, batchId });
      refetchTimeline();
      refetchHealth();
    } catch (error) {
      console.error('Error pausing batch:', error);
    }
  };

  const handleRefreshAll = () => {
    refetchHealth();
    refetchOrchestration();
    refetchActionQueue();
    refetchTimeline();
    refetchInsights();
  };

  return (
    <div className="min-h-screen bg-gray-50 pb-20 md:pb-8">
      {/* Mobile-optimized container */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-3xl md:text-4xl font-bold text-gray-900">Panel de Control</h1>
            <p className="text-gray-600 mt-1">Your bakery at a glance</p>
          </div>
          <button
            onClick={handleRefreshAll}
            className="flex items-center gap-2 px-4 py-2 bg-white hover:bg-gray-50 border border-gray-300 rounded-lg font-semibold text-gray-700 transition-colors duration-200"
          >
            <RefreshCw className="w-5 h-5" />
            <span className="hidden sm:inline">Refresh</span>
          </button>
        </div>

        {/* Main Dashboard Layout */}
        <div className="space-y-6">
          {/* SECTION 1: Bakery Health Status */}
          <ErrorBoundary componentName="HealthStatusCard">
            <HealthStatusCard healthStatus={healthStatus} loading={healthLoading} />
          </ErrorBoundary>

          {/* SECTION 2: What Needs Your Attention (Action Queue) */}
          <ErrorBoundary componentName="ActionQueueCard">
            <ActionQueueCard
              actionQueue={actionQueue}
              loading={actionQueueLoading}
              onApprove={handleApprove}
              onViewDetails={handleViewDetails}
              onModify={handleModify}
            />
          </ErrorBoundary>

          {/* SECTION 3: What the System Did for You (Orchestration Summary) */}
          <ErrorBoundary componentName="OrchestrationSummaryCard">
            <OrchestrationSummaryCard
              summary={orchestrationSummary}
              loading={orchestrationLoading}
            />
          </ErrorBoundary>

          {/* SECTION 4: Today's Production Timeline */}
          <ErrorBoundary componentName="ProductionTimelineCard">
            <ProductionTimelineCard
              timeline={productionTimeline}
              loading={timelineLoading}
              onStart={handleStartBatch}
              onPause={handlePauseBatch}
            />
          </ErrorBoundary>

          {/* SECTION 5: Quick Insights Grid */}
          <ErrorBoundary componentName="InsightsGrid">
            <div>
              <h2 className="text-2xl font-bold text-gray-900 mb-4">Key Metrics</h2>
              <InsightsGrid insights={insights} loading={insightsLoading} />
            </div>
          </ErrorBoundary>

          {/* SECTION 6: Quick Action Links */}
          <div className="bg-white rounded-xl shadow-md p-6">
            <h2 className="text-xl font-bold text-gray-900 mb-4">Quick Actions</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
              <button
                onClick={() => navigate('/app/operations/procurement')}
                className="flex items-center justify-between p-4 bg-blue-50 hover:bg-blue-100 rounded-lg transition-colors duration-200 group"
              >
                <span className="font-semibold text-blue-900">View Orders</span>
                <ExternalLink className="w-5 h-5 text-blue-600 group-hover:translate-x-1 transition-transform duration-200" />
              </button>

              <button
                onClick={() => navigate('/app/operations/production')}
                className="flex items-center justify-between p-4 bg-green-50 hover:bg-green-100 rounded-lg transition-colors duration-200 group"
              >
                <span className="font-semibold text-green-900">Production</span>
                <ExternalLink className="w-5 h-5 text-green-600 group-hover:translate-x-1 transition-transform duration-200" />
              </button>

              <button
                onClick={() => navigate('/app/database/inventory')}
                className="flex items-center justify-between p-4 bg-purple-50 hover:bg-purple-100 rounded-lg transition-colors duration-200 group"
              >
                <span className="font-semibold text-purple-900">Inventory</span>
                <ExternalLink className="w-5 h-5 text-purple-600 group-hover:translate-x-1 transition-transform duration-200" />
              </button>

              <button
                onClick={() => navigate('/app/database/suppliers')}
                className="flex items-center justify-between p-4 bg-amber-50 hover:bg-amber-100 rounded-lg transition-colors duration-200 group"
              >
                <span className="font-semibold text-amber-900">Suppliers</span>
                <ExternalLink className="w-5 h-5 text-amber-600 group-hover:translate-x-1 transition-transform duration-200" />
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Mobile-friendly bottom padding */}
      <div className="h-20 md:hidden"></div>
    </div>
  );
}
