
'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, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { ScanLine, Search, Archive, X, Trash2 } from 'lucide-react';
import { mockParcels } from '@/lib/data';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/hooks/use-toast';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';

export default function AdminBranchBaggingPage() {
  
  const handleBookingComplete = (result: BookingResult) => {};
  const [parcelId, setParcelId] = useState('');
  const [parcelsInBag, setParcelsInBag] = useState<Parcel[]>([]);
  const [bagId, setBagId] = useState<string | null>(null);
  const { toast } = useToast();

  const handleScan = () => {
    if (!parcelId) return;
    const parcel = mockParcels.find(p => p.id.toLowerCase() === parcelId.toLowerCase());
    
    if (parcel) {
        if (parcelsInBag.some(p => p.id === parcel.id)) {
            toast({
                variant: 'destructive',
                title: 'Duplicate Parcel',
                description: `Parcel ${parcel.id} is already in the bag.`,
            });
        } else {
            setParcelsInBag(prev => [parcel, ...prev]);
            toast({
                title: 'Parcel Added',
                description: `Parcel ${parcel.id} added to the bag.`,
            });
        }
    } else {
        toast({
            variant: 'destructive',
            title: 'Scan Failed',
            description: 'No parcel found with this ID.',
        });
    }
    setParcelId('');
  };

  const handleRemoveParcel = (id: string) => {
    setParcelsInBag(prev => prev.filter(p => p.id !== id));
  };
  
  const handleCreateBag = () => {
    if (parcelsInBag.length === 0) {
        toast({ variant: 'destructive', title: 'Empty Bag', description: 'Scan at least one parcel to create a bag.'});
        return;
    }
    const newBagId = `BAG-${Date.now().toString().slice(-6)}`;
    const newSealId = `SEAL-${Date.now().toString().slice(-4)}`;
    setBagId(`${newBagId} (Seal: ${newSealId})`);
     toast({
        title: 'Bag Created!',
        description: `Bag ID: ${newBagId} created with ${parcelsInBag.length} parcels.`,
    });
  }
  
  const handleClear = () => {
    setParcelsInBag([]);
    setBagId(null);
    setParcelId('');
  }

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="branch-operator">
        <div className="flex flex-col gap-8">
          <Card>
            <CardHeader>
              <CardTitle>Create Dispatch Bag</CardTitle>
              <CardDescription>
                Scan parcels to group them into a bag for dispatch. The system will auto-generate a Bag ID and Seal Number.
              </CardDescription>
            </CardHeader>
            <CardContent>
                <div className="flex items-center gap-2 max-w-lg mx-auto">
                    <div className="relative flex-1">
                        <ScanLine className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
                        <Input 
                            placeholder="Scan or enter parcel ID..." 
                            className="pl-10 h-12 text-lg" 
                            value={parcelId}
                            onChange={(e) => setParcelId(e.target.value)}
                            onKeyDown={(e) => e.key === 'Enter' && handleScan()}
                        />
                    </div>
                    <Button size="lg" className="h-12" onClick={handleScan}>
                        <Search className="mr-2 h-5 w-5" /> Add to Bag
                    </Button>
                </div>
            </CardContent>
          </Card>

          {parcelsInBag.length > 0 && (
            <Card className="animate-in fade-in-50">
                <CardHeader>
                    <div className="flex justify-between items-start">
                        <div>
                             <CardTitle>Parcels in Current Bag</CardTitle>
                             <CardDescription>Total parcels scanned: {parcelsInBag.length}</CardDescription>
                        </div>
                        {bagId && <Badge className="text-lg" variant="secondary">{bagId}</Badge>}
                    </div>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Parcel ID</TableHead>
                                <TableHead>Recipient</TableHead>
                                <TableHead>Destination City</TableHead>
                                <TableHead className="text-right">Action</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {parcelsInBag.map(p => (
                                <TableRow key={p.id}>
                                    <TableCell>{p.id}</TableCell>
                                    <TableCell>{p.recipientName}</TableCell>
                                    <TableCell>{p.city}</TableCell>
                                    <TableCell className="text-right">
                                        <Button variant="ghost" size="icon" className="text-red-500 hover:text-red-600" onClick={() => handleRemoveParcel(p.id)}>
                                            <Trash2 className="h-4 w-4"/>
                                        </Button>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </CardContent>
                <CardFooter className="justify-between">
                    <Button variant="destructive" onClick={handleClear}>
                        <X className="mr-2 h-4 w-4" />
                        Clear All
                    </Button>
                    <Button onClick={handleCreateBag}>
                        <Archive className="mr-2 h-4 w-4" />
                        Create & Seal Bag
                    </Button>
                </CardFooter>
            </Card>
          )}
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
