
'use client';

import { useState, useMemo } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult, Branch } 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 { mockBranches } from '@/lib/data';
import { addDays } from 'date-fns';
import type { DateRange } from 'react-day-picker';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';
import { ChartContainer, ChartTooltipContent } from '@/components/ui/chart';
import { Download, Building, TrendingUp } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';

type BranchExpense = {
    branch: Branch;
    total: number;
    breakdown: {
        fuel: number;
        rent: number;
        utilities: number;
    };
};

const mockExpenses: BranchExpense[] = [
    { branch: mockBranches[0], total: 75000, breakdown: { fuel: 35000, rent: 25000, utilities: 15000 } },
    { branch: mockBranches[1], total: 120000, breakdown: { fuel: 50000, rent: 50000, utilities: 20000 } },
    { branch: mockBranches[2], total: 95000, breakdown: { fuel: 40000, rent: 40000, utilities: 15000 } },
];


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

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

  const { total, highestSpendingBranch } = useMemo(() => {
    const total = mockExpenses.reduce((sum, e) => sum + e.total, 0);
    const highest = mockExpenses.reduce((max, e) => e.total > max.total ? e : max, mockExpenses[0]);
    return { total, highestSpendingBranch: highest };
  }, []);
  

  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 Branch Expenses (Period)</CardTitle>
                        <Building className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">PKR {total.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">Highest Spending Branch</CardTitle>
                        <TrendingUp className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{highestSpendingBranch.branch.name}</div>
                        <p className="text-xs text-muted-foreground">PKR {highestSpendingBranch.total.toLocaleString()}</p>
                    </CardContent>
                </Card>
            </div>
          <Card>
            <CardHeader className="flex flex-col md:flex-row md:items-center justify-between gap-4">
              <div className="grid gap-2">
                <CardTitle>Branch Level Expenses</CardTitle>
                <CardDescription>
                  View and analyze expenses across all branches.
                </CardDescription>
              </div>
              <div className="flex items-center gap-2">
                <DatePickerWithRange date={dateRange} setDate={setDateRange} />
                <Button variant="outline"><Download className="mr-2 h-4 w-4" /> Export</Button>
              </div>
            </CardHeader>
            <CardContent className="space-y-8">
                <div>
                    <h3 className="text-lg font-semibold mb-4">Branch Expense Comparison</h3>
                    <ChartContainer config={{}} className="h-80 w-full">
                        <ResponsiveContainer>
                            <BarChart data={mockExpenses}>
                                <XAxis dataKey="branch.name" stroke="#888888" fontSize={12} tickLine={false} axisLine={false} />
                                <YAxis stroke="#888888" fontSize={12} tickLine={false} axisLine={false} tickFormatter={(value) => `PKR ${value / 1000}k`} />
                                <Tooltip content={<ChartTooltipContent />} />
                                <Bar dataKey="total" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} />
                            </BarChart>
                        </ResponsiveContainer>
                    </ChartContainer>
                </div>

                <div>
                    <h3 className="text-lg font-semibold mb-4">Detailed Breakdown</h3>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Branch</TableHead>
                                <TableHead>Fuel</TableHead>
                                <TableHead>Rent</TableHead>
                                <TableHead>Utilities</TableHead>
                                <TableHead className="text-right">Total</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {mockExpenses.map(expense => (
                                <TableRow key={expense.branch.id}>
                                    <TableCell className="font-medium">{expense.branch.name}</TableCell>
                                    <TableCell>PKR {expense.breakdown.fuel.toLocaleString()}</TableCell>
                                    <TableCell>PKR {expense.breakdown.rent.toLocaleString()}</TableCell>
                                    <TableCell>PKR {expense.breakdown.utilities.toLocaleString()}</TableCell>
                                    <TableCell className="text-right font-bold">PKR {expense.total.toLocaleString()}</TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </div>
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
