
'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, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DatePickerWithRange } from '@/components/ui/date-range-picker';
import { mockSellers, mockParcels } from '@/lib/data';
import { addDays } from 'date-fns';
import type { DateRange } from 'react-day-picker';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, TableFooter as ShadTableFooter } from '@/components/ui/table';
import { Loader2 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

type InvoicePreview = {
    merchantId: string;
    merchantName: string;
    dateRange: DateRange;
    parcels: Parcel[];
    totals: {
        cod: number;
        deliveryCharges: number;
        gst: number;
        net: number;
    }
};

export default function FinanceGenerateInvoicePage() {
  
  const handleBookingComplete = (result: BookingResult) => {};

  const [selectedMerchant, setSelectedMerchant] = useState<string>('');
  const [dateRange, setDateRange] = useState<DateRange | undefined>({
    from: addDays(new Date(), -30),
    to: new Date(),
  });
  const [isLoading, setIsLoading] = useState(false);
  const [invoicePreview, setInvoicePreview] = useState<InvoicePreview | null>(null);
  const { toast } = useToast();

  const handlePreview = () => {
    if (!selectedMerchant || !dateRange?.from || !dateRange?.to) {
        toast({ variant: 'destructive', title: 'Missing Information', description: 'Please select a merchant and a date range.' });
        return;
    }
    
    setIsLoading(true);
    setTimeout(() => {
        const merchantParcels = mockParcels.filter(p => 
            p.sellerId === selectedMerchant &&
            p.status === 'Delivered' &&
            new Date(p.bookingDate) >= dateRange.from! &&
            new Date(p.bookingDate) <= dateRange.to!
        );

        const totals = merchantParcels.reduce((acc, p) => {
            const deliveryCharges = 150; // Mock charge
            const gst = deliveryCharges * 0.16;
            acc.cod += p.codAmount;
            acc.deliveryCharges += deliveryCharges;
            acc.gst += gst;
            acc.net += p.codAmount + deliveryCharges + gst;
            return acc;
        }, { cod: 0, deliveryCharges: 0, gst: 0, net: 0 });

        setInvoicePreview({
            merchantId: selectedMerchant,
            merchantName: mockSellers.find(s => s.id === selectedMerchant)?.name || '',
            dateRange: dateRange,
            parcels: merchantParcels,
            totals,
        });

        setIsLoading(false);
    }, 1000);
  };

  const handleGenerate = () => {
    toast({
        title: 'Invoice Generated!',
        description: `Invoice for ${invoicePreview?.merchantName} has been generated and sent.`
    });
    setInvoicePreview(null);
    setSelectedMerchant('');
  }

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="finance">
        <div className="flex flex-col gap-8">
          <Card>
            <CardHeader>
              <CardTitle>Generate New Invoice</CardTitle>
              <CardDescription>
                Select a merchant and date range to create and generate a new invoice.
              </CardDescription>
            </CardHeader>
            <CardContent>
                {!invoicePreview ? (
                    <div className="max-w-xl mx-auto space-y-4">
                        <div>
                            <label className="text-sm font-medium">Select Merchant</label>
                            <Select value={selectedMerchant} onValueChange={setSelectedMerchant}>
                                <SelectTrigger>
                                    <SelectValue placeholder="Select a merchant..." />
                                </SelectTrigger>
                                <SelectContent>
                                    {mockSellers.map(seller => (
                                        <SelectItem key={seller.id} value={seller.id}>{seller.name}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                        <div>
                            <label className="text-sm font-medium">Select Date Range</label>
                            <DatePickerWithRange date={dateRange} setDate={setDateRange} />
                        </div>
                        <Button onClick={handlePreview} disabled={isLoading} className="w-full">
                            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            {isLoading ? 'Generating Preview...' : 'Preview Invoice'}
                        </Button>
                    </div>
                ) : (
                    <div className="animate-in fade-in-50">
                        <div className="flex justify-between items-start mb-4 border-b pb-4">
                            <div>
                                <h3 className="text-lg font-semibold">{invoicePreview.merchantName}</h3>
                                <p className="text-sm text-muted-foreground">
                                    Invoice for {dateRange?.from?.toLocaleDateString()} - {dateRange?.to?.toLocaleDateString()}
                                </p>
                            </div>
                            <Button variant="outline" onClick={() => setInvoicePreview(null)}>Change Criteria</Button>
                        </div>

                         <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Tracking #</TableHead>
                                    <TableHead>COD Amount</TableHead>
                                    <TableHead>Delivery Charges</TableHead>
                                    <TableHead>GST (16%)</TableHead>
                                    <TableHead className="text-right">Net Amount</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {invoicePreview.parcels.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={5} className="text-center h-24">No delivered shipments found for this period.</TableCell>
                                    </TableRow>
                                ) : invoicePreview.parcels.map(p => {
                                    const deliveryCharges = 150;
                                    const gst = deliveryCharges * 0.16;
                                    const net = p.codAmount + deliveryCharges + gst;
                                    return (
                                        <TableRow key={p.id}>
                                            <TableCell>{p.id}</TableCell>
                                            <TableCell>{p.codAmount.toFixed(2)}</TableCell>
                                            <TableCell>{deliveryCharges.toFixed(2)}</TableCell>
                                            <TableCell>{gst.toFixed(2)}</TableCell>
                                            <TableCell className="text-right">{net.toFixed(2)}</TableCell>
                                        </TableRow>
                                    )
                                })}
                            </TableBody>
                            <ShadTableFooter>
                                <TableRow>
                                    <TableCell colSpan={1} className="font-bold">Total</TableCell>
                                    <TableCell className="font-bold">{invoicePreview.totals.cod.toFixed(2)}</TableCell>
                                    <TableCell className="font-bold">{invoicePreview.totals.deliveryCharges.toFixed(2)}</TableCell>
                                    <TableCell className="font-bold">{invoicePreview.totals.gst.toFixed(2)}</TableCell>
                                    <TableCell className="text-right font-bold">{invoicePreview.totals.net.toFixed(2)}</TableCell>
                                </TableRow>
                            </ShadTableFooter>
                        </Table>
                    </div>
                )}
            </CardContent>
            {invoicePreview && (
                <CardFooter className="justify-end border-t pt-6">
                    <Button onClick={handleGenerate} disabled={invoicePreview.parcels.length === 0}>Generate & Send Invoice</Button>
                </CardFooter>
            )}
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
