
'use client';

import { useState, useMemo } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult, Seller } from '@/lib/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { WalletCards, Hourglass, AlertTriangle, MoreVertical, Search, CheckCircle } from 'lucide-react';
import { mockSellers } from '@/lib/data';
import { addDays, format, differenceInDays } from 'date-fns';
import type { DateRange } from 'react-day-picker';
import { DatePickerWithRange } from '@/components/ui/date-range-picker';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';

type PendingSettlement = {
  id: string;
  invoiceNumber: string;
  merchant: Seller;
  invoiceDate: string;
  dueDate: string;
  amount: number;
};

const mockPendingSettlements: PendingSettlement[] = [
  { id: 'set-1', invoiceNumber: 'INV-2024-002', merchant: mockSellers[1], invoiceDate: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(), dueDate: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(), amount: 78950 },
  { id: 'set-2', invoiceNumber: 'INV-2024-004', merchant: mockSellers[0], invoiceDate: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString(), dueDate: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(), amount: 23400 },
  { id: 'set-3', invoiceNumber: 'INV-2024-005', merchant: mockSellers[1], invoiceDate: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString(), dueDate: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString(), amount: 55600 },
];

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

  const [dateRange, setDateRange] = useState<DateRange | undefined>({
    from: addDays(new Date(), -30),
    to: new Date(),
  });

  const filteredSettlements = useMemo(() => {
    return mockPendingSettlements.filter(s => {
        const dueDate = new Date(s.dueDate);
        return dateRange?.from && dateRange?.to && dueDate >= dateRange.from && dueDate <= dateRange.to;
    });
  }, [dateRange]);

  const summary = useMemo(() => {
    return filteredSettlements.reduce((acc, s) => {
        acc.totalPending += s.amount;
        if (new Date(s.dueDate) < new Date()) {
            acc.overdueCount++;
            acc.overdueAmount += s.amount;
        }
        return acc;
    }, { totalPending: 0, overdueCount: 0, overdueAmount: 0 });
  }, [filteredSettlements]);

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="finance">
        <div className="flex flex-col gap-8">
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Pending Amount</CardTitle>
                        <Hourglass className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">PKR {summary.totalPending.toLocaleString()}</div>
                    </CardContent>
                </Card>
                 <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Invoices Pending</CardTitle>
                        <WalletCards className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{filteredSettlements.length}</div>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Overdue Amount</CardTitle>
                        <AlertTriangle className="h-4 w-4 text-red-500" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold text-red-600">PKR {summary.overdueAmount.toLocaleString()}</div>
                        <p className="text-xs text-muted-foreground">{summary.overdueCount} overdue invoices</p>
                    </CardContent>
                </Card>
            </div>
          <Card>
            <CardHeader>
              <CardTitle>Pending Settlement Report</CardTitle>
              <CardDescription>
                A list of all merchant settlements that are currently awaiting payment.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-8">
               <div className="p-4 border rounded-lg bg-muted/50">
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 items-end">
                      <div>
                          <label className="text-sm font-medium">Due Date Range</label>
                          <DatePickerWithRange date={dateRange} setDate={setDateRange} />
                      </div>
                      <div>
                          <label className="text-sm font-medium">Merchant</label>
                          <Select><SelectTrigger><SelectValue placeholder="All Merchants" /></SelectTrigger></Select>
                      </div>
                      <Button className="lg:col-start-4"><Search className="mr-2 h-4 w-4" /> Search</Button>
                  </div>
              </div>
              
              <div>
                <h3 className="text-lg font-semibold mb-4">Pending Payouts</h3>
                 <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Merchant</TableHead>
                            <TableHead>Invoice #</TableHead>
                            <TableHead>Due Date</TableHead>
                            <TableHead>Aging</TableHead>
                            <TableHead className="text-right">Amount Due (PKR)</TableHead>
                            <TableHead className="text-right">Action</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {filteredSettlements.map(item => {
                            const daysOverdue = differenceInDays(new Date(), new Date(item.dueDate));
                            return (
                                <TableRow key={item.id}>
                                    <TableCell>{item.merchant.name}</TableCell>
                                    <TableCell>{item.invoiceNumber}</TableCell>
                                    <TableCell>{format(new Date(item.dueDate), 'dd MMM, yyyy')}</TableCell>
                                    <TableCell>
                                        {daysOverdue > 0 ? (
                                            <Badge variant="destructive">{daysOverdue} days overdue</Badge>
                                        ) : (
                                            <Badge variant="secondary">Due in {-daysOverdue} days</Badge>
                                        )}
                                    </TableCell>
                                    <TableCell className="text-right font-medium">{item.amount.toLocaleString()}</TableCell>
                                    <TableCell className="text-right">
                                         <DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button size="icon" variant="ghost">
                                                    <MoreVertical className="h-4 w-4" />
                                                </Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent>
                                                <DropdownMenuItem>
                                                    <CheckCircle className="mr-2 h-4 w-4" /> Initiate Payout
                                                </DropdownMenuItem>
                                                <DropdownMenuItem>View Invoice</DropdownMenuItem>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </TableCell>
                                </TableRow>
                            )
                        })}
                    </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
