
'use client';

import { useState, useMemo } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult, Parcel, ParcelStatus } from '@/lib/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { DateRange } from 'react-day-picker';
import { addDays, format } from 'date-fns';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DatePickerWithRange } from '@/components/ui/date-range-picker';
import { ParcelsTable } from '@/components/dashboard/parcels-table';
import { mockParcels, mockUser } from '@/lib/data';
import { Download } from 'lucide-react';
import jsPDF from 'jspdf';
import 'jspdf-autotable';

type ReportStatus = 'all' | ParcelStatus;

declare module 'jspdf' {
    interface jsPDF {
      autoTable: (options: any) => jsPDF;
    }
}


export default function ReportsPage() {
  
  const handleBookingComplete = (result: BookingResult) => {};

  const [status, setStatus] = useState<ReportStatus>('all');
  const [date, setDate] = useState<DateRange | undefined>({
    from: addDays(new Date(), -30),
    to: new Date(),
  });

  const filteredParcels = useMemo(() => {
    const sellerParcels = mockParcels.filter(p => p.sellerId === mockUser.id);
    
    return sellerParcels.filter(parcel => {
      const parcelDate = new Date(parcel.bookingDate);
      const isWithinDate = date?.from && date?.to && parcelDate >= date.from && parcelDate <= date.to;
      const matchesStatus = status === 'all' || parcel.status === status;
      return isWithinDate && matchesStatus;
    });
  }, [status, date]);

  const generatePDF = () => {
    const doc = new jsPDF();
    
    const title = "Order Report";
    const dateRange = date?.from && date?.to ? `${format(date.from, "LLL dd, y")} - ${format(date.to, "LLL dd, y")}` : "All time";
    const statusText = status === 'all' ? 'All Statuses' : status;

    doc.setFontSize(18);
    doc.text('Al-wasi Soft Tech', 14, 22);
    doc.setFontSize(12);
    doc.text(title, 14, 30);
    doc.setFontSize(10);
    doc.text(`Date Range: ${dateRange}`, 14, 36);
    doc.text(`Status: ${statusText}`, 14, 42);

    doc.autoTable({
        startY: 50,
        head: [['Order ID', 'Customer', 'City', 'Amount', 'Status', 'Date']],
        body: filteredParcels.map(p => [
            p.id,
            p.recipientName,
            p.city,
            `PKR ${p.codAmount.toFixed(2)}`,
            p.status,
            format(new Date(p.bookingDate), 'dd MMM yyyy')
        ]),
        theme: 'striped',
        headStyles: { fillColor: [34, 119, 215] },
    });

    doc.save(`report_${status}_${format(new Date(), 'yyyy-MM-dd')}.pdf`);
  };


  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="seller">
        <div className="flex flex-col gap-8">
          
          <Card>
            <CardHeader>
              <CardTitle>Filter & Download</CardTitle>
              <CardDescription>
                Select your criteria to generate and download a report.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
               <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label className="text-sm font-medium">Status</label>
                         <Select value={status} onValueChange={(value) => setStatus(value as ReportStatus)}>
                            <SelectTrigger>
                                <SelectValue placeholder="Select status" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">All</SelectItem>
                                <SelectItem value="Pending">Pending</SelectItem>
                                <SelectItem value="Picked Up">Picked Up</SelectItem>
                                <SelectItem value="In Transit">In Transit</SelectItem>
                                <SelectItem value="Delivered">Delivered</SelectItem>
                                <SelectItem value="Returned">Returned</SelectItem>
                                <SelectItem value="Failed">Failed</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>
                     <div>
                        <label className="text-sm font-medium">Date Range</label>
                        <DatePickerWithRange date={date} setDate={setDate} />
                     </div>
                     <div className="flex items-end">
                        <Button className="w-full" onClick={generatePDF} disabled={filteredParcels.length === 0}>
                            <Download className="mr-2 h-4 w-4" />
                            Download PDF
                        </Button>
                     </div>
               </div>
               
               <div>
                  <h3 className="text-lg font-semibold mb-2">Report Preview</h3>
                  <ParcelsTable parcels={filteredParcels} showViewAll={false} showCardWrapper={false} />
               </div>

            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
