
'use client';

import { useState, useRef, useEffect } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult, Parcel, ParcelFormValues } from '@/lib/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Upload, FileText, Download, X, Printer, Pencil, AlertCircle } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { EditOrderDialog } from '@/components/bulk-upload/edit-order-dialog';
import { useToast } from '@/hooks/use-toast';

type UploadedOrder = Partial<ParcelFormValues> & { 
  id: string;
  errors?: Record<string, string>;
  isValid: boolean;
};

const exampleOrders: UploadedOrder[] = [
    { id: '1', orderReferenceNumber: 'REF001', customerName: 'John Doe', customerContact: '03001234567', deliveryAddress: '123 Main St, Anytown', orderAmount: 1500, bookingWeight: 0.5, items: 1, deliveryCity: 'Anytown', isValid: true },
    { id: '2', orderReferenceNumber: 'REF002', customerName: 'Jane Smith', customerContact: '03129876543', deliveryAddress: '456 Oak Ave, Otherville', orderAmount: 2500, bookingWeight: 1.2, items: 2, deliveryCity: 'Otherville', isValid: true },
    { id: '3', orderReferenceNumber: 'REF003', customerName: '', customerContact: '12345', deliveryAddress: '789 Pine', orderAmount: -500, bookingWeight: 0, items: 0, deliveryCity: 'Anytown', isValid: false, errors: { customerName: 'Name is required', customerContact: 'Invalid contact', deliveryAddress: 'Address too short', orderAmount: 'Invalid amount', bookingWeight: 'Invalid weight', items: 'Invalid items' } },
    { id: '4', orderReferenceNumber: 'REF004', customerName: 'Peter Jones', customerContact: '03335554433', deliveryAddress: '321 Elm Rd, Anytown', orderAmount: 500, bookingWeight: 0.3, items: 1, deliveryCity: 'Anytown', isValid: true },
    { id: '5', orderReferenceNumber: '', customerName: 'Missing Ref', customerContact: '03451122333', deliveryAddress: '654 Maple Dr, Otherville', orderAmount: 3000, bookingWeight: 2, items: 3, deliveryCity: 'Otherville', isValid: false, errors: { orderReferenceNumber: 'Reference is required' } },
];

export default function BulkUploadPage() {
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [uploadedOrders, setUploadedOrders] = useState<UploadedOrder[]>([]);
  const [selectedOrders, setSelectedOrders] = useState<string[]>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { toast } = useToast();

  useEffect(() => {
    // Show dummy data on initial load
    setUploadedFile(new File([""], "sample-orders.csv"));
    setUploadedOrders(exampleOrders);
  }, []);

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      setUploadedFile(file);
      // Simulate file parsing
      setUploadedOrders(exampleOrders);
      setSelectedOrders([]);
    }
  };

  const handleUpload = () => {
    if (!uploadedFile) return;
    toast({
        title: 'Upload Successful',
        description: `${uploadedOrders.filter(o => o.isValid).length} valid orders have been added to the queue.`,
    });
  };

  const handleClear = () => {
    setUploadedFile(null);
    setUploadedOrders([]);
    setSelectedOrders([]);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedOrders(uploadedOrders.filter(o => o.isValid).map(o => o.id));
    } else {
      setSelectedOrders([]);
    }
  };

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

  const handleOrderUpdate = (updatedOrder: UploadedOrder) => {
    setUploadedOrders(prev => 
        prev.map(o => o.id === updatedOrder.id ? { ...updatedOrder, isValid: true, errors: undefined } : o)
    );
    toast({
        title: 'Order Updated',
        description: `Order ${updatedOrder.orderReferenceNumber} has been corrected and is now valid.`,
    });
  };

  const allValidSelected = uploadedOrders.length > 0 && selectedOrders.length === uploadedOrders.filter(o => o.isValid).length && selectedOrders.length > 0;

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={() => {}} userRole="seller">
        <div className="flex flex-col gap-8">
          
          <Card>
            <CardHeader>
              <CardTitle>Upload Bulk Orders</CardTitle>
              <CardDescription>
                Use a CSV file to upload multiple orders at once. Orders are aligned by reference number.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                <div className="border border-dashed rounded-lg p-6 flex flex-col items-center text-center">
                    <input type="file" ref={fileInputRef} onChange={handleFileSelect} accept=".csv" className="hidden" />
                    {uploadedFile ? (
                         <div className="flex flex-col items-center gap-2">
                            <FileText className="h-12 w-12 text-green-500" />
                            <p className="font-semibold">{uploadedFile.name}</p>
                            <p className="text-sm text-muted-foreground">{(uploadedFile.size / 1024).toFixed(2)} KB</p>
                            <Button variant="destructive" size="sm" onClick={handleClear}><X className="mr-2 h-4 w-4"/>Clear</Button>
                        </div>
                    ) : (
                        <div className="flex flex-col items-center gap-2">
                             <Upload className="h-12 w-12 text-muted-foreground" />
                             <p className="text-muted-foreground">Drag & drop your CSV file here or</p>
                             <Button onClick={() => fileInputRef.current?.click()}>Select File</Button>
                        </div>
                    )}
                </div>
                 <div className="flex flex-wrap gap-4 items-center justify-between">
                    <div className="flex gap-2">
                        <Button onClick={handleUpload} disabled={!uploadedFile}>
                            <Upload className="mr-2 h-4 w-4" /> Upload
                        </Button>
                        <Button variant="outline">
                            <Download className="mr-2 h-4 w-4" /> Download sample file
                        </Button>
                    </div>
                </div>

                {uploadedOrders.length > 0 && (
                    <div className="overflow-x-auto">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead><Checkbox onCheckedChange={(c) => handleSelectAll(c as boolean)} checked={allValidSelected} /></TableHead>
                                    <TableHead>ORDER REF #</TableHead>
                                    <TableHead>CUSTOMER</TableHead>
                                    <TableHead>CONTACT</TableHead>
                                    <TableHead>ADDRESS</TableHead>
                                    <TableHead>CITY</TableHead>
                                    <TableHead className="text-right">AMOUNT</TableHead>
                                    <TableHead className="text-right">WEIGHT (kg)</TableHead>
                                    <TableHead className="text-right">ITEMS</TableHead>
                                    <TableHead>STATUS</TableHead>
                                    <TableHead>ACTION</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {uploadedOrders.map(order => (
                                    <TableRow key={order.id} className={!order.isValid ? 'bg-red-50 dark:bg-red-900/20' : ''}>
                                        <TableCell>
                                            <Checkbox 
                                                disabled={!order.isValid} 
                                                checked={selectedOrders.includes(order.id)}
                                                onCheckedChange={(c) => handleSelectRow(order.id, c as boolean)}
                                            />
                                        </TableCell>
                                        <TableCell>{order.orderReferenceNumber}</TableCell>
                                        <TableCell>{order.customerName}</TableCell>
                                        <TableCell>{order.customerContact}</TableCell>
                                        <TableCell className="w-40 truncate">{order.deliveryAddress}</TableCell>
                                        <TableCell>{order.deliveryCity}</TableCell>
                                        <TableCell className="text-right">{order.orderAmount}</TableCell>
                                        <TableCell className="text-right">{order.bookingWeight}</TableCell>
                                        <TableCell className="text-right">{order.items}</TableCell>
                                        <TableCell>
                                            {order.isValid ? (
                                                <Badge variant="outline" className="bg-green-100 text-green-800">Valid</Badge>
                                            ) : (
                                                <TooltipProvider>
                                                    <Tooltip>
                                                        <TooltipTrigger asChild>
                                                            <Badge variant="destructive" className="cursor-help">
                                                                <AlertCircle className="mr-1 h-3 w-3"/>
                                                                Invalid
                                                            </Badge>
                                                        </TooltipTrigger>
                                                        <TooltipContent>
                                                            <div className="flex flex-col gap-1 text-xs">
                                                                {Object.entries(order.errors || {}).map(([key, value]) => (
                                                                    <p key={key}><strong>{key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase())}:</strong> {value}</p>
                                                                ))}
                                                            </div>
                                                        </TooltipContent>
                                                    </Tooltip>
                                                </TooltipProvider>
                                            )}
                                        </TableCell>
                                        <TableCell>
                                            {!order.isValid && (
                                                <EditOrderDialog order={order} onUpdate={handleOrderUpdate}>
                                                    <Button variant="ghost" size="icon" className="h-8 w-8">
                                                        <Pencil className="h-4 w-4" />
                                                    </Button>
                                                </EditOrderDialog>
                                            )}
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </div>
                )}
            </CardContent>
            <CardFooter className="flex items-center gap-4">
                 <Button disabled={selectedOrders.length === 0}>
                    <Printer className="mr-2 h-4 w-4" /> Print Airway Bill ({selectedOrders.length})
                </Button>
                 <Button 
                    variant="outline" 
                    onClick={() => setSelectedOrders([])} 
                    disabled={selectedOrders.length === 0}
                >
                    Clear Selection
                </Button>
            </CardFooter>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
