
'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 { Download, MoreVertical, Search, WalletCards, CheckCircle, Clock, Banknote, RefreshCw } 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';

type Payment = {
  id: string;
  merchant: Seller;
  date: string;
  amount: number;
  status: 'Paid' | 'Pending' | 'Failed';
  paymentMethod: string;
};

const mockPayments: Payment[] = [
  { id: 'PAY-001', merchant: mockSellers[0], date: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(), amount: 45600, status: 'Paid', paymentMethod: 'Bank Transfer' },
  { id: 'PAY-002', merchant: mockSellers[1], date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(), amount: 78950, status: 'Pending', paymentMethod: 'Bank Transfer' },
  { id: 'PAY-003', merchant: mockSellers[0], date: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString(), amount: 12300, status: 'Paid', paymentMethod: 'Bank Transfer' },
  { id: 'PAY-004', merchant: mockSellers[1], date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(), amount: 33200, status: 'Failed', paymentMethod: 'Bank Transfer' },
];

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

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

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

  const summary = useMemo(() => {
    return filteredPayments.reduce((acc, p) => {
        if(p.status === 'Paid') acc.totalPaid += p.amount;
        if(p.status === 'Pending') acc.pendingPayouts++;
        return acc;
    }, { totalPaid: 0, pendingPayouts: 0, merchantsPaid: new Set(filteredPayments.filter(p => p.status === 'Paid').map(p => p.merchant.id)).size });
  }, [filteredPayments]);
  

  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>
                        <Banknote className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">PKR {summary.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">Payouts Pending Approval</CardTitle>
                        <Clock className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{summary.pendingPayouts}</div>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Merchants Paid (Period)</CardTitle>
                        <CheckCircle className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{summary.merchantsPaid}</div>
                    </CardContent>
                </Card>
            </div>
          <Card>
            <CardHeader className="flex flex-row items-center">
              <div className="grid gap-2 flex-1">
                <CardTitle>Merchant Payments</CardTitle>
                <CardDescription>
                  Review, approve, and track payments to merchants.
                </CardDescription>
              </div>
               <div className="flex items-center gap-2">
                    <Button>
                        <WalletCards className="mr-2 h-4 w-4" /> Initiate Bulk Payout
                    </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">Payment History</h3>
                 <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Payment ID</TableHead>
                            <TableHead>Merchant</TableHead>
                            <TableHead>Date</TableHead>
                            <TableHead>Method</TableHead>
                            <TableHead>Status</TableHead>
                            <TableHead className="text-right">Amount (PKR)</TableHead>
                            <TableHead className="text-right">Action</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {filteredPayments.map(item => (
                            <TableRow key={item.id}>
                                <TableCell className="font-medium">{item.id}</TableCell>
                                <TableCell>{item.merchant.name}</TableCell>
                                <TableCell>{format(new Date(item.date), 'dd MMM, yyyy')}</TableCell>
                                <TableCell>{item.paymentMethod}</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 Receipt
                                            </DropdownMenuItem>
                                            <DropdownMenuItem disabled={item.status !== 'Pending'}>
                                                <CheckCircle className="mr-2 h-4 w-4" /> Approve Payment
                                            </DropdownMenuItem>
                                             <DropdownMenuItem disabled={item.status !== 'Failed'} className="text-red-500">
                                                <RefreshCw className="mr-2 h-4 w-4" /> Retry Payment
                                            </DropdownMenuItem>
                                        </DropdownMenuContent>
                                    </DropdownMenu>
                                </TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
