'use client';

import { useSearchParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import api from '../../../../../lib/api-client';
import { Loader2, Printer } from 'lucide-react';
import { Suspense } from 'react';

interface CommodityDelivery {
  commodity_name: string;
  total_quantity: number;
  delivery_count: number;
  dates: string;
  first_delivery: string;
  last_delivery: string;
}

interface SchoolReport {
  school_id: number;
  school_name: string;
  region: string;
  commodities: CommodityDelivery[];
}

interface LandscapeResponse {
  filters: any;
  schools: SchoolReport[];
}

function ReportContent() {
  const searchParams = useSearchParams();
  const planPeriodId = searchParams.get('plan_period_id');
  const dateFrom = searchParams.get('date_from');
  const dateTo = searchParams.get('date_to');

  const { data, isLoading, error } = useQuery({
    queryKey: ['delivery-landscape', planPeriodId, dateFrom, dateTo],
    queryFn: async () => {
      const response = await api.get<LandscapeResponse>('/reports/deliveries/landscape', {
        params: {
          plan_period_id: planPeriodId || undefined,
          date_from: dateFrom || undefined,
          date_to: dateTo || undefined,
        },
      });
      return response.data;
    },
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="w-8 h-8 animate-spin" />
      </div>
    );
  }

  if (error) {
    return <div className="p-8 text-red-500">Failed to load report.</div>;
  }

  return (
    <div className="min-h-screen bg-white text-black p-8 print:p-0">
      <div className="flex justify-between items-center mb-8 print:hidden">
        <h1 className="text-2xl font-bold">Delivery Landscape Report</h1>
        <button
          onClick={() => window.print()}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
        >
          <Printer className="w-4 h-4" />
          Print
        </button>
      </div>

      <div className="mb-4">
        <div className="text-sm text-gray-600">
           Period: {dateFrom || 'Start'} to {dateTo || 'End'}
        </div>
      </div>

      <div className="space-y-6">
        {data?.schools.map((school) => (
          <div key={school.school_id} className="border border-gray-300 rounded p-4 break-inside-avoid">
            <div className="bg-gray-100 p-2 mb-2 font-bold text-lg border-b border-gray-300 flex justify-between items-center">
                <span>{school.school_name}</span>
                <span className="text-sm font-normal text-gray-600 px-2 py-1 bg-white rounded border border-gray-200">{school.region}</span>
            </div>
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-gray-200">
                  <th className="text-left py-1 w-1/4">Commodity</th>
                  <th className="text-right py-1 w-24">Total Qty</th>
                  <th className="text-right py-1 w-24">Deliveries</th>
                  <th className="text-left py-1 pl-4">Delivery Dates</th>
                </tr>
              </thead>
              <tbody>
                {school.commodities.map((item, idx) => (
                  <tr key={idx} className="border-b border-gray-100 last:border-0 hover:bg-gray-50">
                    <td className="py-1 font-medium">{item.commodity_name}</td>
                    <td className="text-right py-1 font-mono font-bold text-blue-700">{item.total_quantity.toLocaleString()}</td>
                    <td className="text-right py-1">{item.delivery_count}</td>
                    <td className="py-1 pl-4 text-xs text-gray-500 break-words">
                      {item.dates}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ))}
        {data?.schools.length === 0 && (
            <div className="text-center text-gray-500 italic p-8 border border-dashed rounded">No delivery records found for this period.</div>
        )}
      </div>
      
      <style jsx global>{`
        @media print {
          @page {
            size: landscape;
            margin: 0.5cm;
          }
          body {
            print-color-adjust: exact;
            -webkit-print-color-adjust: exact;
          }
        }
      `}</style>
    </div>
  );
}

export default function LandscapeReportPage() {
  return (
    <Suspense fallback={<div className="p-8">Loading...</div>}>
      <ReportContent />
    </Suspense>
  )
}
