'use client';

import { MobileLayout } from '@/components/mobile-layout';
import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import api from '../../../lib/api-client';
import { smartRound } from '../../../lib/utils';
import { useSupplierDirectory } from '../../../hooks/use-supplier-directory';
import { NetworkStatusIndicator, useNetworkStatus } from '../../../components/ui/network-status';
import { UrgentAnnouncementBanner, AnnouncementFeed } from '../../../components/notifications/announcement-feed';
import { OfflineQueuePanel, ConflictBadge } from '../../../components/delivery/conflict-resolution';
import { usePullToRefresh, useHaptic, useAppBadge } from '../../../hooks/use-ux-enhancements';
import { useOfflineSync } from '../../../hooks/use-offline-sync';
import { useAnnouncements } from '../../../hooks/use-announcements';
import { GcxLoading } from '../../../components/ui/gcx-loading';
import { 
  Plus, 
  Users, 
  History, 
  User, 
  Settings, 
  MapPin, 
  CheckSquare, 
  Lightbulb,
  ChevronRight,
  Truck,
  Eye,
  BarChart3,
  FileText,
  CloudOff,
  Bell,
  Zap
} from 'lucide-react';

const QUICK_TOOLS = [
  {
    id: 'campus-navigator',
    title: 'Recent Schools',
    description: 'Your last 5 visited schools',
    icon: <MapPin className="h-6 w-6 text-blue-600" />,
    bg: 'bg-blue-50',
    text: 'text-blue-700'
  },
  {
    id: 'my-stats',
    title: 'My Stats',
    description: 'View your personal performance',
    icon: <BarChart3 className="h-6 w-6 text-purple-600" />,
    bg: 'bg-purple-50',
    text: 'text-purple-700',
    link: '/field-staff/stats'
  },
  {
    id: 'templates',
    title: 'Delivery Templates',
    description: 'Reuse saved delivery patterns',
    icon: <FileText className="h-6 w-6 text-teal-600" />,
    bg: 'bg-teal-50',
    text: 'text-teal-700',
    link: '/field-staff/templates'
  },
  {
    id: 'pack-prep',
    title: 'Pre-Delivery Checklist',
    description: 'Complete these steps before submitting',
    icon: <CheckSquare className="h-6 w-6 text-amber-600" />,
    bg: 'bg-amber-50',
    text: 'text-amber-700'
  },
  {
    id: 'quick-tips',
    title: 'Quick Tips',
    description: 'Essential field staff reminders',
    icon: <Lightbulb className="h-6 w-6 text-emerald-600" />,
    bg: 'bg-emerald-50',
    text: 'text-emerald-700'
  },
];

export default function FieldStaffDashboard() {
  const router = useRouter();
  const [expandedTool, setExpandedTool] = useState<string | null>(null);
  const [user, setUser] = useState<any>(null);
  const [greeting, setGreeting] = useState('Hello');
  const [showAnnouncements, setShowAnnouncements] = useState(false);
  const [showOfflineQueue, setShowOfflineQueue] = useState(false);

  // PWA enhancement hooks
  const { isOnline } = useNetworkStatus();
  const haptic = useHaptic();
  const { setBadge: setBadgeCount } = useAppBadge();
  
  // Offline sync hooks
  const { 
    queue, 
    pendingCount, 
    failedCount, 
    conflicts, 
    conflictCount,
    removeFromQueue, 
    retryDelivery,
    resolveConflict,
    syncAll
  } = useOfflineSync();
  
  // Derive hasConflicts from conflictCount
  const hasConflicts = conflictCount > 0;
  
  // Announcements
  const { unreadCount: announcementUnreadCount } = useAnnouncements();

  const {
    suppliers,
    isRefreshing: suppliersRefreshing,
    lastRefreshed: suppliersLastSyncedAt,
    stats: supplierStats,
    error: suppliersError,
    refreshSuppliers,
  } = useSupplierDirectory();

  // Set greeting after mount to avoid hydration mismatch
  useEffect(() => {
    const hour = new Date().getHours();
    setGreeting(hour < 12 ? 'Good morning' : hour < 17 ? 'Good afternoon' : 'Good evening');
  }, []);

  // Load user from localStorage
  useEffect(() => {
    const userData = localStorage.getItem('gcx_fshs_user');
    if (userData) {
      setUser(JSON.parse(userData));
    }
  }, []);

  // Update app badge with pending items
  useEffect(() => {
    const totalPending = pendingCount + failedCount + conflictCount;
    setBadgeCount(totalPending);
  }, [pendingCount, failedCount, conflictCount, setBadgeCount]);

  // Fetch live dashboard stats
  const {
    data: deliveriesData,
    isLoading: statsLoading,
    isFetching,
    refetch,
    dataUpdatedAt,
  } = useQuery({
    queryKey: ['my-deliveries'],
    staleTime: 5_000,
    gcTime: 0,
    refetchInterval: 15_000,
    refetchIntervalInBackground: true,
    refetchOnWindowFocus: true,
    refetchOnReconnect: true,
    queryFn: async () => {
      const response = await api.get('/deliveries', {
        params: { 
          cache_bust: Date.now(),
          per_page: 200, // Increased from default 20 to prevent counter sticking
        },
      });
      const data = response.data.data;
      if (Array.isArray(data)) {
        return data;
      } else if (data && Array.isArray(data.items)) {
        return data.items;
      } else if (data && Array.isArray(data.deliveries)) {
        return data.deliveries;
      }
      return [];
    },
  });

  // Fetch accurate schools_served count from backend (avoids pagination window distortion)
  const {
    data: backendStats,
    refetch: refetchStats,
  } = useQuery({
    queryKey: ['field-staff-stats'],
    staleTime: 10_000,
    gcTime: 0,
    refetchInterval: 30_000,
    refetchIntervalInBackground: false,
    refetchOnWindowFocus: true,
    refetchOnReconnect: true,
    queryFn: async () => {
      const response = await api.get('/field-staff/stats');
      return response.data?.data ?? response.data ?? null;
    },
  });

  // Pull-to-refresh handler
  const handlePullToRefresh = useCallback(async () => {
    haptic.light();
    await Promise.all([
      refetch(),
      refetchStats(),
      refreshSuppliers(),
    ]);
    haptic.success();
  }, [refetch, refetchStats, refreshSuppliers, haptic]);

  const { isPulling, isRefreshing, pullDistance, containerRef } = usePullToRefresh({
    onRefresh: handlePullToRefresh,
    threshold: 80,
  });
  const pullState = isRefreshing
    ? 'refreshing'
    : isPulling
      ? (pullDistance >= 80 ? 'ready' : 'pulling')
      : 'idle';

  // Calculate stats from deliveries
  const calculateStats = () => {
    const deliveries = Array.isArray(deliveriesData) ? deliveriesData : [];
    const weekStart = new Date();
    weekStart.setDate(weekStart.getDate() - weekStart.getDay() + 1);
    weekStart.setHours(0, 0, 0, 0);
    
    const thisWeek = deliveries.filter((d: any) => new Date(d.delivery_date) >= weekStart);
    const totalQuantity = thisWeek.reduce((sum: any, d: any) => sum + parseFloat(d.actual_quantity || 0), 0);
    // Use backend count (covers full history, not just the 200-row page window).
    // Fall back to client-side distinct count only if the endpoint hasn't replied yet.
    const schoolsServed: number =
      backendStats?.schools_served != null
        ? (backendStats.schools_served as number)
        : new Set(deliveries.map((d: any) => d.school_id)).size;
    
    return {
      deliveries_this_week: thisWeek.length,
      tonnage_captured: smartRound(totalQuantity),
      schools_served: schoolsServed,
      last_sync: deliveries.length > 0 ? 'Just now' : 'Never',
    };
  };

  const stats = calculateStats();
  const lastSyncText = statsLoading
    ? 'Syncing…'
    : dataUpdatedAt
      ? new Date(dataUpdatedAt).toLocaleString(undefined, {
          dateStyle: 'medium',
          timeStyle: 'short',
        })
      : 'Never';

  const formatLastVisit = (timestamp: string) => {
    try {
      return new Date(timestamp).toLocaleString(undefined, {
        dateStyle: 'medium',
        timeStyle: 'short',
      });
    } catch (error) {
      return timestamp;
    }
  };

  // Get last 5 unique schools visited
  const getRecentSchools = () => {
    const deliveries = Array.isArray(deliveriesData) ? [...deliveriesData] : [];
    const schoolMap = new Map<number, {
      id: number;
      name: string;
      code: string;
      region: string;
      lastVisit: string;
    }>();
    
    deliveries
      .sort((a: any, b: any) => {
        const aTimestamp = a.recorded_at || a.updated_at || a.delivery_date;
        const bTimestamp = b.recorded_at || b.updated_at || b.delivery_date;
        return new Date(bTimestamp).getTime() - new Date(aTimestamp).getTime();
      })
      .forEach((d: any) => {
        if (!schoolMap.has(d.school_id)) {
          schoolMap.set(d.school_id, {
            id: d.school_id,
            name: d.school_name || 'Unnamed School',
            code: d.school_code || 'Code unavailable',
            region: d.school_region || 'Region unavailable',
            lastVisit: d.recorded_at || d.updated_at || d.delivery_date,
          });
        }
      });
    
    return Array.from(schoolMap.values()).slice(0, 5);
  };

  const recentSchools = getRecentSchools();

  // Check if user has seen welcome screen
  useEffect(() => {
    const hasSeenWelcome = localStorage.getItem('gcx_fshs_welcome_seen');
    if (!hasSeenWelcome) {
      router.push('/field-staff/welcome');
    }
  }, [router]);

  // Show skeleton while loading
  if (statsLoading) {
    return (
      <MobileLayout>
        <GcxLoading className="min-h-[calc(100vh-8rem)]" />
      </MobileLayout>
    );
  }

  return (
    <MobileLayout>
      {/* Network Status Indicator */}
      <NetworkStatusIndicator />
      
      {/* Urgent Announcements */}
      <UrgentAnnouncementBanner />

      {/* Pull-to-refresh container */}
      <div 
        ref={containerRef}
        className="max-w-full overflow-x-hidden pb-24 relative"
      >
        {/* Pull-to-refresh indicator */}
        {pullState !== 'idle' && (
          <div 
            className="absolute top-0 left-0 right-0 flex justify-center items-center transition-all z-40"
            style={{ height: Math.min(pullDistance, 80), opacity: Math.min(pullDistance / 80, 1) }}
          >
            <div className={`flex items-center gap-2 ${pullState === 'refreshing' ? 'animate-pulse' : ''}`}>
              <svg 
                className={`h-5 w-5 text-emerald-600 ${pullState === 'refreshing' ? 'animate-spin' : ''}`} 
                fill="none" 
                viewBox="0 0 24 24" 
                stroke="currentColor"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
              <span className="text-sm font-medium text-emerald-600">
                {pullState === 'pulling' && 'Pull to refresh'}
                {pullState === 'ready' && 'Release to refresh'}
                {pullState === 'refreshing' && 'Refreshing...'}
              </span>
            </div>
          </div>
        )}
        {/* Hero Header with Greeting */}
        <div className="relative overflow-hidden bg-gradient-to-br from-emerald-500 via-teal-600 to-cyan-500 px-5 pb-20 pt-6">
          {/* Background Pattern */}
          <div className="absolute inset-0 opacity-10">
            <div className="absolute -right-10 -top-10 h-40 w-40 rounded-full bg-white"></div>
            <div className="absolute -bottom-20 -left-10 h-60 w-60 rounded-full bg-white"></div>
          </div>
          
          <div className="relative">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-emerald-100">{greeting},</p>
                <h1 className="mt-0.5 text-2xl font-bold text-white">
                  {user?.name || 'Field Lead'} 👋
                </h1>
              </div>
              <div className="flex items-center gap-2">
                {/* Offline Queue Indicator */}
                {(pendingCount > 0 || failedCount > 0) && (
                  <button
                    onClick={() => {
                      haptic.light();
                      setShowOfflineQueue(true);
                    }}
                    className="relative flex h-10 w-10 items-center justify-center rounded-full bg-white/20 backdrop-blur-sm transition-all active:scale-95"
                    title="Offline queue"
                  >
                    <CloudOff className="h-5 w-5 text-white" />
                    <span className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full bg-amber-500 text-[10px] font-bold text-white">
                      {pendingCount + failedCount}
                    </span>
                  </button>
                )}
                
                {/* Conflict Badge */}
                {hasConflicts && (
                  <ConflictBadge onClick={() => setShowOfflineQueue(true)} />
                )}
                
                {/* Announcements Button */}
                <button
                  onClick={() => {
                    haptic.light();
                    setShowAnnouncements(!showAnnouncements);
                  }}
                  className="relative flex h-10 w-10 items-center justify-center rounded-full bg-white/20 backdrop-blur-sm transition-all active:scale-95"
                  title="Announcements"
                >
                  <Bell className="h-5 w-5 text-white" />
                  {announcementUnreadCount > 0 && (
                    <span className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold text-white">
                      {announcementUnreadCount}
                    </span>
                  )}
                </button>

                {/* Sync Button */}
                <button
                  onClick={() => {
                    haptic.light();
                    refetch();
                  }}
                  disabled={isFetching}
                  title="Sync now"
                  aria-label="Sync now"
                  className="flex h-10 w-10 items-center justify-center rounded-full bg-white/20 backdrop-blur-sm transition-all active:scale-95 disabled:opacity-60"
                >
                  <svg className={`h-5 w-5 text-white ${isFetching ? 'animate-spin' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                </button>
              </div>
            </div>
            
            <p className="mt-2 text-sm text-emerald-100 flex items-center gap-2">
              {!isOnline && (
                <span className="inline-flex items-center gap-1 rounded-full bg-amber-500/30 px-2 py-0.5 text-xs font-medium text-amber-100">
                  <CloudOff className="h-3 w-3" /> Offline
                </span>
              )}
              Last synced {lastSyncText}
            </p>
          </div>
        </div>

        {/* Stats Cards - Floating over hero */}
        <div className="relative z-10 -mt-14 px-4">
          <div className="grid grid-cols-2 gap-3">
            <div className="rounded-2xl bg-white p-4 shadow-lg shadow-emerald-500/20">
              <div className="flex items-center gap-2">
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gradient-to-br from-emerald-100 to-cyan-100">
                  <svg className="h-4 w-4 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                </div>
                <span className="text-xs font-medium text-slate-500">This Week</span>
              </div>
              {statsLoading ? (
                <div className="mt-2 h-9 w-12 animate-pulse rounded-lg bg-slate-100"></div>
              ) : (
                <p className="mt-2 text-3xl font-bold text-slate-900">{stats.deliveries_this_week}</p>
              )}
              <p className="text-xs text-slate-500">deliveries made</p>
            </div>
            
            <div className="rounded-2xl bg-white p-4 shadow-lg shadow-cyan-500/20">
              <div className="flex items-center gap-2">
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gradient-to-br from-amber-100 to-orange-100">
                  <svg className="h-4 w-4 text-amber-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                  </svg>
                </div>
                <span className="text-xs font-medium text-slate-500">Schools</span>
              </div>
              {statsLoading ? (
                <div className="mt-2 h-9 w-12 animate-pulse rounded-lg bg-slate-100"></div>
              ) : (
                <p className="mt-2 text-3xl font-bold text-slate-900">{stats.schools_served}</p>
              )}
              <p className="text-xs text-slate-500">schools served</p>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="mt-4 space-y-4 px-4">
          {/* Announcement Feed (collapsible) */}
          {showAnnouncements && (
            <div className="animate-in slide-in-from-top duration-200">
              <AnnouncementFeed maxItems={3} />
            </div>
          )}

          {/* Offline Queue Panel */}
          {showOfflineQueue && (
            <OfflineQueuePanel
              pendingCount={pendingCount}
              failedCount={failedCount}
              conflictCount={conflictCount}
              isSyncing={false}
              onSyncAll={() => {
                syncAll();
                setShowOfflineQueue(false);
              }}
              onViewConflicts={() => {
                // Could open a conflicts modal here
                console.log('View conflicts:', conflicts);
              }}
            />
          )}

          {/* Primary Action */}
          <button
            onClick={() => router.push('/field-staff/new-delivery')}
            className="group relative w-full overflow-hidden rounded-2xl bg-gradient-to-r from-emerald-500 to-teal-600 p-6 text-left shadow-lg shadow-emerald-500/30 transition-all active:scale-[0.98]"
          >
            <div className="absolute right-0 top-0 h-32 w-32 -translate-y-8 translate-x-8 rounded-full bg-white/10 blur-2xl transition-transform group-active:scale-150"></div>
            <div className="relative z-10 flex items-center justify-between">
              <div>
                <h2 className="text-xl font-bold text-white">New Delivery</h2>
                <p className="mt-1 text-sm text-emerald-100">Record a drop-off at a school</p>
              </div>
              <div className="flex h-12 w-12 items-center justify-center rounded-full bg-white/20 backdrop-blur-sm">
                <Plus className="h-6 w-6 text-white" />
              </div>
            </div>
          </button>

          {/* See Something Say Something Banner */}
          <button
            onClick={() => router.push('/field-staff/see-something-say-something')}
            className="w-full rounded-2xl bg-gradient-to-r from-slate-900 to-slate-800 p-1 shadow-lg relative overflow-hidden group active:scale-[0.98] transition-all"
          >
             <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition">
                <Eye className="w-32 h-32 text-white -mr-10 -mt-10" />
             </div>
             
             <div className="bg-slate-900/50 backdrop-blur-sm rounded-xl p-5 border border-white/10 h-full">
                <div className="relative z-10 flex items-center justify-between">
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <div className="w-2 h-2 rounded-full bg-red-500 animate-pulse" />
                        <h3 className="font-bold text-white text-lg tracking-tight">See Something?</h3>
                      </div>
                      <p className="text-slate-400 text-sm font-medium">Say Something. Report anonymously.</p>
                    </div>
                    <div className="bg-white/10 p-2.5 rounded-full backdrop-blur-md group-hover:bg-white/20 transition-colors">
                        <ChevronRight className="w-5 h-5 text-white" />
                    </div>
                </div>
             </div>
          </button>

          {/* Action Grid */}
          <div className="grid grid-cols-2 gap-3">
            <button
              onClick={() => router.push('/field-staff/suppliers')}
              className="flex flex-col items-center justify-center gap-2 rounded-2xl bg-white p-4 shadow-sm transition-all active:scale-[0.98] active:bg-slate-50"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-50 text-blue-600">
                <Users className="h-5 w-5" />
              </div>
              <span className="text-sm font-semibold text-slate-700">Suppliers</span>
            </button>
            
            <button
              onClick={() => router.push('/field-staff/my-deliveries')}
              className="flex flex-col items-center justify-center gap-2 rounded-2xl bg-white p-4 shadow-sm transition-all active:scale-[0.98] active:bg-slate-50"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-amber-50 text-amber-600">
                <History className="h-5 w-5" />
              </div>
              <span className="text-sm font-semibold text-slate-700">History</span>
            </button>

            <button
              onClick={() => router.push('/field-staff/profile')}
              className="flex flex-col items-center justify-center gap-2 rounded-2xl bg-white p-4 shadow-sm transition-all active:scale-[0.98] active:bg-slate-50"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-purple-50 text-purple-600">
                <User className="h-5 w-5" />
              </div>
              <span className="text-sm font-semibold text-slate-700">Profile</span>
            </button>

            <button
              onClick={() => router.push('/field-staff/settings')}
              className="flex flex-col items-center justify-center gap-2 rounded-2xl bg-white p-4 shadow-sm transition-all active:scale-[0.98] active:bg-slate-50"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-slate-100 text-slate-600">
                <Settings className="h-5 w-5" />
              </div>
              <span className="text-sm font-semibold text-slate-700">Settings</span>
            </button>
          </div>

          {/* Quick Tools Section */}
          <div>
            <div className="flex items-center justify-between px-1 mb-3">
              <h2 className="text-base font-bold text-slate-900">Quick Tools</h2>
              <span className="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-500">
                {QUICK_TOOLS.length} tools
              </span>
            </div>

            <div className="space-y-3">
              {QUICK_TOOLS.map((tool) => (
                <div 
                  key={tool.id} 
                  className="overflow-hidden rounded-2xl bg-white shadow-sm transition-all"
                >
                  <button
                    onClick={() => {
                      haptic.light();
                      if ('link' in tool && tool.link) {
                        router.push(tool.link);
                      } else {
                        setExpandedTool(expandedTool === tool.id ? null : tool.id);
                      }
                    }}
                    className="flex w-full items-center gap-4 p-4 text-left transition-colors active:bg-slate-50"
                  >
                    <div className={`flex h-12 w-12 items-center justify-center rounded-xl text-2xl ${tool.bg}`}>
                      {tool.icon}
                    </div>
                    <div className="flex-1">
                      <h3 className="text-sm font-semibold text-slate-900">{tool.title}</h3>
                      <p className="text-xs text-slate-500 mt-0.5">{tool.description}</p>
                    </div>
                    <div className={`flex h-8 w-8 items-center justify-center rounded-full transition-all ${
                      'link' in tool ? 'bg-slate-50' : expandedTool === tool.id ? 'bg-slate-100 rotate-180' : 'bg-slate-50'
                    }`}>
                      <ChevronRight className={`h-5 w-5 text-slate-400 transition-transform ${
                        !('link' in tool) && expandedTool === tool.id ? 'rotate-90' : ''
                      }`} />
                    </div>
                  </button>
                  
                  {expandedTool === tool.id && !('link' in tool) && (
                    <div className="border-t border-slate-100 bg-slate-50/50 p-4">
                      {/* Campus Navigator - Recent Schools */}
                      {tool.id === 'campus-navigator' && (
                        <div className="space-y-2">
                          {recentSchools.length === 0 ? (
                            <div className="rounded-xl bg-white p-6 text-center">
                              <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-slate-100">
                                <MapPin className="h-6 w-6 text-slate-400" />
                              </div>
                              <p className="text-sm font-medium text-slate-700">No recent schools</p>
                              <p className="mt-1 text-xs text-slate-500">Record a delivery to see schools here</p>
                            </div>
                          ) : (
                            recentSchools.map((school) => (
                              <button
                                key={school.id}
                                onClick={() => router.push(`/field-staff/new-delivery?school_id=${school.id}`)}
                                className="flex w-full items-center gap-3 rounded-xl bg-white p-3 text-left shadow-sm transition-all active:scale-[0.99]"
                              >
                                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-emerald-50">
                                  <MapPin className="h-5 w-5 text-emerald-600" />
                                </div>
                                <div className="flex-1 min-w-0">
                                  <p className="text-sm font-semibold text-slate-900 truncate">{school.name}</p>
                                  <p className="text-xs text-slate-500">{school.code} • {school.region}</p>
                                </div>
                                <div className="text-right">
                                  <p className="text-xs text-emerald-600 font-medium">{formatLastVisit(school.lastVisit)}</p>
                                  <ChevronRight className="ml-auto h-4 w-4 text-slate-300" />
                                </div>
                              </button>
                            ))
                          )}
                        </div>
                      )}

                      {/* Pack Prep Checklist */}
                      {tool.id === 'pack-prep' && (
                        <div className="space-y-3">
                          {[
                            { id: 'docs', label: 'Delivery documentation ready' },
                            { id: 'verified', label: 'Commodity verified' },
                            { id: 'photo', label: 'Photos taken (optional)' },
                            { id: 'contact', label: 'School contact confirmed' },
                          ].map((item) => (
                            <label key={item.id} className="flex items-center gap-3 rounded-xl bg-white p-3 shadow-sm cursor-pointer transition-colors hover:bg-slate-50">
                              <input 
                                type="checkbox" 
                                id={item.id} 
                                className="h-5 w-5 rounded-lg border-2 border-slate-200 text-emerald-500 focus:ring-emerald-500" 
                              />
                              <span className="text-sm font-medium text-slate-700">{item.label}</span>
                            </label>
                          ))}
                          <button 
                            onClick={() => router.push('/field-staff/new-delivery')}
                            className="mt-2 w-full rounded-xl bg-gradient-to-r from-emerald-500 to-teal-500 px-4 py-3.5 text-sm font-semibold text-white shadow-lg shadow-emerald-500/30 transition-all active:scale-[0.98]"
                          >
                            Ready? Record Delivery →
                          </button>
                        </div>
                      )}

                      {/* Quick Tips */}
                      {tool.id === 'quick-tips' && (
                        <div className="space-y-2">
                          {[
                            { icon: '✅', title: 'Always verify quantities', desc: 'Double-check before recording', bg: 'bg-emerald-50', text: 'text-emerald-700' },
                            { icon: '📱', title: 'Work offline anytime', desc: 'Syncs automatically when online', bg: 'bg-blue-50', text: 'text-blue-700' },
                            { icon: '�', title: 'Take photo proof', desc: 'Document deliveries with photos', bg: 'bg-purple-50', text: 'text-purple-700' },
                            { icon: '🎤', title: 'Voice notes supported', desc: 'Add audio memos to deliveries', bg: 'bg-pink-50', text: 'text-pink-700' },
                            { icon: '�📊', title: 'Check supply balance', desc: 'Review stock before delivery', bg: 'bg-amber-50', text: 'text-amber-700' },
                          ].map((tip, i) => (
                            <div key={i} className={`flex items-start gap-3 rounded-xl ${tip.bg} p-3`}>
                              <span className="text-lg">{tip.icon}</span>
                              <div>
                                <p className={`text-sm font-semibold ${tip.text}`}>{tip.title}</p>
                                <p className={`text-xs ${tip.text} opacity-80`}>{tip.desc}</p>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>

        </div>
      </div>
    </MobileLayout>
  );
}
