
'use client';

import { useState } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult } 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 { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
import { MoreVertical, PlusCircle, CheckCircle, Clock, Truck } from 'lucide-react';
import { format, addDays } from 'date-fns';
import { DatePickerWithRange } from '@/components/ui/date-range-picker';
import type { DateRange } from 'react-day-picker';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select';


type VendorPayment = {
  id: string;
  vendor: string;
  invoiceId: string;
  date: string;
  dueDate: string;
  amount: number;
  status: 'Paid' | 'Pending' | 'Overdue';
};

const mockPayments: VendorPayment[] = [
  { id: 'ven-1', vendor: 'Punjab Packaging', invoiceId: 'INV-PP-001', date: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(), dueDate: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(), amount: 25000, status: 'Paid' },
  { id: 'ven-2', vendor: 'National Fuel Services', invoiceId: 'INV-NFS-005', date: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(), dueDate: new Date(Date.now() + 10 * 24 * 60 * 60 * 1000).toISOString(), amount: 80000, status: 'Pending' },
  { id: 'ven-3', vendor: 'City Vehicle Repairs', invoiceId: 'INV-CVR-002', date: new Date(Date.now() - 40 * 24 * 60 * 60 * 1000).toISOString(), dueDate: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(), amount: 15000, status: 'Overdue' },
];

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

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

  const totalPaid = mockPayments.filter(p => p.status === 'Paid').reduce((sum, p) => sum + p.amount, 0);
  const pendingAmount = mockPayments.filter(p => p.status === 'Pending' || p.status === 'Overdue').reduce((sum, p) => sum + p.amount, 0);

  const getStatusBadge = (status: VendorPayment['status']) => {
    switch (status) {
        case 'Paid': return 'bg-green-100 text-green-800';
        case 'Pending': return 'bg-yellow-100 text-yellow-800';
        case 'Overdue': return 'bg-red-100 text-red-800';
    }
  }

  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 Paid (Period)</CardTitle>
                        <CheckCircle className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">PKR {totalPaid.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">Pending &amp; Overdue</CardTitle>
                        <Clock className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">PKR {pendingAmount.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">Total Vendors</CardTitle>
                        <Truck className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">3</div>
                    </CardContent>
                </Card>
            </div>
          <Card>
            <CardHeader className="flex flex-row items-center">
                <div className="grid gap-2">
                    <CardTitle>Vendor Payments</CardTitle>
                    <CardDescription>
                        Track and manage payments to vendors for supplies and services.
                    </CardDescription>
                </div>
                <Button size="sm" className="ml-auto gap-1">
                    <PlusCircle className="h-4 w-4" />
                    Add Payment
                </Button>
            </CardHeader>
            <CardContent className="space-y-6">
                <div className="p-4 border rounded-lg bg-muted/50 grid grid-cols-1 md:grid-cols-3 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">Vendor</label>
                        <Select><SelectTrigger><SelectValue placeholder="All Vendors"/></SelectTrigger></Select>
                    </div>
                     <div>
                        <label className="text-sm font-medium">Status</label>
                        <Select><SelectTrigger><SelectValue placeholder="All Statuses"/></SelectTrigger></Select>
                    </div>
                </div>

                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Vendor</TableHead>
                            <TableHead>Invoice ID</TableHead>
                            <TableHead>Due Date</TableHead>
                            <TableHead>Amount (PKR)</TableHead>
                            <TableHead>Status</TableHead>
                            <TableHead className="text-right">Actions</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {mockPayments.map(payment => (
                            <TableRow key={payment.id}>
                                <TableCell className="font-medium">{payment.vendor}</TableCell>
                                <TableCell>{payment.invoiceId}</TableCell>
                                <TableCell>{format(new Date(payment.dueDate), 'dd MMM, yyyy')}</TableCell>
                                <TableCell>{payment.amount.toLocaleString()}</TableCell>
                                <TableCell>
                                    <Badge variant="outline" className={getStatusBadge(payment.status)}>{payment.status}</Badge>
                                </TableCell>
                                <TableCell className="text-right">
                                     <DropdownMenu>
                                        <DropdownMenuTrigger asChild>
                                            <Button size="icon" variant="ghost">
                                                <MoreVertical className="h-4 w-4" />
                                            </Button>
                                        </DropdownMenuTrigger>
                                        <DropdownMenuContent>
                                            <DropdownMenuItem>View Invoice</DropdownMenuItem>
                                            <DropdownMenuItem disabled={payment.status === 'Paid'}>Mark as Paid</DropdownMenuItem>
                                        </DropdownMenuContent>
                                    </DropdownMenu>
                                </TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
