
'use client';

import { useState, useMemo } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult, Rider, Branch } from '@/lib/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { DatePickerWithRange } from '@/components/ui/date-range-picker';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { AlertTriangle, TrendingDown, TrendingUp, MoreVertical, Search, CheckCircle, Hourglass } from 'lucide-react';
import { mockRiders, mockBranches } 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 Discrepancy = {
  id: string;
  date: string;
  rider: Rider;
  branch: Branch;
  scannedAmount: number;
  depositedAmount: number;
  variance: number;
  status: 'Under Review' | 'Resolved';
};

const mockDiscrepancies: Discrepancy[] = [
  { id: 'DISC-001', date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(), rider: mockRiders[0], branch: mockBranches[0], scannedAmount: 15500, depositedAmount: 15000, variance: -500, status: 'Under Review' },
  { id: 'DISC-002', date: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(), rider: mockRiders[1], branch: mockBranches[1], scannedAmount: 12300, depositedAmount: 12300, variance: 0, status: 'Resolved' },
  { id: 'DISC-003', date: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(), rider: mockRiders[2], branch: mockBranches[2], scannedAmount: 9800, depositedAmount: 9500, variance: -300, status: 'Under Review' },
];

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

  const [dateRange, setDateRange] = useState<DateRange | undefined>({
    from: addDays(new Date(), -7),
    to: new Date(),
  });
  
  const filteredDiscrepancies = useMemo(() => {
    return mockDiscrepancies.filter(d => {
        const discrepancyDate = new Date(d.date);
        return dateRange?.from && dateRange?.to && discrepancyDate >= dateRange.from && discrepancyDate <= dateRange.to;
    });
  }, [dateRange]);

  const summary = useMemo(() => {
    return filteredDiscrepancies.reduce((acc, d) => {
        if(d.status === 'Under Review') {
            acc.underReviewCount++;
            acc.underReviewAmount += Math.abs(d.variance);
        }
        if(d.variance !== 0) {
            acc.totalDiscrepancies++;
        }
        if(d.status === 'Resolved') {
            acc.resolvedAmount += Math.abs(d.variance);
        }
        return acc;
    }, { totalDiscrepancies: 0, underReviewCount: 0, underReviewAmount: 0, resolvedAmount: 0 });
  }, [filteredDiscrepancies]);
  

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="finance">
        <div className="flex flex-col gap-8">
          <Card>
            <CardHeader>
              <CardTitle>COD Variance Report</CardTitle>
              <CardDescription>
                Automatically flagged mismatches between cash scanned and cash deposited.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-8">
               <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                  <Card>
                      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                          <CardTitle className="text-sm font-medium">Total Discrepancies</CardTitle>
                          <AlertTriangle className="h-4 w-4 text-muted-foreground" />
                      </CardHeader>
                      <CardContent>
                          <div className="text-2xl font-bold">{summary.totalDiscrepancies}</div>
                          <p className="text-xs text-muted-foreground">in selected period</p>
                      </CardContent>
                  </Card>
                   <Card>
                      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                          <CardTitle className="text-sm font-medium">Amount Under Review</CardTitle>
                          <TrendingDown className="h-4 w-4 text-red-500" />
                      </CardHeader>
                      <CardContent>
                          <div className="text-2xl font-bold">PKR {summary.underReviewAmount.toLocaleString()}</div>
                          <p className="text-xs text-muted-foreground">across {summary.underReviewCount} cases</p>
                      </CardContent>
                  </Card>
                  <Card>
                      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                          <CardTitle className="text-sm font-medium">Resolved Amount</CardTitle>
                          <TrendingUp className="h-4 w-4 text-green-500" />
                      </CardHeader>
                      <CardContent>
                          <div className="text-2xl font-bold">PKR {summary.resolvedAmount.toLocaleString()}</div>
                           <p className="text-xs text-muted-foreground">in selected period</p>
                      </CardContent>
                  </Card>
              </div>

               <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">Branch</label>
                          <Select><SelectTrigger><SelectValue placeholder="All Branches" /></SelectTrigger></Select>
                      </div>
                       <div>
                          <label className="text-sm font-medium">Rider</label>
                          <Select><SelectTrigger><SelectValue placeholder="All Riders" /></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">Discrepancy Details</h3>
                 <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Date</TableHead>
                            <TableHead>Rider</TableHead>
                            <TableHead>Branch</TableHead>
                            <TableHead>Scanned Amount</TableHead>
                            <TableHead>Deposited Amount</TableHead>
                            <TableHead>Variance</TableHead>
                            <TableHead>Status</TableHead>
                            <TableHead className="text-right">Action</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {filteredDiscrepancies.map(item => (
                            <TableRow key={item.id}>
                                <TableCell>{format(new Date(item.date), 'dd MMM, yyyy')}</TableCell>
                                <TableCell>{item.rider.name}</TableCell>
                                <TableCell>{item.branch.name}</TableCell>
                                <TableCell>PKR {item.scannedAmount.toLocaleString()}</TableCell>
                                <TableCell>PKR {item.depositedAmount.toLocaleString()}</TableCell>
                                <TableCell className={`font-semibold ${item.variance < 0 ? 'text-red-600' : 'text-green-600'}`}>
                                    PKR {item.variance.toLocaleString()}
                                </TableCell>
                                <TableCell>
                                    <Badge variant={item.status === 'Resolved' ? 'default' : 'destructive'} className={item.status === 'Resolved' ? 'bg-green-100 text-green-800' : ''}>
                                        {item.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 disabled={item.status === 'Resolved'}>
                                                <Hourglass className="mr-2 h-4 w-4" /> Start Investigation
                                            </DropdownMenuItem>
                                            <DropdownMenuItem disabled={item.status === 'Resolved'}>
                                                <CheckCircle className="mr-2 h-4 w-4" /> Mark as Resolved
                                            </DropdownMenuItem>
                                        </DropdownMenuContent>
                                    </DropdownMenu>
                                </TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
