
'use client';

import { LayoutShell } from '../../../../components/layout-shell';
import { useEffect, useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import api from '../../../../lib/api-client';
import { BarChart3, Layers, LineChart as LineIcon, PieChart as PieIcon, Filter, Calendar, MapPin, Sparkles, AlertTriangle, Printer, FileDown } from 'lucide-react';
import {
  BarChart,
  Bar,
  LineChart,
  Line,
  PieChart,
  Pie,
  Tooltip,
  ResponsiveContainer,
  XAxis,
  YAxis,
  CartesianGrid,
  Legend,
  Cell,
} from 'recharts';
import { smartRound } from '../../../../lib/utils';
import dynamic from 'next/dynamic';
import 'leaflet/dist/leaflet.css';

const MapContainer = dynamic(() => import('react-leaflet').then((mod) => mod.MapContainer), { ssr: false });
const TileLayer = dynamic(() => import('react-leaflet').then((mod) => mod.TileLayer), { ssr: false });
const Marker = dynamic(() => import('react-leaflet').then((mod) => mod.Marker), { ssr: false });
const Popup = dynamic(() => import('react-leaflet').then((mod) => mod.Popup), { ssr: false });

const GROUP_OPTIONS = [
  { value: 'commodity', label: 'Commodity' },
  { value: 'region', label: 'Region' },
  { value: 'supplier', label: 'Supplier' },
  { value: 'user', label: 'User' },
  { value: 'school', label: 'School' },
  { value: 'month', label: 'Month' },
];

const COLORS = ['#4F46E5', '#06B6D4', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#14B8A6', '#F97316'];

// Helper to get week ranges
const getWeekRanges = () => {
  const weeks = [];
  const today = new Date();
  
  // Current week
  const currentWeekStart = new Date(today);
  currentWeekStart.setDate(today.getDate() - today.getDay() + 1); // Monday
  const currentWeekEnd = new Date(currentWeekStart);
  currentWeekEnd.setDate(currentWeekStart.getDate() + 6); // Sunday
  
  weeks.push({
    label: 'This Week',
    from: currentWeekStart.toISOString().split('T')[0],
    to: currentWeekEnd.toISOString().split('T')[0],
  });
  
  // Generate past 12 weeks
  for (let i = 1; i <= 12; i++) {
    const weekStart = new Date(currentWeekStart);
    weekStart.setDate(currentWeekStart.getDate() - (7 * i));
    const weekEnd = new Date(weekStart);
    weekEnd.setDate(weekStart.getDate() + 6);
    
    const startStr = weekStart.toLocaleDateString('en-GB', { day: '2-digit', month: 'short' });
    const endStr = weekEnd.toLocaleDateString('en-GB', { day: '2-digit', month: 'short' });
    
    weeks.push({
      label: `${startStr} - ${endStr}`,
      from: weekStart.toISOString().split('T')[0],
      to: weekEnd.toISOString().split('T')[0],
    });
  }
  
  return weeks;
};

// Group data by school for display
const groupBySchool = (data: any[]) => {
  if (!data || data.length === 0) return [];
  
  const grouped: Record<string, {
    school_id: string;
    school_name: string;
    school_region: string;
    commodities: any[];
    totals: {
      total_expected: number;
      total_received: number;
      difference: number;
      delivery_count: number;
    };
  }> = {};
  
  data.forEach((row: any) => {
    const schoolId = row.school_id;
    if (!grouped[schoolId]) {
      grouped[schoolId] = {
        school_id: schoolId,
        school_name: row.school_name,
        school_region: row.school_region || '',
        commodities: [],
        totals: {
          total_expected: 0,
          total_received: 0,
          difference: 0,
          delivery_count: 0,
        },
      };
    }
    
    grouped[schoolId].commodities.push(row);
    grouped[schoolId].totals.total_expected += parseFloat(row.total_expected) || 0;
    grouped[schoolId].totals.total_received += parseFloat(row.total_received) || 0;
    grouped[schoolId].totals.difference += parseFloat(row.difference) || 0;
    grouped[schoolId].totals.delivery_count += parseInt(row.delivery_count) || 0;
  });
  
  return Object.values(grouped).sort((a, b) => {
    // Sort by region, then by school name
    if (a.school_region !== b.school_region) {
      return (a.school_region || '').localeCompare(b.school_region || '');
    }
    return a.school_name.localeCompare(b.school_name);
  });
};

export default function DeliveryReportsPage() {
  const [groupBy, setGroupBy] = useState('commodity');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [planPeriodId, setPlanPeriodId] = useState('');
  const [schoolId, setSchoolId] = useState('');
  const [commodityId, setCommodityId] = useState('');
  const [selectedWeek, setSelectedWeek] = useState('');
  const [regionFilter, setRegionFilter] = useState('');
  
  const weekRanges = useMemo(() => getWeekRanges(), []);

  // Handle week selection
  const handleWeekChange = (value: string) => {
    setSelectedWeek(value);
    if (value) {
      const week = weekRanges.find(w => w.label === value);
      if (week) {
        setDateFrom(week.from);
        setDateTo(week.to);
      }
    } else {
      setDateFrom('');
      setDateTo('');
    }
  };

  const { data: schoolsData } = useQuery({
    queryKey: ['schools-lookup'],
    queryFn: async () => {
      const response = await api.get('/schools');
      return response.data?.data || [];
    }
  });

  const { data: commoditiesData } = useQuery({
    queryKey: ['commodities-lookup'],
    queryFn: async () => {
      const response = await api.get('/commodities');
      return response.data?.data || [];
    }
  });
  
  // Get unique regions from schools
  const regions = useMemo(() => {
    if (!schoolsData) return [];
    const uniqueRegions = [...new Set<string>(schoolsData.map((s: any) => String(s.region || '')).filter(Boolean))];
    return uniqueRegions.sort();
  }, [schoolsData]);

  const { data: detailedData } = useQuery({
    queryKey: ['delivery-reports-details', dateFrom, dateTo, planPeriodId, schoolId, commodityId, regionFilter],
    queryFn: async () => {
      const response = await api.get('/reports/deliveries/details', {
        params: {
          date_from: dateFrom || undefined,
          date_to: dateTo || undefined,
          plan_period_id: planPeriodId || undefined,
          school_id: schoolId || undefined,
          commodity_id: commodityId || undefined,
          region: regionFilter || undefined,
        }
      });
      return response.data || { data: [], totals: {} };
    },
  });
  
  // Group detailed data by school
  const groupedSchools = useMemo(() => {
    return groupBySchool(detailedData?.data || []);
  }, [detailedData]);

  const { data, isLoading } = useQuery({
    queryKey: ['delivery-reports', groupBy, dateFrom, dateTo, planPeriodId],
    queryFn: async () => {
      const response = await api.get('/reports/deliveries', {
        params: {
          group_by: groupBy,
          date_from: dateFrom || undefined,
          date_to: dateTo || undefined,
          plan_period_id: planPeriodId || undefined,
        }
      });
      return response.data;
    },
  });

  const { data: insights } = useQuery({
    queryKey: ['delivery-reports-insights', dateFrom, dateTo, planPeriodId],
    queryFn: async () => {
      const response = await api.get('/reports/deliveries/insights', {
        params: {
          date_from: dateFrom || undefined,
          date_to: dateTo || undefined,
          plan_period_id: planPeriodId || undefined,
        }
      });
      return response.data;
    },
  });

  const { data: mapData } = useQuery({
    queryKey: ['delivery-reports-map', dateFrom, dateTo, planPeriodId],
    queryFn: async () => {
      const response = await api.get('/reports/deliveries/map', {
        params: {
          date_from: dateFrom || undefined,
          date_to: dateTo || undefined,
          plan_period_id: planPeriodId || undefined,
        }
      });
      return response.data;
    },
  });

  const groups = data?.groups ?? [];
  const series = data?.series ?? [];
  const totals = data?.totals ?? { deliveries_count: 0, total_quantity: 0, flagged_count: 0 };
  const heatmap = insights?.heatmap ?? [];
  const clusters = insights?.clusters ?? [];
  const topSchools = insights?.top_schools ?? {};
  const anomalies = insights?.anomalies ?? [];
  const mapPoints = mapData?.points ?? [];

  const topGroups = useMemo(() => groups.slice(0, 8), [groups]);
  const heatmapMeta = useMemo(() => {
    const regions = Array.from(new Set<string>(heatmap.map((row: any) => String(row.region))));
    const commodities = Array.from(new Set<string>(heatmap.map((row: any) => String(row.commodity))));
    const maxValue = heatmap.reduce((max: number, row: any) => Math.max(max, Number(row.total_quantity || 0)), 0);
    return { regions, commodities, maxValue };
  }, [heatmap]);

  const getHeatColor = (value: number) => {
    const ratio = heatmapMeta.maxValue ? value / heatmapMeta.maxValue : 0;
    const alpha = Math.min(0.85, Math.max(0.15, ratio));
    return `rgba(99, 102, 241, ${alpha})`;
  };

  useEffect(() => {
    import('leaflet').then(({ default: L }) => {
      L.Icon.Default.mergeOptions({
        iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
        iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
        shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png',
      });
    });
  }, []);

  return (
    <LayoutShell role="SUPER_ADMIN">
      <div className="space-y-8">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
          <div>
            <h1 className="text-3xl font-bold tracking-tight text-slate-900">Delivery Intelligence Hub</h1>
            <p className="text-sm text-slate-500">Advanced reporting with live grouping, trend insights, and anomaly context.</p>
          </div>
          <div className="flex items-center gap-2 rounded-full bg-white px-4 py-2 text-sm font-semibold text-brand shadow-sm">
            <BarChart3 className="h-4 w-4" />
            Intelligent Reporting
          </div>
        </div>

        <div className="grid grid-cols-1 gap-4 lg:grid-cols-4">
          <div className="rounded-2xl bg-gradient-to-br from-indigo-500 to-indigo-700 p-6 text-white shadow-lg">
            <div className="text-xs uppercase tracking-wide text-indigo-100">Total Deliveries</div>
            <div className="mt-2 text-3xl font-bold">{totals.deliveries_count}</div>
            <div className="mt-2 text-indigo-100">Across all sources</div>
          </div>
          <div className="rounded-2xl bg-gradient-to-br from-emerald-500 to-teal-600 p-6 text-white shadow-lg">
            <div className="text-xs uppercase tracking-wide text-emerald-100">Total Quantity</div>
            <div className="mt-2 text-3xl font-bold">{smartRound(totals.total_quantity)}</div>
            <div className="mt-2 text-emerald-100">Aggregate volume</div>
          </div>
          <div className="rounded-2xl bg-gradient-to-br from-amber-500 to-orange-600 p-6 text-white shadow-lg">
            <div className="text-xs uppercase tracking-wide text-amber-100">Flagged Deliveries</div>
            <div className="mt-2 text-3xl font-bold">{totals.flagged_count}</div>
            <div className="mt-2 text-amber-100">Needs review</div>
          </div>
          <div className="rounded-2xl bg-gradient-to-br from-slate-800 to-slate-900 p-6 text-white shadow-lg">
            <div className="text-xs uppercase tracking-wide text-slate-300">Grouping</div>
            <div className="mt-2 text-xl font-semibold">{GROUP_OPTIONS.find(o => o.value === groupBy)?.label}</div>
            <div className="mt-2 text-slate-300">Dynamic perspective</div>
          </div>
        </div>

        <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div className="flex items-center gap-2 text-sm font-semibold text-slate-700">
              <Filter className="h-4 w-4" /> Filters
            </div>
            <div className="flex flex-wrap items-center gap-3">
              <div className="flex items-center gap-2 rounded-full bg-slate-50 px-3 py-1 text-sm text-slate-600">
                <Layers className="h-4 w-4" />
                <select
                  value={groupBy}
                  onChange={(e) => setGroupBy(e.target.value)}
                  className="bg-transparent outline-none"
                >
                  {GROUP_OPTIONS.map((opt) => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </div>
              <div className="flex items-center gap-2 rounded-full bg-slate-50 px-3 py-1 text-sm text-slate-600">
                <Calendar className="h-4 w-4" />
                <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)} className="bg-transparent outline-none" />
                <span className="text-slate-400">–</span>
                <input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)} className="bg-transparent outline-none" />
              </div>
              <input
                type="number"
                value={planPeriodId}
                onChange={(e) => setPlanPeriodId(e.target.value)}
                placeholder="Plan Period ID"
                className="rounded-full border border-slate-200 px-4 py-2 text-sm"
              />
              <button
                onClick={() => {
                  const params = new URLSearchParams();
                  if (planPeriodId) params.append('plan_period_id', planPeriodId);
                  if (dateFrom) params.append('date_from', dateFrom);
                  if (dateTo) params.append('date_to', dateTo);
                  window.open(`/super-admin/delivery-reports/landscape?${params.toString()}`, '_blank');
                }}
                className="flex items-center gap-2 rounded-full bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 transition shadow-sm"
              >
                <FileDown className="h-4 w-4" />
                Landscape Report
              </button>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
            <div className="mb-4 flex items-center justify-between">
              <div className="flex items-center gap-2 text-sm font-semibold text-slate-700">
                <BarChart3 className="h-4 w-4 text-brand" /> Top {GROUP_OPTIONS.find(o => o.value === groupBy)?.label}
              </div>
              <span className="text-xs text-slate-400">Total quantity</span>
            </div>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={topGroups} margin={{ top: 5, right: 20, left: -10, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" vertical={false} />
                  <XAxis dataKey="group_name" tick={{ fontSize: 10 }} interval={0} angle={-20} textAnchor="end" height={60} />
                  <YAxis tick={{ fontSize: 10 }} />
                  <Tooltip />
                  <Bar dataKey="total_quantity" fill="#4F46E5" radius={[6, 6, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>

          <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
            <div className="mb-4 flex items-center justify-between">
              <div className="flex items-center gap-2 text-sm font-semibold text-slate-700">
                <PieIcon className="h-4 w-4 text-brand" /> Distribution Share
              </div>
              <span className="text-xs text-slate-400">Top 8</span>
            </div>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie data={topGroups} dataKey="total_quantity" nameKey="group_name" outerRadius={90} innerRadius={50}>
                    {topGroups.map((_: any, index: number) => (
                      <Cell key={index} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip />
                  <Legend verticalAlign="bottom" height={36} />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </div>
        </div>

        <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
          <div className="mb-4 flex items-center justify-between">
            <div className="flex items-center gap-2 text-sm font-semibold text-slate-700">
              <LineIcon className="h-4 w-4 text-brand" /> Delivery Momentum
            </div>
            <span className="text-xs text-slate-400">Daily totals</span>
          </div>
          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={series} margin={{ top: 5, right: 20, left: -10, bottom: 5 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} />
                <XAxis dataKey="date" tick={{ fontSize: 10 }} />
                <YAxis tick={{ fontSize: 10 }} />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="total_quantity" stroke="#10B981" strokeWidth={2} dot={false} />
                <Line type="monotone" dataKey="deliveries_count" stroke="#6366F1" strokeWidth={2} dot={false} />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </div>

        <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
          <div className="mb-4 flex items-center justify-between">
            <div className="text-sm font-semibold text-slate-700">Grouped Results</div>
            <span className="text-xs text-slate-400">Showing top 50</span>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-slate-50 text-slate-500">
                <tr>
                  <th className="px-4 py-2 text-left">Group</th>
                  <th className="px-4 py-2 text-right">Deliveries</th>
                  <th className="px-4 py-2 text-right">Total Qty</th>
                  <th className="px-4 py-2 text-right">Flagged</th>
                </tr>
              </thead>
              <tbody>
                {isLoading ? (
                  <tr>
                    <td colSpan={4} className="px-4 py-6 text-center text-slate-500">Loading...</td>
                  </tr>
                ) : groups.length === 0 ? (
                  <tr>
                    <td colSpan={4} className="px-4 py-6 text-center text-slate-500">No data found</td>
                  </tr>
                ) : (
                  groups.map((row: any, idx: number) => (
                    <tr key={`${row.group_id}-${idx}`} className="border-b last:border-none hover:bg-slate-50">
                      <td className="px-4 py-2 font-medium text-slate-900">{row.group_name || 'Unknown'}</td>
                      <td className="px-4 py-2 text-right">{row.deliveries_count}</td>
                      <td className="px-4 py-2 text-right">{smartRound(row.total_quantity)}</td>
                      <td className="px-4 py-2 text-right text-amber-600">{row.flagged_count}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>

        <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
          <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm lg:col-span-2">
            <div className="mb-4 flex items-center justify-between">
              <div className="flex items-center gap-2 text-sm font-semibold text-slate-700">
                <Sparkles className="h-4 w-4 text-brand" /> Heatmap: Region × Commodity
              </div>
              <span className="text-xs text-slate-400">Intensity by total quantity</span>
            </div>
            <div className="overflow-x-auto">
              <div className="min-w-[640px]">
                <div className="grid" style={{ gridTemplateColumns: `160px repeat(${heatmapMeta.commodities.length || 1}, minmax(110px, 1fr))` }}>
                  <div className="p-2 text-xs font-semibold text-slate-500">Region</div>
                  {heatmapMeta.commodities.map((commodity: string) => (
                    <div key={commodity} className="p-2 text-xs font-semibold text-slate-500 text-center">
                      {commodity}
                    </div>
                  ))}
                  {heatmapMeta.regions.map((region: string) => (
                    <>
                      <div key={`${region}-label`} className="p-2 text-xs font-semibold text-slate-600">
                        {region}
                      </div>
                      {heatmapMeta.commodities.map((commodity: string) => {
                        const cell = heatmap.find((row: any) => row.region === region && row.commodity === commodity);
                        const value = cell ? Number(cell.total_quantity) : 0;
                        return (
                          <div
                            key={`${region}-${commodity}`}
                            className="m-1 flex items-center justify-center rounded-lg p-2 text-[11px] font-semibold text-white"
                            style={{ backgroundColor: getHeatColor(value) }}
                            title={`${region} • ${commodity}: ${smartRound(value)}`}
                          >
                            {value ? smartRound(value) : '-'}
                          </div>
                        );
                      })}
                    </>
                  ))}
                </div>
              </div>
            </div>
          </div>

          <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
            <div className="mb-4 flex items-center justify-between">
              <div className="flex items-center gap-2 text-sm font-semibold text-slate-700">
                <AlertTriangle className="h-4 w-4 text-amber-500" /> Anomaly Ribbons
              </div>
            </div>
            <div className="space-y-2">
              {anomalies.length === 0 ? (
                <div className="text-sm text-slate-500">No anomalies detected.</div>
              ) : (
                anomalies.map((row: any, idx: number) => (
                  <div key={`${row.reason}-${idx}`} className="flex items-center justify-between rounded-full border border-amber-100 bg-amber-50 px-4 py-2 text-sm">
                    <span className="font-medium text-amber-800">{row.reason}</span>
                    <span className="rounded-full bg-amber-200 px-2 py-0.5 text-xs font-semibold text-amber-900">{row.count}</span>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>

        <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
          <div className="mb-4 flex items-center justify-between">
            <div className="flex items-center gap-2 text-sm font-semibold text-slate-700">
              <MapPin className="h-4 w-4 text-brand" /> Geo-clusters by Region
            </div>
            <span className="text-xs text-slate-400">Top regions by volume</span>
          </div>
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            {clusters.length === 0 ? (
              <div className="text-sm text-slate-500">No cluster data available.</div>
            ) : (
              clusters.map((cluster: any) => (
                <div key={cluster.region} className="rounded-xl border border-slate-100 bg-slate-50 p-4">
                  <div className="flex items-center justify-between">
                    <div className="text-sm font-semibold text-slate-900">{cluster.region}</div>
                    <span className="rounded-full bg-slate-200 px-2 py-0.5 text-xs font-semibold text-slate-700">
                      {cluster.deliveries_count} deliveries
                    </span>
                  </div>
                  <div className="mt-2 text-2xl font-bold text-brand">{smartRound(cluster.total_quantity)}</div>
                  <div className="mt-1 text-xs text-amber-600">Flagged: {cluster.flagged_count}</div>
                  <div className="mt-3 space-y-1 text-xs text-slate-500">
                    {(topSchools?.[cluster.region] || []).map((school: any, idx: number) => (
                      <div key={`${cluster.region}-school-${idx}`} className="flex items-center justify-between">
                        <span className="truncate">{school.school_name}</span>
                        <span className="font-semibold text-slate-700">{smartRound(school.total_quantity)}</span>
                      </div>
                    ))}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
          <div className="mb-4 flex items-center justify-between">
            <div className="flex items-center gap-2 text-sm font-semibold text-slate-700">
              <MapPin className="h-4 w-4 text-brand" /> Ghana Delivery Map
            </div>
            <span className="text-xs text-slate-400">Click a pin for school + supplier summary</span>
          </div>
          <div className="h-[520px] overflow-hidden rounded-2xl border border-slate-100">
            <MapContainer center={[7.9465, -1.0232]} zoom={6} scrollWheelZoom className="h-full w-full">
              <TileLayer
                attribution="&copy; OpenStreetMap contributors"
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
              />
              {mapPoints.map((point: any) => (
                <Marker key={point.school_id} position={[point.lat, point.lng]}>
                  <Popup>
                    <div className="space-y-2 text-sm">
                      <div className="text-base font-semibold text-slate-900">{point.school_name}</div>
                      <div className="text-xs text-slate-500">
                        {point.region || 'Unknown Region'}
                        {point.approximate ? ` • ${point.source === 'region-centroid' ? 'Region centroid' : 'Geocoded'}` : ''}
                      </div>
                      <div className="grid grid-cols-2 gap-2 text-xs">
                        <div>
                          <div className="text-slate-500">Deliveries</div>
                          <div className="font-semibold">{point.deliveries_count}</div>
                        </div>
                        <div>
                          <div className="text-slate-500">Total Qty</div>
                          <div className="font-semibold">{smartRound(point.total_quantity)}</div>
                        </div>
                        <div>
                          <div className="text-slate-500">Flagged</div>
                          <div className="font-semibold text-amber-600">{point.flagged_count}</div>
                        </div>
                        <div>
                          <div className="text-slate-500">Last Delivery</div>
                          <div className="font-semibold">{point.latest_delivery_date || '—'}</div>
                        </div>
                      </div>
                      <div className="pt-2">
                        <div className="text-xs font-semibold text-slate-700">Suppliers</div>
                        <div className="mt-1 space-y-1">
                          {(point.suppliers || []).length === 0 ? (
                            <div className="text-xs text-slate-400">No suppliers linked</div>
                          ) : (
                            point.suppliers.slice(0, 5).map((supplier: any, idx: number) => (
                              <div key={`${point.school_id}-supplier-${idx}`} className="flex items-center justify-between text-xs">
                                <span className="truncate">{supplier.supplier_name}</span>
                                <span className="font-semibold text-slate-700">{smartRound(supplier.total_quantity)}</span>
                              </div>
                            ))
                          )}
                        </div>
                      </div>
                    </div>
                  </Popup>
                </Marker>
              ))}
            </MapContainer>
          </div>
        </div>

        {/* Detailed Report Section - Printable */}
        <div className="printable-report rounded-2xl border border-slate-100 bg-white p-6 shadow-sm print:shadow-none print:border-none print:p-0 print:m-0">
          <div className="mb-4 flex flex-col gap-4 print:hidden">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2 text-sm font-semibold text-slate-700">
                <FileDown className="h-4 w-4 text-brand" /> Detailed Delivery Report (Grouped by School)
              </div>
              <button 
                onClick={() => window.print()}
                className="flex items-center gap-2 rounded-full bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-700"
              >
                <Printer className="h-4 w-4" /> Print / PDF
              </button>
            </div>
            
            {/* Enhanced Filters */}
            <div className="flex flex-wrap items-center gap-3 p-4 bg-slate-50 rounded-xl">
              {/* Week Quick Select */}
              <div className="flex flex-col gap-1">
                <label className="text-xs font-medium text-slate-500">Quick Week Select</label>
                <select
                  value={selectedWeek}
                  onChange={(e) => handleWeekChange(e.target.value)}
                  className="rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none bg-white min-w-[180px]"
                >
                  <option value="">All Time</option>
                  {weekRanges.map((week) => (
                    <option key={week.label} value={week.label}>{week.label}</option>
                  ))}
                </select>
              </div>
              
              {/* Custom Date Range */}
              <div className="flex flex-col gap-1">
                <label className="text-xs font-medium text-slate-500">Custom Date Range</label>
                <div className="flex items-center gap-2">
                  <input 
                    type="date" 
                    value={dateFrom} 
                    onChange={(e) => { setDateFrom(e.target.value); setSelectedWeek(''); }}
                    className="rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none bg-white" 
                  />
                  <span className="text-slate-400">to</span>
                  <input 
                    type="date" 
                    value={dateTo} 
                    onChange={(e) => { setDateTo(e.target.value); setSelectedWeek(''); }}
                    className="rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none bg-white" 
                  />
                </div>
              </div>
              
              {/* Region Filter */}
              <div className="flex flex-col gap-1">
                <label className="text-xs font-medium text-slate-500">Region</label>
                <select
                  value={regionFilter}
                  onChange={(e) => setRegionFilter(e.target.value)}
                  className="rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none bg-white min-w-[150px]"
                >
                  <option value="">All Regions</option>
                  {regions.map((r: string) => (
                    <option key={r} value={r}>{r}</option>
                  ))}
                </select>
              </div>

              {/* School Filter */}
              <div className="flex flex-col gap-1">
                <label className="text-xs font-medium text-slate-500">School</label>
                <select
                  value={schoolId}
                  onChange={(e) => setSchoolId(e.target.value)}
                  className="rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none bg-white min-w-[200px]"
                >
                  <option value="">All Schools</option>
                  {schoolsData?.filter((s: any) => !regionFilter || s.region === regionFilter).map((s: any) => (
                    <option key={s.id} value={s.id}>{s.name}</option>
                  ))}
                </select>
              </div>
              
              {/* Commodity Filter */}
              <div className="flex flex-col gap-1">
                <label className="text-xs font-medium text-slate-500">Commodity</label>
                <select
                  value={commodityId}
                  onChange={(e) => setCommodityId(e.target.value)}
                  className="rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none bg-white min-w-[150px]"
                >
                  <option value="">All Commodities</option>
                  {commoditiesData?.map((c: any) => (
                    <option key={c.id} value={c.id}>{c.name}</option>
                  ))}
                </select>
              </div>
              
              {/* Clear Filters */}
              <div className="flex flex-col gap-1">
                <label className="text-xs font-medium text-transparent">Clear</label>
                <button
                  onClick={() => {
                    setSelectedWeek('');
                    setDateFrom('');
                    setDateTo('');
                    setRegionFilter('');
                    setSchoolId('');
                    setCommodityId('');
                  }}
                  className="rounded-lg border border-slate-300 px-3 py-2 text-sm font-medium text-slate-600 hover:bg-slate-100"
                >
                  Clear All
                </button>
              </div>
            </div>
            
            {/* Active Filters Summary */}
            {(dateFrom || dateTo || regionFilter || schoolId || commodityId) && (
              <div className="flex flex-wrap items-center gap-2 text-xs">
                <span className="text-slate-500">Active filters:</span>
                {selectedWeek && (
                  <span className="px-2 py-1 bg-indigo-100 text-indigo-700 rounded-full">{selectedWeek}</span>
                )}
                {!selectedWeek && dateFrom && (
                  <span className="px-2 py-1 bg-indigo-100 text-indigo-700 rounded-full">From: {dateFrom}</span>
                )}
                {!selectedWeek && dateTo && (
                  <span className="px-2 py-1 bg-indigo-100 text-indigo-700 rounded-full">To: {dateTo}</span>
                )}
                {regionFilter && (
                  <span className="px-2 py-1 bg-emerald-100 text-emerald-700 rounded-full">{regionFilter}</span>
                )}
                {schoolId && (
                  <span className="px-2 py-1 bg-amber-100 text-amber-700 rounded-full">
                    {schoolsData?.find((s: any) => s.id == schoolId)?.name || 'School'}
                  </span>
                )}
                {commodityId && (
                  <span className="px-2 py-1 bg-cyan-100 text-cyan-700 rounded-full">
                    {commoditiesData?.find((c: any) => c.id == commodityId)?.name || 'Commodity'}
                  </span>
                )}
              </div>
            )}
          </div>
          
          {/* Printable Header - Visible only in Print */}
          <div className="hidden print:block mb-2">
             <h1 className="text-lg font-bold text-center">GCX FSHS Delivery Report</h1>
             <div className="flex justify-between text-[10px] border-b pb-1 mb-2">
                <span>Generated: {new Date().toLocaleDateString('en-GB')}</span>
                <span>{selectedWeek || (dateFrom && dateTo ? `${dateFrom} to ${dateTo}` : 'All Time')}</span>
             </div>
          </div>

          {/* Grouped by School Display - SCREEN ONLY */}
          <div className="space-y-6 print:hidden">
            {groupedSchools.length === 0 ? (
              <div className="text-center py-12 text-slate-500">
                <FileDown className="h-12 w-12 mx-auto mb-4 opacity-30" />
                <p className="text-lg font-medium">No delivery records found</p>
                <p className="text-sm mt-1">Try adjusting your filters or date range</p>
              </div>
            ) : (
              groupedSchools.map((school, schoolIdx) => (
                <div key={school.school_id} className="border border-slate-200 rounded-xl overflow-hidden">
                  {/* School Header */}
                  <div className="bg-slate-100 px-4 py-3">
                    <div className="flex items-center justify-between">
                      <div>
                        <h3 className="font-bold text-slate-900 text-base">
                          {schoolIdx + 1}. {school.school_name}
                        </h3>
                        {school.school_region && (
                          <p className="text-xs text-slate-500 mt-0.5">{school.school_region} Region</p>
                        )}
                      </div>
                      <div className="text-right">
                        <div className="text-xs text-slate-500">School Totals</div>
                        <div className="flex items-center gap-4 text-sm">
                          <span><strong>{school.totals.delivery_count}</strong> deliveries</span>
                          <span className="text-emerald-600"><strong>{smartRound(school.totals.total_received)}</strong> received</span>
                          <span className={school.totals.difference > 0 ? 'text-red-600' : 'text-emerald-600'}>
                            <strong>{school.totals.difference > 0 ? '-' : '+'}{smartRound(Math.abs(school.totals.difference))}</strong> variance
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  {/* Commodities Table */}
                  <table className="w-full text-sm">
                    <thead className="bg-slate-50 text-slate-500 text-xs">
                      <tr>
                        <th className="px-4 py-2 text-left">Commodity</th>
                        <th className="px-4 py-2 text-left">Field Staff</th>
                        <th className="px-4 py-2 text-left">Supplier</th>
                        <th className="px-4 py-2 text-right">Expected</th>
                        <th className="px-4 py-2 text-right">Received</th>
                        <th className="px-4 py-2 text-right">Diff</th>
                        <th className="px-4 py-2 text-center">Count</th>
                        <th className="px-4 py-2 text-left">Delivery Dates</th>
                      </tr>
                    </thead>
                    <tbody>
                      {school.commodities.map((row: any, idx: number) => (
                        <tr key={`${row.commodity_id}-${idx}`} className="border-t border-slate-100 hover:bg-slate-50">
                          <td className="px-4 py-2 font-medium text-slate-900">{row.commodity_name}</td>
                          <td className="px-4 py-2 text-slate-600">{row.field_staff_name || '—'}</td>
                          <td className="px-4 py-2 text-slate-600">{row.supplier_name || '—'}</td>
                          <td className="px-4 py-2 text-right">{smartRound(row.total_expected)}</td>
                          <td className="px-4 py-2 text-right">{smartRound(row.total_received)}</td>
                          <td className={`px-4 py-2 text-right font-medium ${row.difference > 0 ? 'text-red-600' : row.difference < 0 ? 'text-emerald-600' : 'text-slate-600'}`}>
                            {row.difference > 0 ? '-' : row.difference < 0 ? '+' : ''}{smartRound(Math.abs(row.difference))}
                          </td>
                          <td className="px-4 py-2 text-center">
                            <span className="inline-flex items-center justify-center min-w-[24px] rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-700">
                              {row.delivery_count}
                            </span>
                          </td>
                          <td className="px-4 py-2 text-slate-500 text-xs max-w-[200px]">
                            <span className="line-clamp-2" title={row.delivery_dates}>
                              {row.delivery_dates || '—'}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ))
            )}
          </div>
          
          {/* SIMPLE FLAT TABLE - PRINT ONLY */}
          <table className="hidden print:table w-full border-collapse" style={{ fontSize: '11px', tableLayout: 'fixed' }}>
            <colgroup>
              <col style={{ width: '22%' }} />  {/* School */}
              <col style={{ width: '14%' }} />  {/* Commodity */}
              <col style={{ width: '9%' }} />   {/* Expected */}
              <col style={{ width: '9%' }} />   {/* Received */}
              <col style={{ width: '8%' }} />   {/* Diff */}
              <col style={{ width: '5%' }} />   {/* # Del */}
              <col style={{ width: '15%' }} />  {/* Field Staff */}
              <col style={{ width: '18%' }} />  {/* Dates */}
            </colgroup>
            <thead>
              <tr style={{ backgroundColor: '#1e293b', color: '#fff' }}>
                <th style={{ border: '1px solid #334155', padding: '6px 8px', textAlign: 'left', fontWeight: 600 }}>School</th>
                <th style={{ border: '1px solid #334155', padding: '6px 8px', textAlign: 'left', fontWeight: 600 }}>Commodity</th>
                <th style={{ border: '1px solid #334155', padding: '6px 8px', textAlign: 'right', fontWeight: 600 }}>Expected</th>
                <th style={{ border: '1px solid #334155', padding: '6px 8px', textAlign: 'right', fontWeight: 600 }}>Received</th>
                <th style={{ border: '1px solid #334155', padding: '6px 8px', textAlign: 'right', fontWeight: 600 }}>Diff</th>
                <th style={{ border: '1px solid #334155', padding: '6px 8px', textAlign: 'center', fontWeight: 600 }}>#</th>
                <th style={{ border: '1px solid #334155', padding: '6px 8px', textAlign: 'left', fontWeight: 600 }}>Field Staff</th>
                <th style={{ border: '1px solid #334155', padding: '6px 8px', textAlign: 'left', fontWeight: 600 }}>Dates</th>
              </tr>
            </thead>
            <tbody>
              {detailedData?.data
                ?.slice()
                .sort((a: any, b: any) => (a.school_name || '').localeCompare(b.school_name || ''))
                .map((row: any, idx: number) => {
                  const diff = (row.total_expected || 0) - (row.total_received || 0);
                  return (
                <tr key={idx} style={{ backgroundColor: idx % 2 === 0 ? '#fff' : '#f1f5f9' }}>
                  <td style={{ border: '1px solid #cbd5e1', padding: '5px 8px', fontWeight: 600 }}>{row.school_name}</td>
                  <td style={{ border: '1px solid #cbd5e1', padding: '5px 8px' }}>{row.commodity_name}</td>
                  <td style={{ border: '1px solid #cbd5e1', padding: '5px 8px', textAlign: 'right' }}>{smartRound(row.total_expected)}</td>
                  <td style={{ border: '1px solid #cbd5e1', padding: '5px 8px', textAlign: 'right' }}>{smartRound(row.total_received)}</td>
                  <td style={{ border: '1px solid #cbd5e1', padding: '5px 8px', textAlign: 'right', fontWeight: 600, color: diff > 0 ? '#dc2626' : diff < 0 ? '#059669' : '#475569' }}>
                    {diff > 0 ? '-' : diff < 0 ? '+' : ''}{smartRound(Math.abs(diff))}
                  </td>
                  <td style={{ border: '1px solid #cbd5e1', padding: '5px 8px', textAlign: 'center', fontWeight: 600 }}>{row.delivery_count}</td>
                  <td style={{ border: '1px solid #cbd5e1', padding: '5px 8px' }}>{row.field_staff_name || '—'}</td>
                  <td style={{ border: '1px solid #cbd5e1', padding: '5px 8px', fontSize: '10px' }}>{row.delivery_dates || '—'}</td>
                </tr>
                  );
              })}
            </tbody>
          </table>
          
          {/* Grand Totals - Screen Only */}
          {groupedSchools.length > 0 && detailedData?.totals && (
            <div className="mt-6 p-4 bg-slate-800 text-white rounded-xl print:hidden">
              <div className="grid grid-cols-5 gap-4 text-center">
                <div>
                  <div className="text-2xl font-bold">{groupedSchools.length}</div>
                  <div className="text-xs text-slate-300">Schools</div>
                </div>
                <div>
                  <div className="text-2xl font-bold">{detailedData.totals.total_deliveries || 0}</div>
                  <div className="text-xs text-slate-300">Total Deliveries</div>
                </div>
                <div>
                  <div className="text-2xl font-bold">{smartRound(detailedData.totals.total_expected || 0)}</div>
                  <div className="text-xs text-slate-300">Total Expected</div>
                </div>
                <div>
                  <div className="text-2xl font-bold">{smartRound(detailedData.totals.total_received || 0)}</div>
                  <div className="text-xs text-slate-300">Total Received</div>
                </div>
                <div>
                  <div className={`text-2xl font-bold ${(detailedData.totals.total_difference || 0) > 0 ? 'text-red-400' : 'text-emerald-400'}`}>
                    {(detailedData.totals.total_difference || 0) > 0 ? '-' : '+'}{smartRound(Math.abs(detailedData.totals.total_difference || 0))}
                  </div>
                  <div className="text-xs text-slate-300">Total Variance</div>
                </div>
              </div>
            </div>
          )}
          
          {/* Print Footer - Compact */}
          <div className="hidden print:block mt-2 text-[8px] text-slate-400 text-center">
            GCX FSHS | {new Date().toLocaleDateString('en-GB')}
          </div>
        </div>
      </div>
      <style jsx global>{`
        @media print {
          @page {
            size: A4 landscape;
            margin: 5mm;
          }
          body, html {
            margin: 0 !important;
            padding: 0 !important;
          }
          body * {
            visibility: hidden;
          }
          .printable-report, .printable-report * {
            visibility: visible;
          }
          .printable-report {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            padding: 0;
            margin: 0;
          }
          .print\\:hidden {
            display: none !important;
          }
          .print\\:block {
            display: block !important;
          }
          .print\\:table {
            display: table !important;
          }
        }
      `}</style>

    </LayoutShell>
  );
}
