
"use client"

import * as React from "react"
import { addDays, format, startOfMonth, endOfMonth, eachMonthOfInterval, subMonths } from "date-fns"
import { Calendar as CalendarIcon } from "lucide-react"
import { DateRange } from "react-day-picker"

import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { PageHeader } from "@/components/page-header"
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/components/ui/card"
import { ResponsiveContainer, BarChart, XAxis, YAxis, Tooltip, Legend, Bar } from "recharts"
import { getMockOrders, getOtherExpenses, getMockEmployees, getMockIncome } from "@/lib/data"
import { ChartConfig, ChartContainer } from "@/components/ui/chart"
import { Skeleton } from "@/components/ui/skeleton"

const chartConfig = {
  income: {
    label: "Income",
    color: "hsl(var(--chart-1))",
  },
  expenses: {
    label: "Expenses",
    color: "hsl(var(--chart-2))",
  },
} satisfies ChartConfig

type ChartData = {
  month: string;
  income: number;
  expenses: number;
}

export default function ReportsPage() {
  const [date, setDate] = React.useState<DateRange | undefined>()
  const [chartData, setChartData] = React.useState<ChartData[]>([]);
  const [isLoading, setIsLoading] = React.useState(true);
  const [totalIncome, setTotalIncome] = React.useState(0);
  const [totalExpenses, setTotalExpenses] = React.useState(0);
  const [totalProfit, setTotalProfit] = React.useState(0);


  const generateReportData = React.useCallback((dateRange?: DateRange) => {
    setIsLoading(true);

    const orders = getMockOrders();
    const otherExpenses = getOtherExpenses();
    const otherIncome = getMockIncome();

    const reportStartDate = dateRange?.from || subMonths(new Date(), 5);
    const reportEndDate = dateRange?.to || new Date();

    const start = startOfMonth(reportStartDate);
    const end = endOfMonth(reportEndDate);
    const months = eachMonthOfInterval({ start, end });

    let grandTotalIncome = 0;
    let grandTotalExpenses = 0;

    const data = months.map(month => {
        const monthStart = startOfMonth(month);
        const monthEnd = endOfMonth(month);

        const monthlyIncomeFromOrders = orders
            .filter(o => {
                const orderDate = new Date(o.date);
                return orderDate >= monthStart && orderDate <= monthEnd && o.paidAmount > 0;
            })
            .reduce((sum, o) => sum + o.paidAmount, 0);

        const monthlyOtherIncome = otherIncome
            .filter(i => {
                 const incomeDate = new Date(i.date);
                 return incomeDate >= monthStart && incomeDate <= monthEnd;
            })
            .reduce((sum, i) => sum + i.amount, 0);
        
        const totalMonthlyIncome = monthlyIncomeFromOrders + monthlyOtherIncome;

        const totalMonthlyExpenses = otherExpenses
            .filter(e => {
                const expenseDate = new Date(e.date);
                return expenseDate >= monthStart && expenseDate <= monthEnd;
            })
            .reduce((sum, e) => sum + e.amount, 0);
        
        grandTotalIncome += totalMonthlyIncome;
        grandTotalExpenses += totalMonthlyExpenses;

        return {
            month: format(month, 'MMM yyyy'),
            income: parseFloat(totalMonthlyIncome.toFixed(2)),
            expenses: parseFloat(totalMonthlyExpenses.toFixed(2)),
        }
    });

    setChartData(data);
    setTotalIncome(grandTotalIncome);
    setTotalExpenses(grandTotalExpenses);
    setTotalProfit(grandTotalIncome - grandTotalExpenses);
    setIsLoading(false);
  }, []);

  React.useEffect(() => {
    // Generate default report for the last 6 months on initial load
    generateReportData();
  }, [generateReportData]);

  const handleGenerateReport = () => {
    generateReportData(date);
  }

  return (
    <div className="flex flex-col gap-4">
      <PageHeader title="Reports">
        <div className={cn("grid gap-2")}>
          <Popover>
            <PopoverTrigger asChild>
              <Button
                id="date"
                variant={"outline"}
                className={cn(
                  "w-[300px] justify-start text-left font-normal",
                  !date && "text-muted-foreground"
                )}
              >
                <CalendarIcon className="mr-2 h-4 w-4" />
                {date?.from ? (
                  date.to ? (
                    <>
                      {format(date.from, "LLL dd, y")} -{" "}
                      {format(date.to, "LLL dd, y")}
                    </>
                  ) : (
                    format(date.from, "LLL dd, y")
                  )
                ) : (
                  <span>Pick a date range</span>
                )}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="end">
              <Calendar
                initialFocus
                mode="range"
                defaultMonth={date?.from}
                selected={date}
                onSelect={setDate}
                numberOfMonths={2}
              />
            </PopoverContent>
          </Popover>
        </div>
        <Button onClick={handleGenerateReport} disabled={isLoading}>
            {isLoading ? 'Generating...' : 'Generate Report'}
        </Button>
      </PageHeader>
      
      <Card>
          <CardHeader>
            <CardTitle className="font-headline">Financial Summary</CardTitle>
            <CardDescription>
              {date?.from && date?.to 
                ? `Income vs. Expenses from ${format(date.from, "LLL dd, y")} to ${format(date.to, "LLL dd, y")}.`
                : "Income vs. Expenses for the last 6 months."
              }
            </CardDescription>
          </CardHeader>
          <CardContent>
            {isLoading ? (
                <div className="min-h-[400px] w-full flex items-center justify-center">
                    <Skeleton className="h-full w-full" />
                </div>
            ) : chartData.length > 0 ? (
                <ChartContainer config={chartConfig} className="min-h-[400px] w-full">
                <ResponsiveContainer width="100%" height={400}>
                    <BarChart data={chartData}>
                    <XAxis dataKey="month" stroke="#888888" fontSize={12} tickLine={false} axisLine={false} />
                    <YAxis stroke="#888888" fontSize={12} tickLine={false} axisLine={false} tickFormatter={(value) => `৳${value/1000}k`} />
                    <Tooltip
                        cursor={{fill: 'hsl(var(--muted))'}}
                        contentStyle={{
                        backgroundColor: 'hsl(var(--background))',
                        borderColor: 'hsl(var(--border))',
                        borderRadius: 'var(--radius)',
                        }}
                    />
                    <Legend />
                    <Bar dataKey="income" fill="hsl(var(--chart-1))" radius={[4, 4, 0, 0]} />
                    <Bar dataKey="expenses" fill="hsl(var(--chart-2))" radius={[4, 4, 0, 0]} />
                    </BarChart>
                </ResponsiveContainer>
                </ChartContainer>
            ) : (
                <div className="min-h-[400px] w-full flex flex-col items-center justify-center bg-muted/50 rounded-lg">
                    <p className="text-lg font-semibold text-muted-foreground">No data available</p>
                    <p className="text-sm text-muted-foreground">Please select a different date range or add some transactions.</p>
                </div>
            )}
          </CardContent>
           {!isLoading && chartData.length > 0 && (
                <CardFooter className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-center border-t pt-6">
                    <div className="p-4 bg-muted/50 rounded-lg">
                        <p className="text-sm text-muted-foreground">Total Income</p>
                        <p className="text-2xl font-bold text-green-600">৳{totalIncome.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</p>
                    </div>
                     <div className="p-4 bg-muted/50 rounded-lg">
                        <p className="text-sm text-muted-foreground">Total Expenses</p>
                        <p className="text-2xl font-bold text-red-600">৳{totalExpenses.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</p>
                    </div>
                     <div className="p-4 bg-muted/50 rounded-lg">
                        <p className="text-sm text-muted-foreground">Net Profit</p>
                        <p className="text-2xl font-bold">৳{totalProfit.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</p>
                    </div>
                </CardFooter>
            )}
        </Card>
    </div>
  )
}
