<script>
  import { onMount } from 'svelte';
  import { 
    Clock, 
    CheckCircle2, 
    AlertTriangle, 
    Users,
    TrendingUp,
    PieChart,
    Plus,
    UserCircle,
    FlaskConical,
    FileText,
    ChevronRight,
    RefreshCw
  } from 'lucide-svelte';
  import { fetchOrders } from '$lib/api/orders.js';
  import { fetchResults } from '$lib/api/results.js';
  import { fetchPatients } from '$lib/api/patients.js';
  import { goto } from '$app/navigation';
  import { error as toastError } from '$lib/utils/toast.js';

  // Stats state
  let stats = $state({
    pendingOrders: 0,
    todayResults: 0,
    criticalResults: 0,
    activePatients: 0
  });
  let loading = $state(true);
  let recentActivity = $state([]);

  // Fetch dashboard data
  async function loadDashboardData() {
    loading = true;
    try {
      // Fetch pending orders (SCH - Scheduled status)
      const ordersResponse = await fetchOrders({ 
        OrderStatus: 'SCH',
        perPage: 1 
      });
      stats.pendingOrders = ordersResponse.total || 0;

      // Fetch today's results (we'll get all and filter)
      const today = new Date().toISOString().split('T')[0];
      const resultsResponse = await fetchResults({ 
        per_page: 100
      });
      
      const allResults = resultsResponse.data || [];
      
      // Count today's results
      const todayResults = allResults.filter(r => {
        if (!r.ResultDateTime) return false;
        const resultDate = new Date(r.ResultDateTime).toISOString().split('T')[0];
        return resultDate === today;
      });
      stats.todayResults = todayResults.length;

      // Count critical results (H or L flags)
      const criticalResults = allResults.filter(r => {
        const value = parseFloat(r.Result);
        if (isNaN(value)) return false;
        const isHigh = r.High !== null && value > r.High;
        const isLow = r.Low !== null && value < r.Low;
        return isHigh || isLow;
      });
      stats.criticalResults = criticalResults.length;

      // Fetch active patients
      const patientsResponse = await fetchPatients({ perPage: 1 });
      stats.activePatients = patientsResponse.total || 0;

      // Generate recent activity from data
      recentActivity = generateRecentActivity(allResults, ordersResponse.data || []);

    } catch (err) {
      toastError('Failed to load dashboard data');
      console.error('Dashboard error:', err);
    } finally {
      loading = false;
    }
  }

  function generateRecentActivity(results, orders) {
    const activities = [];
    
    // Add recent results
    const recentResults = results
      .filter(r => r.ResultDateTime)
      .sort((a, b) => new Date(b.ResultDateTime) - new Date(a.ResultDateTime))
      .slice(0, 3);
    
    recentResults.forEach(r => {
      activities.push({
        type: 'result',
        time: new Date(r.ResultDateTime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
        title: `Result: ${r.TestSiteCode}`,
        description: `Order: ${r.OrderNumber || 'N/A'}`,
        icon: CheckCircle2,
        color: 'secondary'
      });
    });

    // Add recent orders
    const recentOrders = orders
      .filter(o => o.CreateDate)
      .sort((a, b) => new Date(b.CreateDate) - new Date(a.CreateDate))
      .slice(0, 2);
    
    recentOrders.forEach(o => {
      activities.push({
        type: 'order',
        time: new Date(o.CreateDate).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
        title: `Order #${o.OrderID}`,
        description: `Patient: ${o.InternalPID || 'N/A'}`,
        icon: Plus,
        color: 'primary'
      });
    });

    // Sort by time and take top 5
    return activities
      .sort((a, b) => {
        const timeA = new Date(`2024-01-01 ${a.time}`);
        const timeB = new Date(`2024-01-01 ${b.time}`);
        return timeB - timeA;
      })
      .slice(0, 5);
  }

  function navigateTo(path) {
    goto(path);
  }

  onMount(() => {
    loadDashboardData();
  });
</script>

<div class="p-4">
  <!-- Header with refresh -->
  <div class="flex items-center justify-between mb-4">
    <h1 class="text-2xl font-bold text-primary">Dashboard</h1>
    <button 
      class="btn btn-sm btn-ghost" 
      onclick={loadDashboardData}
      disabled={loading}
    >
      <RefreshCw class="w-4 h-4 {loading ? 'animate-spin' : ''}" />
    </button>
  </div>

  <!-- Summary Stats -->
  <div class="stats stats-vertical lg:stats-horizontal shadow w-full mb-4 bg-base-100/80 backdrop-blur">
    <!-- Pending Orders -->
    <div 
      class="stat border-l-4 border-primary hover:bg-primary/5 transition-colors py-2 cursor-pointer"
      onclick={() => navigateTo('/orders')}
    >
      <div class="stat-figure text-primary">
        <Clock class="w-6 h-6" />
      </div>
      <div class="stat-title text-primary font-medium text-sm">Pending Orders</div>
      <div class="stat-value text-primary text-2xl">
        {#if loading}
          <span class="loading loading-spinner loading-sm"></span>
        {:else}
          {stats.pendingOrders}
        {/if}
      </div>
      <div class="stat-desc text-primary/70 text-xs">Scheduled for analysis</div>
    </div>

    <!-- Today's Results -->
    <div 
      class="stat border-l-4 border-secondary hover:bg-secondary/5 transition-colors py-2 cursor-pointer"
      onclick={() => navigateTo('/results')}
    >
      <div class="stat-figure text-secondary">
        <CheckCircle2 class="w-6 h-6" />
      </div>
      <div class="stat-title text-secondary font-medium text-sm">Today's Results</div>
      <div class="stat-value text-secondary text-2xl">
        {#if loading}
          <span class="loading loading-spinner loading-sm"></span>
        {:else}
          {stats.todayResults}
        {/if}
      </div>
      <div class="stat-desc text-secondary/70 text-xs">Results entered today</div>
    </div>

    <!-- Critical Results -->
    <div 
      class="stat border-l-4 border-error hover:bg-error/5 transition-colors py-2 cursor-pointer"
      onclick={() => navigateTo('/results')}
    >
      <div class="stat-figure text-error">
        <AlertTriangle class="w-6 h-6" />
      </div>
      <div class="stat-title text-error font-medium text-sm">Critical Results</div>
      <div class="stat-value text-error text-2xl">
        {#if loading}
          <span class="loading loading-spinner loading-sm"></span>
        {:else}
          {stats.criticalResults}
        {/if}
      </div>
      <div class="stat-desc text-error/70 text-xs">Requires attention</div>
    </div>

    <!-- Active Patients -->
    <div 
      class="stat border-l-4 border-accent hover:bg-accent/5 transition-colors py-2 cursor-pointer"
      onclick={() => navigateTo('/patients')}
    >
      <div class="stat-figure text-accent">
        <Users class="w-6 h-6" />
      </div>
      <div class="stat-title text-accent font-medium text-sm">Active Patients</div>
      <div class="stat-value text-accent text-2xl">
        {#if loading}
          <span class="loading loading-spinner loading-sm"></span>
        {:else}
          {stats.activePatients}
        {/if}
      </div>
      <div class="stat-desc text-accent/70 text-xs">Currently in system</div>
    </div>
  </div>

  <!-- Charts Section -->
  <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">
    <!-- Orders Trend Card -->
    <div class="card bg-base-100 shadow border-t-4 border-primary hover:shadow-lg transition-shadow">
      <div class="card-body p-4">
        <div class="flex items-center justify-between mb-3">
          <h2 class="card-title text-primary text-base flex items-center gap-2">
            <TrendingUp class="w-4 h-4" />
            Orders Trend
          </h2>
          <button class="btn btn-xs btn-ghost" onclick={() => navigateTo('/orders')}>
            View All <ChevronRight class="w-3 h-3" />
          </button>
        </div>
        <div class="h-48 flex flex-col items-center justify-center bg-gradient-to-br from-primary/10 to-accent/10 rounded-lg border border-primary/20">
          <div class="text-center">
            <FlaskConical class="w-12 h-12 text-primary/30 mb-2" />
            <p class="text-primary/60 text-sm">Order analytics coming soon</p>
            <p class="text-primary/40 text-xs mt-1">Track orders over time</p>
          </div>
        </div>
      </div>
    </div>

    <!-- Results Volume Card -->
    <div class="card bg-base-100 shadow border-t-4 border-secondary hover:shadow-lg transition-shadow">
      <div class="card-body p-4">
        <div class="flex items-center justify-between mb-3">
          <h2 class="card-title text-secondary text-base flex items-center gap-2">
            <PieChart class="w-4 h-4" />
            Results Volume
          </h2>
          <button class="btn btn-xs btn-ghost" onclick={() => navigateTo('/results')}>
            View All <ChevronRight class="w-3 h-3" />
          </button>
        </div>
        <div class="h-48 flex flex-col items-center justify-center bg-gradient-to-br from-secondary/10 to-accent/10 rounded-lg border border-secondary/20">
          <div class="text-center">
            <FileText class="w-12 h-12 text-secondary/30 mb-2" />
            <p class="text-secondary/60 text-sm">Results analytics coming soon</p>
            <p class="text-secondary/40 text-xs mt-1">Results by test type</p>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Recent Activity -->
  <div class="card bg-base-100 shadow border-t-4 border-primary hover:shadow-lg transition-shadow">
    <div class="card-body p-4">
      <h2 class="card-title mb-3 text-primary text-base flex items-center gap-2">
        <Clock class="w-4 h-4" />
        Recent Activity
      </h2>
      
      {#if loading}
        <div class="flex justify-center p-4">
          <span class="loading loading-spinner loading-md text-primary"></span>
        </div>
      {:else if recentActivity.length === 0}
        <div class="text-center p-4 text-base-content/50">
          <Clock class="w-8 h-8 mx-auto mb-2 opacity-30" />
          <p class="text-sm">No recent activity</p>
        </div>
      {:else}
        <ul class="timeline timeline-vertical timeline-compact">
          {#each recentActivity as activity, i}
            <li>
              <div class="timeline-middle">
                <div class="w-8 h-8 rounded-full bg-{activity.color}/10 flex items-center justify-center">
                  <svelte:component this={activity.icon} class="w-4 h-4 text-{activity.color}" />
                </div>
              </div>
              <div class="timeline-start timeline-box bg-gradient-to-r from-{activity.color}/5 to-white border-l-4 border-{activity.color} p-2">
                <time class="text-xs font-mono text-{activity.color}">{activity.time}</time>
                <div class="text-base font-bold text-{activity.color}/90">{activity.title}</div>
                <div class="text-xs text-{activity.color}/70">{activity.description}</div>
              </div>
              {#if i < recentActivity.length - 1}
                <hr class="bg-{activity.color}/30"/>
              {/if}
            </li>
          {/each}
        </ul>
      {/if}
    </div>
  </div>
</div>
