
'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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DatePickerWithRange } from '@/components/ui/date-range-picker';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, Download, MoreVertical, PlusCircle, Search, Upload } from 'lucide-react';
import { mockSellers } from '@/lib/data';
import { addDays, format } from 'date-fns';
import type { DateRange } from 'react-day-picker';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import Link from 'next/link';

type Invoice = {
  id: string;
  invoiceNumber: string;
  merchant: Seller;
  date: string;
  amount: number;
  status: 'Paid' | 'Unpaid' | 'Overdue';
  type: 'Generated' | 'Uploaded';
};

const mockInvoices: Invoice[] = [
  { id: 'inv-1', invoiceNumber: 'INV-2024-001', merchant: mockSellers[0], date: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(), amount: 45600, status: 'Paid', type: 'Generated' },
  { id: 'inv-2', invoiceNumber: 'INV-2024-002', merchant: mockSellers[1], date: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(), amount: 78950, status: 'Unpaid', type: 'Generated' },
  { id: 'inv-3', invoiceNumber: 'EXT-001', merchant: mockSellers[0], date: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(), amount: 12300, status: 'Paid', type: 'Uploaded' },
  { id: 'inv-4', invoiceNumber: 'INV-2024-003', merchant: mockSellers[1], date: new Date(Date.now() - 40 * 24 * 60 * 60 * 1000).toISOString(), amount: 33200, status: 'Overdue', type: 'Generated' },
];

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

  const [dateRange, setDateRange] = useState<DateRange | undefined>({
    from: addDays(new Date(), -30),
    to: new Date(),
  });
  
  const filteredInvoices = useMemo(() => {
    return mockInvoices.filter(i => {
        const invoiceDate = new Date(i.date);
        return dateRange?.from && dateRange?.to && invoiceDate >= dateRange.from && invoiceDate <= dateRange.to;
    });
  }, [dateRange]);

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

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="finance">
        <div className="flex flex-col gap-8">
          <Card>
            <CardHeader className="flex flex-row items-center">
              <div className="grid gap-2 flex-1">
                <CardTitle>Merchant Invoices</CardTitle>
                <CardDescription>
                  View, generate, and manage all merchant invoices.
                </CardDescription>
              </div>
               <div className="flex items-center gap-2">
                    <Button asChild variant="outline">
                        <Link href="/admin/finance/invoices/upload"><Upload className="mr-2 h-4 w-4" /> Upload Invoice</Link>
                    </Button>
                    <Button asChild>
                        <Link href="/admin/finance/invoices/generate"><PlusCircle className="mr-2 h-4 w-4" /> Generate Invoice</Link>
                    </Button>
               </div>
            </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">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>
                       <div>
                          <label className="text-sm font-medium">Status</label>
                          <Select><SelectTrigger><SelectValue placeholder="All Statuses" /></SelectTrigger></Select>
                      </div>
                      <Button><Search className="mr-2 h-4 w-4" /> Search</Button>
                  </div>
              </div>
              
              <div>
                <h3 className="text-lg font-semibold mb-4">Invoice Log</h3>
                 <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Invoice #</TableHead>
                            <TableHead>Merchant</TableHead>
                            <TableHead>Date</TableHead>
                            <TableHead>Type</TableHead>
                            <TableHead>Status</TableHead>
                            <TableHead className="text-right">Amount (PKR)</TableHead>
                            <TableHead className="text-right">Action</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {filteredInvoices.map(item => (
                            <TableRow key={item.id}>
                                <TableCell className="font-medium">{item.invoiceNumber}</TableCell>
                                <TableCell>{item.merchant.name}</TableCell>
                                <TableCell>{format(new Date(item.date), 'dd MMM, yyyy')}</TableCell>
                                <TableCell>
                                    <Badge variant={item.type === 'Generated' ? 'default' : 'secondary'}>{item.type}</Badge>
                                </TableCell>
                                <TableCell>
                                    <Badge variant="outline" className={getStatusBadge(item.status)}>
                                        {item.status}
                                    </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>
                                                <Download className="mr-2 h-4 w-4" /> Download PDF
                                            </DropdownMenuItem>
                                            <DropdownMenuItem disabled={item.status !== 'Unpaid'}>
                                                <CheckCircle className="mr-2 h-4 w-4" /> Mark as Paid
                                            </DropdownMenuItem>
                                        </DropdownMenuContent>
                                    </DropdownMenu>
                                </TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}

