
'use client';

import { useState, useEffect, useMemo } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import { mockParcels as allParcelsData, mockComplaints, mockSellers, mockMarketingTeam, mockBranches } from '@/lib/data';
import type { BookingResult, Parcel, Complaint, TimeRange } from '@/lib/types';
import { SellersTable } from '@/components/admin/sellers-table';
import { BranchesTable } from '@/components/admin/branches-table';
import { MarketingStaffTable } from '@/components/admin/marketing-staff-table';
import { ComplaintsTable } from '@/components/complaints/complaints-table';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Banknote, Hourglass, Receipt, Ticket, CheckCircle, ShieldAlert, Users, Truck, BookCopy, Building } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { subDays, isWithinInterval, startOfDay, endOfDay, startOfMonth, endOfMonth, startOfYear, endOfYear, subMonths } from 'date-fns';
import type { DateRange } from 'react-day-picker';
import { DatePickerWithRange } from '@/components/ui/date-range-picker';
import { Button } from '@/components/ui/button';


const filterByDate = <T extends { bookingDate?: string; date?: string }>(items: T[], timeRange: TimeRange, customRange?: DateRange): T[] => {
    if (timeRange === '-1' && !customRange) return items; // All time

    let startDate: Date;
    let endDate: Date = endOfDay(new Date());

    if (timeRange === 'custom' && customRange?.from) {
        startDate = startOfDay(customRange.from);
        endDate = customRange.to ? endOfDay(customRange.to) : endOfDay(customRange.from);
    } else {
        const days = parseInt(timeRange);
        startDate = startOfDay(subDays(new Date(), days));
    }

    return items.filter(item => {
        const itemDateStr = item.date || item.bookingDate;
        if (!itemDateStr) return false;
        const itemDate = new Date(itemDateStr);
        return isWithinInterval(itemDate, { start: startDate, end: endDate });
    });
};


export default function AdminDashboard() {
  const [allParcels, setAllParcels] = useState<Parcel[]>([]);
  const [allComplaints, setAllComplaints] = useState<Complaint[]>([]);
  const [timeRange, setTimeRange] = useState<TimeRange>('7');
  const [customDateRange, setCustomDateRange] = useState<DateRange | undefined>(undefined);
  
  useEffect(() => {
    setAllParcels(allParcelsData);
    setAllComplaints(mockComplaints);
  }, []);

  const { filteredParcels, filteredComplaints } = useMemo(() => {
    return {
        filteredParcels: filterByDate(allParcels, timeRange, customDateRange),
        filteredComplaints: filterByDate(allComplaints, timeRange, customDateRange),
    }
  }, [allParcels, allComplaints, timeRange, customDateRange]);

  const handleTimeRangeChange = (value: TimeRange) => {
    setTimeRange(value);
    if (value !== 'custom') {
      setCustomDateRange(undefined);
    }
  }


  const handleBookingComplete = (result: BookingResult) => {
    if (result) {
      setAllParcels(prevParcels => [result.parcel, ...prevParcels]);
    }
  };

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole='super-admin'>
        <div className="flex flex-col gap-8">
            <div className="flex flex-wrap items-end justify-end gap-4">
                <div className="flex items-center gap-2">
                    <Select value={timeRange} onValueChange={handleTimeRangeChange}>
                        <SelectTrigger className="w-[180px]">
                            <SelectValue placeholder="Select time range" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="0">Today</SelectItem>
                            <SelectItem value="7">Last 7 days</SelectItem>
                            <SelectItem value="30">Last 30 days</SelectItem>
                            <SelectItem value="365">Last 365 days</SelectItem>
                            <SelectItem value="-1">All Time</SelectItem>
                            <SelectItem value="custom">Custom Range</SelectItem>
                        </SelectContent>
                    </Select>
                    {timeRange === 'custom' && (
                        <DatePickerWithRange date={customDateRange} setDate={setCustomDateRange} />
                    )}
                </div>
            </div>
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
                 <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Bookings</CardTitle>
                        <BookCopy className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{filteredParcels.length}</div>
                        <p className="text-xs text-muted-foreground">Parcel bookings</p>
                    </CardContent>
                </Card>
                 <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Delivered</CardTitle>
                        <CheckCircle className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{filteredParcels.filter(p => p.status === 'Delivered').length}</div>
                        <p className="text-xs text-muted-foreground">Successful deliveries</p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Sellers</CardTitle>
                        <Users className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{mockSellers.length}</div>
                        <p className="text-xs text-muted-foreground">Number of registered sellers</p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Riders</CardTitle>
                        <Truck className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">42</div>
                        <p className="text-xs text-muted-foreground">Number of active riders</p>
                    </CardContent>
                </Card>
                 <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Branches</CardTitle>
                        <Building className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{mockBranches.length}</div>
                        <p className="text-xs text-muted-foreground">Number of branches</p>
                    </CardContent>
                </Card>
            </div>
          
           <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">Pending COD</CardTitle>
                        <Hourglass className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">PKR 1,250,000</div>
                        <p className="text-xs text-muted-foreground">Awaiting collection across all branches</p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Reconciled COD</CardTitle>
                        <Banknote className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">PKR 5,750,000</div>
                        <p className="text-xs text-muted-foreground">Total verified and reconciled amount</p>
                    </CardContent>
                </Card>
                 <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Expenses</CardTitle>
                        <Receipt className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">PKR 320,000</div>
                        <p className="text-xs text-muted-foreground">This month's total operational expenses</p>
                    </CardContent>
                </Card>
            </div>
            
            <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">Open Tickets</CardTitle>
                        <Ticket className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{filteredComplaints.filter(c => c.status === 'Open' || c.status === 'In Progress').length}</div>
                        <p className="text-xs text-muted-foreground">Tickets requiring attention</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 Today</CardTitle>
                        <CheckCircle className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{filterByDate(allComplaints.filter(c => c.status === 'Resolved' || c.status === 'Closed'), '0').length}</div>
                         <p className="text-xs text-muted-foreground">Tickets closed today</p>
                    </CardContent>
                </Card>
                 <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">SLA Breaches</CardTitle>
                        <ShieldAlert className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">3</div>
                        <p className="text-xs text-muted-foreground">Tickets that have breached SLA</p>
                    </CardContent>
                </Card>
            </div>

          <div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
            <div className="lg:col-span-2">
               <SellersTable />
            </div>
            <div className="lg:col-span-1">
              <ComplaintsTable complaints={allComplaints.slice(0, 5)} />
            </div>
          </div>
          <div className="grid grid-cols-1 gap-8 lg:grid-cols-2">
            <MarketingStaffTable />
            <BranchesTable />
          </div>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}

    

