'use client';

/**
 * Daily Summary Dashboard
 * 
 * Quick view of today's deliveries vs targets
 * Personal stats, charts, and heat map
 */

import { useState } from 'react';
import { usePersonalStats } from '../../../../hooks/use-personal-stats';
import { MobileLayout } from '../../../../components/mobile-layout';
import {
  SkeletonDashboard,
  SkeletonStatsCard,
  SkeletonChart,
} from '../../../../components/ui/skeleton';
import {
  TrendingUp,
  Target,
  Calendar,
  MapPin,
  Award,
  Flame,
  Package,
  School,
  ChevronRight,
  BarChart3,
  RefreshCw,
} from 'lucide-react';

// Simple bar chart component
function SimpleBarChart({ data, height = 120 }: { data: { label: string; value: number }[]; height?: number }) {
  const maxValue = Math.max(...data.map(d => d.value), 1);
  
  return (
    <div className="flex items-end gap-1" style={{ height }}>
      {data.map((item, i) => (
        <div key={i} className="flex-1 flex flex-col items-center gap-1">
          <div
            className="w-full bg-emerald-500 rounded-t transition-all duration-300"
            style={{ height: `${(item.value / maxValue) * 100}%`, minHeight: item.value > 0 ? 4 : 0 }}
          />
          <span className="text-[10px] text-slate-500 truncate w-full text-center">{item.label}</span>
        </div>
      ))}
    </div>
  );
}

// Region heat card
function RegionHeatCard({ 
  region, 
  deliveries, 
  quantity, 
  schools, 
  maxDeliveries 
}: { 
  region: string; 
  deliveries: number; 
  quantity: number; 
  schools: number;
  maxDeliveries: number;
}) {
  const intensity = maxDeliveries > 0 ? deliveries / maxDeliveries : 0;
  const bgOpacity = Math.min(0.9, Math.max(0.2, intensity));
  
  return (
    <div
      className="rounded-xl p-3 transition-all"
      style={{ 
        backgroundColor: `rgba(16, 185, 129, ${bgOpacity})`,
        color: intensity > 0.5 ? 'white' : '#1e293b'
      }}
    >
      <div className="flex items-center justify-between">
        <span className="font-medium text-sm truncate">{region}</span>
        <span className="text-lg font-bold">{deliveries}</span>
      </div>
      <div className="mt-1 flex items-center gap-2 text-xs opacity-80">
        <span>{schools} schools</span>
        <span>•</span>
        <span>{Math.round(quantity)} units</span>
      </div>
    </div>
  );
}

export default function DailySummaryPage() {
  const { stats, dailyBreakdown, regionCoverage, isLoading, refetch } = usePersonalStats();
  const [isRefreshing, setIsRefreshing] = useState(false);

  const handleRefresh = async () => {
    setIsRefreshing(true);
    await refetch();
    setIsRefreshing(false);
  };

  if (isLoading) {
    return (
      <MobileLayout>
        <SkeletonDashboard />
      </MobileLayout>
    );
  }

  // Prepare chart data (last 7 days)
  const last7Days = dailyBreakdown.slice(-7).map(d => ({
    label: new Date(d.date).toLocaleDateString('en-US', { weekday: 'short' }).charAt(0),
    value: d.deliveries,
  }));

  // Pad if less than 7 days
  while (last7Days.length < 7) {
    last7Days.unshift({ label: '-', value: 0 });
  }

  const maxRegionDeliveries = Math.max(...regionCoverage.map(r => r.deliveries), 1);

  return (
    <MobileLayout>
      <div className="pb-24">
        {/* Header */}
        <div className="sticky top-0 z-10 bg-gradient-to-b from-slate-50 to-transparent pb-4 pt-4 px-4">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold text-slate-900">My Stats</h1>
              <p className="text-sm text-slate-500">Your delivery performance</p>
            </div>
            <button
              onClick={handleRefresh}
              disabled={isRefreshing}
              className="p-2 rounded-full bg-white shadow-sm hover:shadow transition-all disabled:opacity-50"
            >
              <RefreshCw className={`h-5 w-5 text-slate-600 ${isRefreshing ? 'animate-spin' : ''}`} />
            </button>
          </div>
        </div>

        <div className="px-4 space-y-6">
          {/* Today's Summary */}
          <div className="rounded-2xl bg-gradient-to-br from-emerald-500 to-teal-600 p-5 text-white shadow-lg">
            <div className="flex items-center gap-2 text-emerald-100 text-sm">
              <Calendar className="h-4 w-4" />
              Today's Progress
            </div>
            <div className="mt-4 grid grid-cols-3 gap-4">
              <div className="text-center">
                <div className="text-3xl font-bold">{stats?.todayDeliveries || 0}</div>
                <div className="text-xs text-emerald-100">Deliveries</div>
              </div>
              <div className="text-center">
                <div className="text-3xl font-bold">{stats?.todaySchools || 0}</div>
                <div className="text-xs text-emerald-100">Schools</div>
              </div>
              <div className="text-center">
                <div className="text-3xl font-bold">{Math.round(stats?.todayQuantity || 0)}</div>
                <div className="text-xs text-emerald-100">Units</div>
              </div>
            </div>
          </div>

          {/* Streak & Achievement */}
          <div className="grid grid-cols-2 gap-4">
            <div className="rounded-xl border border-slate-100 bg-white p-4 shadow-sm">
              <div className="flex items-center gap-2 text-amber-600">
                <Flame className="h-5 w-5" />
                <span className="text-sm font-medium">Streak</span>
              </div>
              <div className="mt-2 text-2xl font-bold text-slate-900">
                {stats?.currentStreak || 0} days
              </div>
              <div className="text-xs text-slate-500">
                Best: {stats?.longestStreak || 0} days
              </div>
            </div>
            <div className="rounded-xl border border-slate-100 bg-white p-4 shadow-sm">
              <div className="flex items-center gap-2 text-blue-600">
                <Award className="h-5 w-5" />
                <span className="text-sm font-medium">Completion</span>
              </div>
              <div className="mt-2 text-2xl font-bold text-slate-900">
                {stats?.completionRate || 0}%
              </div>
              <div className="text-xs text-slate-500">
                Monthly target
              </div>
            </div>
          </div>

          {/* Weekly Chart */}
          <div className="rounded-xl border border-slate-100 bg-white p-4 shadow-sm">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2 text-slate-700">
                <BarChart3 className="h-5 w-5" />
                <span className="font-semibold">Last 7 Days</span>
              </div>
              <span className="text-sm text-slate-500">
                {stats?.weekDeliveries || 0} total
              </span>
            </div>
            <SimpleBarChart data={last7Days} />
          </div>

          {/* Week & Month Stats */}
          <div className="grid grid-cols-2 gap-4">
            <div className="rounded-xl bg-gradient-to-br from-blue-50 to-indigo-50 p-4">
              <div className="flex items-center gap-2 text-blue-700 text-sm">
                <Target className="h-4 w-4" />
                This Week
              </div>
              <div className="mt-2 text-xl font-bold text-slate-900">
                {stats?.weekDeliveries || 0}
                <span className="text-sm font-normal text-slate-500">/{stats?.weekTarget || 35}</span>
              </div>
              <div className="mt-1 h-2 bg-white rounded-full overflow-hidden">
                <div
                  className="h-full bg-blue-500 rounded-full transition-all"
                  style={{ width: `${Math.min(100, ((stats?.weekDeliveries || 0) / (stats?.weekTarget || 35)) * 100)}%` }}
                />
              </div>
            </div>
            <div className="rounded-xl bg-gradient-to-br from-purple-50 to-pink-50 p-4">
              <div className="flex items-center gap-2 text-purple-700 text-sm">
                <TrendingUp className="h-4 w-4" />
                This Month
              </div>
              <div className="mt-2 text-xl font-bold text-slate-900">
                {stats?.monthDeliveries || 0}
                <span className="text-sm font-normal text-slate-500">/{stats?.monthTarget || 150}</span>
              </div>
              <div className="mt-1 h-2 bg-white rounded-full overflow-hidden">
                <div
                  className="h-full bg-purple-500 rounded-full transition-all"
                  style={{ width: `${Math.min(100, ((stats?.monthDeliveries || 0) / (stats?.monthTarget || 150)) * 100)}%` }}
                />
              </div>
            </div>
          </div>

          {/* Average Stats */}
          <div className="grid grid-cols-3 gap-3">
            <div className="rounded-xl border border-slate-100 bg-white p-3 text-center">
              <Package className="h-5 w-5 mx-auto text-emerald-600" />
              <div className="mt-1 text-lg font-bold">{stats?.avgDeliveriesPerDay || 0}</div>
              <div className="text-xs text-slate-500">Avg/day</div>
            </div>
            <div className="rounded-xl border border-slate-100 bg-white p-3 text-center">
              <School className="h-5 w-5 mx-auto text-blue-600" />
              <div className="mt-1 text-lg font-bold">{stats?.monthSchools || 0}</div>
              <div className="text-xs text-slate-500">Schools</div>
            </div>
            <div className="rounded-xl border border-slate-100 bg-white p-3 text-center">
              <MapPin className="h-5 w-5 mx-auto text-purple-600" />
              <div className="mt-1 text-lg font-bold">{regionCoverage.length}</div>
              <div className="text-xs text-slate-500">Regions</div>
            </div>
          </div>

          {/* Region Heat Map */}
          <div className="rounded-xl border border-slate-100 bg-white p-4 shadow-sm">
            <div className="flex items-center gap-2 text-slate-700 mb-4">
              <MapPin className="h-5 w-5" />
              <span className="font-semibold">Region Coverage</span>
            </div>
            {regionCoverage.length > 0 ? (
              <div className="grid grid-cols-2 gap-2">
                {regionCoverage.slice(0, 8).map((region) => (
                  <RegionHeatCard
                    key={region.region}
                    region={region.region}
                    deliveries={region.deliveries}
                    quantity={region.quantity}
                    schools={region.schools}
                    maxDeliveries={maxRegionDeliveries}
                  />
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-slate-400">
                <MapPin className="h-8 w-8 mx-auto mb-2 opacity-50" />
                <p className="text-sm">No region data yet</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </MobileLayout>
  );
}
