
'use client';

import { useState } 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, 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 { Badge } from '@/components/ui/badge';
import { DatePicker } from '@/components/ui/date-picker';
import { Search, Printer, MoreVertical } from 'lucide-react';
import { mockUser } from '@/lib/data';
import { format } from 'date-fns';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';

type SearchType = 'order' | 'tracking';

const allStatuses: ParcelStatus[] = [
    'Pending', 'Picked Up', 'In Transit', 'Delivered', 'Returned', 'Failed', 'Unbooked',
    'In Warehouse', 'Out for Delivery', 'Attempted', 'Out for Return', 'Shipper Advice',
    'Branch Shift', 'Cancelled', 'Lost', 'Stolen', 'Damaged'
];


export default function AirwayBillsPage() {
    const [parcels] = useState<Parcel[]>([]);
    const [searchType, setSearchType] = useState<SearchType>('order');
    const [selectedParcels, setSelectedParcels] = useState<string[]>([]);

    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));
        }
    };

    const getStatusVariant = (status: Parcel['status']) => {
        switch (status) {
            case 'Delivered': return 'bg-green-100 text-green-800';
            case 'Returned':
            case 'Failed':
                return 'bg-red-100 text-red-800';
            case 'In Transit':
                return 'bg-blue-100 text-blue-800';
            case 'Unbooked':
                return 'bg-gray-200 text-gray-800';
            default:
                return 'bg-yellow-100 text-yellow-800';
        }
    };

    const getJourneyVariant = (parcel: Parcel) => {
      if (parcel.returnAddress) return 'destructive';
      return 'default';
    }


  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 ({parcels.length})</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">InTransit (0)</Button>
                        </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>
                                        </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">STATUS</label>
                               <Select>
                                    <SelectTrigger><SelectValue placeholder="Status"/></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">All</SelectItem>
                                        {allStatuses.map(status => (
                                            <SelectItem key={status} value={status}>{status}</SelectItem>
                                        ))}
                                    </SelectContent>
                               </Select>
                            </div>
                             <div>
                                <label className="text-xs text-muted-foreground">ORDER DATE TYPE</label>
                                <Select defaultValue="transaction-date">
                                    <SelectTrigger>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="transaction-date">Transaction Date</SelectItem>
                                        <SelectItem value="delivery-date">Delivery Date</SelectItem>
                                        <SelectItem value="pickup-date">PickUp Date</SelectItem>
                                        <SelectItem value="stock-in-picked-at">Stock In Picked At</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 col-start-1">
                                <Button className="w-full md:w-auto"><Search className="mr-2 h-4 w-4"/> Search</Button>
                                <Button variant="secondary" className="w-full md:w-auto">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>CUSTOMER</TableHead>
                                    <TableHead>DELIVERY ADDRESS</TableHead>
                                    <TableHead>RETURN ADDRESS</TableHead>
                                    <TableHead>ORDER TYPE</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={12} className="h-24 text-center">No airway bills to display.</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.items}</TableCell>
                                        <TableCell>
                                            <div className="font-medium text-primary">{parcel.orderReferenceNumber}</div>
                                            <div className="text-xs text-muted-foreground">{format(new Date(parcel.bookingDate), 'yyyy-MM-dd')}</div>
                                        </TableCell>
                                        <TableCell>
                                            <div className="font-medium">{parcel.recipientName}</div>
                                            <div className="text-xs text-muted-foreground">{parcel.contact}</div>
                                        </TableCell>
                                        <TableCell>
                                            <div className="w-40 truncate">{parcel.address}</div>
                                            <Badge variant="secondary">{parcel.city}</Badge>
                                        </TableCell>
                                        <TableCell>
                                            <div className="w-40 truncate">{parcel.returnAddress ?? 'N/A'}</div>
                                             <Badge variant="secondary">{parcel.returnCity ?? 'N/A'}</Badge>
                                        </TableCell>
                                        <TableCell>{parcel.orderType}</TableCell>
                                        <TableCell>{parcel.orderDetail}</TableCell>
                                        <TableCell className="text-right">PKR {parcel.codAmount.toFixed(2)}</TableCell>
                                        <TableCell>
                                            <Badge variant={getJourneyVariant(parcel)} className="capitalize">
                                                {parcel.returnAddress ? 'Return' : 'Forward'}
                                            </Badge>
                                        </TableCell>
                                        <TableCell>
                                            <Badge variant="outline" className={`${getStatusVariant(parcel.status)} capitalize`}>{parcel.status}</Badge>
                                            <div className="text-xs text-muted-foreground mt-1">Re-route to {parcel.city} warehouse</div>
                                        </TableCell>
                                        <TableCell>
                                            <DropdownMenu>
                                                <DropdownMenuTrigger asChild>
                                                    <Button variant="ghost" size="icon" className="h-8 w-8" disabled={parcel.isScanned}>
                                                        <MoreVertical className="h-4 w-4" />
                                                    </Button>
                                                </DropdownMenuTrigger>
                                                <DropdownMenuContent align="end">
                                                    <DropdownMenuItem>Print Airway Bill</DropdownMenuItem>
                                                </DropdownMenuContent>
                                            </DropdownMenu>
                                        </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 disabled={selectedParcels.length === 0}><Printer className="mr-2 h-4 w-4" /> Print Airway Bill</Button>
                         <p className="text-sm text-muted-foreground">Showing 1 to {parcels.length} of {parcels.length} entries</p>
                    </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>
  );
}
