
'use client';

import { useState } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult, Parcel } from '@/lib/types';
import { Card, CardContent, CardHeader, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { DatePicker } from '@/components/ui/date-picker';
import { Search, RefreshCw, Printer, Download, Settings, PlusCircle, UploadCloud } from 'lucide-react';
import { format } from 'date-fns';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuLabel } from '@/components/ui/dropdown-menu';

type SearchType = 'order' | 'tracking';

export default function GenerateLoadSheetPage() {
    const [parcels, setParcels] = useState<Parcel[]>([]);
    const [searchType, setSearchType] = useState<SearchType>('order');
    const [selectedParcels, setSelectedParcels] = useState<string[]>([]);
    const [bookingDateFrom, setBookingDateFrom] = useState<Date | undefined>(new Date());
    const [bookingDateTo, setBookingDateTo] = useState<Date | undefined>(new Date());
    const [showCount, setShowCount] = useState("25");
    const [sortOrder, setSortOrder] = useState("desc");

    const handleBookingComplete = (result: BookingResult) => {};

    const handleSelectAll = (checked: boolean) => {
        if (checked) {
            setSelectedParcels(parcels.map(p => p.id));
        } else {
            setSelectedParcels([]);
        }
    };

    const handleSelectRow = (parcelId: string, checked: boolean) => {
        if (checked) {
            setSelectedParcels(prev => [...prev, parcelId]);
        } else {
            setSelectedParcels(prev => prev.filter(id => id !== parcelId));
        }
    };

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="seller">
        <div className="flex flex-col gap-8">
            <div className="flex items-center justify-end">
                <Button disabled={selectedParcels.length === 0} variant="accent">
                    <PlusCircle className="mr-2 h-4 w-4" />
                    Generate LoadSheet ({selectedParcels.length})
                </Button>
            </div>
            <Card>
                <CardHeader className="p-4">
                    <div className="flex flex-wrap items-center justify-between gap-4">
                       <div className="flex items-center gap-4 flex-wrap">
                           <div className="flex-1 min-w-[200px]">
                               <label className="text-sm font-medium">Booking Date From</label>
                               <DatePicker date={bookingDateFrom} setDate={setBookingDateFrom} />
                           </div>
                           <div className="flex-1 min-w-[200px]">
                               <label className="text-sm font-medium">Booking Date To</label>
                               <DatePicker date={bookingDateTo} setDate={setBookingDateTo} />
                           </div>
                       </div>
                       <div className="flex items-end gap-2">
                           <Button variant="outline" size="icon"><RefreshCw className="h-4 w-4" /></Button>
                           <Button variant="outline" size="icon"><UploadCloud className="h-4 w-4" /></Button>
                           <Button variant="outline" size="icon"><Download className="h-4 w-4" /></Button>
                           <Button variant="outline" size="icon"><Printer className="h-4 w-4" /></Button>
                           <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <Button variant="outline" size="icon">
                                        <Settings className="h-4 w-4" />
                                    </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                    <DropdownMenuLabel>Show</DropdownMenuLabel>
                                    <DropdownMenuRadioGroup value={showCount} onValueChange={setShowCount}>
                                        <DropdownMenuRadioItem value="25">25</DropdownMenuRadioItem>
                                        <DropdownMenuRadioItem value="50">50</DropdownMenuRadioItem>
                                        <DropdownMenuRadioItem value="100">100</DropdownMenuRadioItem>
                                        <DropdownMenuRadioItem value="200">200</DropdownMenuRadioItem>
                                        <DropdownMenuRadioItem value="300">300</DropdownMenuRadioItem>
                                        <DropdownMenuRadioItem value="all">All</DropdownMenuRadioItem>
                                    </DropdownMenuRadioGroup>
                                    <DropdownMenuLabel className="mt-2">Sort By Order Date</DropdownMenuLabel>
                                    <DropdownMenuRadioGroup value={sortOrder} onValueChange={setSortOrder}>
                                        <DropdownMenuRadioItem value="asc">ASC</DropdownMenuRadioItem>
                                        <DropdownMenuRadioItem value="desc">DESC</DropdownMenuRadioItem>
                                    </DropdownMenuRadioGroup>
                                </DropdownMenuContent>
                            </DropdownMenu>
                       </div>
                    </div>
                </CardHeader>
                <CardContent className="space-y-6">
                    <div className="p-4 border rounded-lg bg-muted/50">
                        <p className="text-sm font-semibold mb-4">ADVANCED SEARCH</p>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            <div className="lg:col-span-1">
                                <label className="text-xs text-muted-foreground">Search by</label>
                                <div className="flex">
                                    <Input placeholder="Search..." className="rounded-r-none" />
                                    <Select value={searchType} onValueChange={(val) => setSearchType(val as SearchType)}>
                                        <SelectTrigger className="w-auto min-w-[150px] rounded-l-none border-l-0">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="order">ORDER REF</SelectItem>
                                            <SelectItem value="tracking">TRACKING #</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>
                             <div>
                                <label className="text-xs text-muted-foreground">CITY</label>
                                <Select>
                                  <SelectTrigger><SelectValue placeholder="Select City" /></SelectTrigger>
                                  <SelectContent>
                                      <SelectItem value="multan">Multan</SelectItem>
                                      <SelectItem value="lahore">Lahore</SelectItem>
                                      <SelectItem value="karachi">Karachi</SelectItem>
                                  </SelectContent>
                                </Select>
                            </div>
                            <div className="flex items-end gap-2">
                                <Button className="w-full"><Search className="mr-2 h-4 w-4"/> Search</Button>
                                <Button variant="secondary" className="w-full">Clear Filter</Button>
                            </div>
                        </div>
                    </div>

                    <div className="overflow-x-auto">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead><Checkbox onCheckedChange={(c) => handleSelectAll(c as boolean)} checked={parcels.length > 0 && selectedParcels.length === parcels.length} /></TableHead>
                                    <TableHead>ORDER REF</TableHead>
                                    <TableHead>TRACKING #</TableHead>
                                    <TableHead>TYPE</TableHead>
                                    <TableHead>STATUS</TableHead>
                                    <TableHead>CUSTOMER</TableHead>
                                    <TableHead>CITY</TableHead>
                                    <TableHead>PICKUP ADDRESS</TableHead>
                                    <TableHead>DETAIL</TableHead>
                                    <TableHead className="text-right">AMOUNT</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {parcels.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={10} className="h-24 text-center">No orders found for the selected date.</TableCell>
                                    </TableRow>
                                ) : parcels.map(parcel => (
                                    <TableRow key={parcel.id} data-state={selectedParcels.includes(parcel.id) && "selected"}>
                                        <TableCell><Checkbox checked={selectedParcels.includes(parcel.id)} onCheckedChange={(c) => handleSelectRow(parcel.id, c as boolean)} /></TableCell>
                                        <TableCell>
                                            <div className="font-medium">{parcel.orderReferenceNumber}</div>
                                            <div className="text-xs text-muted-foreground">{format(new Date(parcel.bookingDate), 'dd-MMM-yyyy')}</div>
                                        </TableCell>
                                        <TableCell>
                                            <Button variant="link" className="p-0 h-auto text-primary">{parcel.id}</Button>
                                        </TableCell>
                                        <TableCell>{parcel.orderType}</TableCell>
                                        <TableCell>{parcel.status}</TableCell>
                                        <TableCell>{parcel.recipientName}</TableCell>
                                        <TableCell>{parcel.city}</TableCell>
                                        <TableCell>{parcel.pickupAddress}</TableCell>
                                        <TableCell>{parcel.orderDetail}</TableCell>
                                        <TableCell className="text-right">PKR {parcel.codAmount.toFixed(2)}</TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </div>
                </CardContent>
                <CardFooter className="flex-col items-start gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <div className="text-sm text-muted-foreground">
                        Showing <strong>{parcels.length}</strong> of <strong>{parcels.length}</strong> entries
                    </div>
                    <div className="flex items-center gap-2">
                        <span>Page</span>
                        <Select defaultValue="1">
                            <SelectTrigger className="w-16"><SelectValue /></SelectTrigger>
                            <SelectContent>
                                <SelectItem value="1">1</SelectItem>
                            </SelectContent>
                        </Select>
                        <span className="text-sm">of 1</span>
                        <Button variant="outline" size="sm" disabled>Previous</Button>
                        <Button variant="outline" size="sm" disabled>Next</Button>
                    </div>
                </CardFooter>
            </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
