
'use client';

import { useState, useMemo } 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, CardTitle, CardDescription, 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 { Badge } from '@/components/ui/badge';
import { DatePicker } from '@/components/ui/date-picker';
import { Search, RefreshCw, Printer, Download, Settings, Trash2, MoreVertical, UploadCloud } from 'lucide-react';
import { mockParcels, mockUser } from '@/lib/data';
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' | 'name' | 'phone';

export default function CancelOrderPage() {
    const [parcels, setParcels] = useState<Parcel[]>([]);
    const [searchType, setSearchType] = useState<SearchType>('order');
    const [selectedParcels, setSelectedParcels] = useState<string[]>([]);
    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">
            
            <Card>
                <CardHeader>
                    <div className="flex flex-wrap items-center justify-between gap-4">
                        <div className="flex items-center gap-2 border-b">
                            <Button variant="ghost" className="border-b-2 border-primary text-primary rounded-none">All (0)</Button>
                            <Button variant="ghost" className="text-muted-foreground rounded-none">Booked (0)</Button>
                            <Button variant="ghost" className="text-muted-foreground rounded-none">Unbooked (0)</Button>
                            <Button variant="ghost" className="text-muted-foreground rounded-none">Logs (0)</Button>
                        </div>
                        <div className="flex items-center 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-4 gap-4">
                            <div className="lg:col-span-2">
                                <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-[160px] rounded-l-none border-l-0">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="order">ORDER #</SelectItem>
                                            <SelectItem value="tracking">TRACKING #</SelectItem>
                                            <SelectItem value="name">NAME</SelectItem>
                                            <SelectItem value="phone">PHONE #</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>
                            <div>
                                <label className="text-xs text-muted-foreground">FROM</label>
                                <DatePicker />
                            </div>
                             <div>
                                <label className="text-xs text-muted-foreground">TO</label>
                                <DatePicker />
                            </div>
                             <div>
                                <label className="text-xs text-muted-foreground">ORDER DATE TYPE</label>
                                <Select defaultValue="transaction-date">
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select Order Date Type" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="transaction-date">Transaction Date</SelectItem>
                                        <SelectItem value="status-changed-at">Order Status Changed At</SelectItem>
                                        <SelectItem value="booked-at">Booked At</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)} /></TableHead>
                                    <TableHead>ORDER REF</TableHead>
                                    <TableHead>TRACKING #</TableHead>
                                    <TableHead>CUSTOMER</TableHead>
                                    <TableHead>DELIVERY ADDRESS</TableHead>
                                    <TableHead>RETURN ADDRESS</TableHead>
                                    <TableHead>DETAILS</TableHead>
                                    <TableHead className="text-right">AMOUNT</TableHead>
                                    <TableHead>JOURNEY</TableHead>
                                    <TableHead>STATUS</TableHead>
                                    <TableHead>ACTION</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {parcels.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={11} className="h-24 text-center">No orders available to cancel.</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>{parcel.orderType}</TableCell>
                                        <TableCell>
                                            <div className="font-medium text-primary">{parcel.orderReferenceNumber}</div>
                                            <div className="text-xs">{format(new Date(parcel.bookingDate), 'yyyy-MM-dd')}</div>
                                        </TableCell>
                                        <TableCell>
                                            <div className="font-medium">{parcel.recipientName}</div>
                                            <div className="text-xs">{parcel.contact}</div>
                                        </TableCell>
                                        <TableCell>
                                            <div>{parcel.address}</div>
                                            <Badge variant="secondary">{parcel.city}</Badge>
                                        </TableCell>
                                        <TableCell>
                                            <div>{parcel.returnAddress ?? 'N/A'}</div>
                                             <Badge variant="secondary">{parcel.returnCity ?? 'N/A'}</Badge>
                                        </TableCell>
                                        <TableCell>{parcel.orderDetail}</TableCell>
                                        <TableCell className="text-right">{parcel.codAmount.toFixed(2)}</TableCell>
                                        <TableCell><Badge variant="outline" className="bg-green-100 text-green-800">Forward</Badge></TableCell>
                                        <TableCell><Badge variant="secondary">{parcel.status}</Badge></TableCell>
                                        <TableCell>
                                            <Button variant="ghost" size="icon" className="text-red-500 hover:text-red-700">
                                                <Trash2 className="h-4 w-4" />
                                            </Button>
                                        </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="flex items-center gap-4">
                        <Button variant="destructive" disabled={selectedParcels.length === 0}>CANCEL ORDER</Button>
                         <p className="text-sm text-muted-foreground">Showing 0 of 0 entries</p>
                    </div>
                    <div className="flex items-center gap-2">
                        <Select defaultValue="0">
                            <SelectTrigger className="w-16"><SelectValue /></SelectTrigger>
                            <SelectContent>
                                <SelectItem value="0">0</SelectItem>
                            </SelectContent>
                        </Select>
                        <span className="text-sm">of 0</span>
                        <Button variant="outline" size="sm" disabled>Previous</Button>
                        <Button variant="outline" size="sm" disabled>Next</Button>
                    </div>
                </CardFooter>
            </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
