'use client';

import {
  Activity,
  ArrowUpRight,
  CreditCard,
  DollarSign,
  Users,
  Package,
  AlertCircle,
  ShoppingCart,
  PlusCircle,
} from "lucide-react"
import Link from "next/link"
import React, { useState, useEffect, useMemo } from 'react';

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Bar,
  BarChart,
  ResponsiveContainer,
  XAxis,
  YAxis,
  Tooltip,
  Legend,
} from "recharts"
import { format, subMonths, startOfMonth, endOfMonth, eachMonthOfInterval } from 'date-fns';
import { ChartConfig, ChartContainer } from "@/components/ui/chart"
import { getMockOrders, getMockInventory, getMockIncome, getOtherExpenses, getMockCustomers, getArtisans, getCuttingMasters, getMockTailoringItems, type Order, type InventoryItem, type Customer, type Employee, type TailoringItem } from "@/lib/data"
import { OrderDialog } from "@/components/orders/order-dialog";

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 DashboardPage() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [inventory, setInventory] = useState<InventoryItem[]>([]);
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [tailoringItems, setTailoringItems] = useState<TailoringItem[]>([]);
  const [artisans, setArtisans] = useState<Employee[]>([]);
  const [cuttingMasters, setCuttingMasters] = useState<Employee[]>([]);
  const [isOrderDialogOpen, setIsOrderDialogOpen] = useState(false);
  const [dashboardData, setDashboardData] = useState({
      totalRevenue: 0,
      newCustomers: 0,
      monthlyChartData: [] as ChartData[],
  });

   useEffect(() => {
    loadDashboardData();

    const handleStorageChange = () => {
      loadDashboardData();
    };

    window.addEventListener('storage', handleStorageChange);
    return () => {
        window.removeEventListener('storage', handleStorageChange);
    };
  }, []);

  const loadDashboardData = () => {
    const ordersData = getMockOrders();
    const inventoryData = getMockInventory();
    const customersData = getMockCustomers();
    const incomeData = getMockIncome();
    const expensesData = getOtherExpenses();

    setOrders(ordersData);
    setInventory(inventoryData);
    setCustomers(customersData);
    setTailoringItems(getMockTailoringItems());
    setArtisans(getArtisans());
    setCuttingMasters(getCuttingMasters());

    // Calculate Total Revenue
    const incomeFromOrders = ordersData.reduce((sum, order) => sum + order.paidAmount, 0);
    const otherIncome = incomeData.reduce((sum, income) => sum + income.amount, 0);
    const totalRevenue = incomeFromOrders + otherIncome;
    
    // Calculate New Customers (last 30 days)
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    // Note: We don't have a customer creation date, so this is a placeholder. 
    // A real implementation would need a `joinDate` on the customer object.
    const newCustomers = 0; 
    
    // Generate Chart Data for last 6 months
    const start = startOfMonth(subMonths(new Date(), 5));
    const end = endOfMonth(new Date());
    const months = eachMonthOfInterval({ start, end });

    const monthlyChartData = months.map(month => {
        const monthStart = startOfMonth(month);
        const monthEnd = endOfMonth(month);

        const monthlyIncomeFromOrders = ordersData
            .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 = incomeData
            .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 monthlyOtherExpenses = expensesData
            .filter(e => {
                const expenseDate = new Date(e.date);
                return expenseDate >= monthStart && expenseDate <= monthEnd;
            })
            .reduce((sum, e) => sum + e.amount, 0);

        const monthlyArtisanWages = ordersData
             .filter(o => {
                const orderDate = new Date(o.artisanCompletedDate || o.date);
                return o.totalArtisanWage && orderDate >= monthStart && orderDate <= monthEnd;
            })
            .reduce((sum, o) => sum + o.totalArtisanWage!, 0);

        const totalMonthlyExpenses = monthlyOtherExpenses + monthlyArtisanWages;

        return {
            month: format(month, 'MMM'),
            income: parseFloat(totalMonthlyIncome.toFixed(2)),
            expenses: parseFloat(totalMonthlyExpenses.toFixed(2)),
        }
    });

    setDashboardData({
      totalRevenue,
      newCustomers,
      monthlyChartData,
    });
  }

  const handleAddOrder = (newOrderData: Omit<Order, 'id' | 'date'>) => {
    const currentOrders = getMockOrders();
    const newOrder: Order = {
      id: `ORD${(currentOrders.length + 1).toString().padStart(3, '0')}`,
      ...newOrderData,
      date: new Date().toISOString().split('T')[0],
    };
    
    let customerId = newOrderData.customerId;
    const currentCustomers = getMockCustomers();
    if (!customerId) {
        const existingCustomer = currentCustomers.find(c => c.name.toLowerCase() === newOrderData.customer.toLowerCase() && c.phone === newOrderData.phone);
        if (existingCustomer) {
            customerId = existingCustomer.id;
        } else {
            const newCustomer: Customer = {
                id: `CUST${(currentCustomers.length + 1).toString().padStart(3, '0')}`,
                name: newOrderData.customer,
                phone: newOrderData.phone,
            };
            const newCustomers = [newCustomer, ...currentCustomers];
            localStorage.setItem('mockCustomers', JSON.stringify(newCustomers));
            customerId = newCustomer.id;
        }
    }

    const finalOrder = { ...newOrder, customerId: customerId! };
    const newOrders = [finalOrder, ...currentOrders];
    localStorage.setItem('mockOrders', JSON.stringify(newOrders));
    
    loadDashboardData();
  };

  const pendingOrders = orders.filter(o => o.status === 'New' || o.status === 'In Progress' || o.status === 'Ready for Delivery');
  const lowStockItems = inventory.filter(item => item.quantity > 0 && item.quantity < item.lowStockThreshold);

  return (
    <div className="flex flex-col gap-4">
       <OrderDialog 
        isOpen={isOrderDialogOpen}
        onOpenChange={setIsOrderDialogOpen}
        order={null}
        customers={customers}
        tailoringItems={tailoringItems}
        artisans={artisans}
        cuttingMasters={cuttingMasters}
        onOrderSubmit={handleAddOrder}
      />
      <div className="grid gap-4 md:grid-cols-2 md:gap-8 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 Revenue
            </CardTitle>
            <DollarSign className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">৳{dashboardData.totalRevenue.toFixed(2)}</div>
            <p className="text-xs text-muted-foreground">
              Total revenue from all sources
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              Pending Orders
            </CardTitle>
            <ShoppingCart className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">+{pendingOrders.length}</div>
            <p className="text-xs text-muted-foreground">
              Across all customers
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">New Customers</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">+{customers.length}</div>
            <p className="text-xs text-muted-foreground">
              Total customers in database
            </p>
          </CardContent>
        </Card>
         <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">
                Low Stock
                </CardTitle>
                <AlertCircle className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <div className="text-2xl font-bold">{lowStockItems.length} items</div>
                <p className="text-xs text-muted-foreground">
                Items that need restocking
                </p>
            </CardContent>
        </Card>
      </div>
      <div className="grid gap-4 md:gap-8 lg:grid-cols-2 xl:grid-cols-3">
        <Card className="xl:col-span-2">
          <CardHeader>
            <CardTitle className="font-headline">Monthly Performance</CardTitle>
            <CardDescription>
              An overview of your income and expenses for the last 6 months.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={chartConfig} className="min-h-[300px] w-full">
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={dashboardData.monthlyChartData}>
                  <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>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center">
             <div className="grid gap-2">
                <CardTitle className="font-headline">Pending Orders</CardTitle>
                <CardDescription>
                You have {pendingOrders.length} active orders.
                </CardDescription>
            </div>
             <div className="ml-auto flex items-center gap-2">
                 <Button asChild size="sm" className="h-8 gap-1">
                  <Link href="/dashboard/orders">
                    View All
                    <ArrowUpRight className="h-4 w-4" />
                  </Link>
                </Button>
                <Button size="sm" className="h-8 gap-1" onClick={() => setIsOrderDialogOpen(true)}>
                    <PlusCircle className="h-3.5 w-3.5" />
                    <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">Create Order</span>
                </Button>
            </div>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Customer</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">Amount</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {pendingOrders.slice(0, 5).map(order => (
                    <TableRow key={order.id}>
                        <TableCell>
                            <div className="font-medium">{order.customer}</div>
                            <div className="hidden text-sm text-muted-foreground md:inline">
                                {order.phone}
                            </div>
                        </TableCell>
                        <TableCell>
                          <Badge 
                            variant={
                              order.status === "Ready for Delivery" ? "secondary" : "outline"
                            }
                            className={order.status === 'New' ? 'border-blue-500 text-blue-500' : ''}
                          >
                            {order.status}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-right">৳{(order.totalAmount || 0).toFixed(2)}</TableCell>
                    </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
