
'use client';

import React, { useState, useEffect } from 'react';
import { File, Search, MoreHorizontal, ChevronDown } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"

import { getOtherExpenses, getMockEmployees, type Expense, Employee } from "@/lib/data"
import { PageHeader } from "@/components/page-header"
import { Input } from '@/components/ui/input';
import { AddExpenseDialog } from '@/components/expenses/add-expense-dialog';
import { ExpenseFormValues } from '@/components/expenses/add-expense-form';
import { exportToCsv } from '@/lib/utils';
import { format, subMonths, startOfMonth, endOfMonth, eachMonthOfInterval } from 'date-fns';

export default function ExpensesPage() {
    const [allExpenses, setAllExpenses] = useState<Expense[]>([]);
    const [employees, setEmployees] = useState<Employee[]>([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [editingExpense, setEditingExpense] = useState<Expense | null>(null);
    const [deletingExpense, setDeletingExpense] = useState<Expense | null>(null);
    const [selectedMonth, setSelectedMonth] = useState<Date | null>(null);

    const loadData = () => {
        const otherExpenses = getOtherExpenses();
        const employeeData = getMockEmployees();
        setAllExpenses(otherExpenses.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()));
        setEmployees(employeeData);
    };

    useEffect(() => {
        loadData();
        
        const handleStorageChange = () => {
            loadData();
        };

        window.addEventListener('storage', handleStorageChange);
        return () => {
            window.removeEventListener('storage', handleStorageChange);
        };
    }, []);
    
    const updateOtherExpenses = (newExpenses: Expense[]) => {
        localStorage.setItem('mockOtherExpenses', JSON.stringify(newExpenses));
        loadData();
    };

    const handleFormSubmit = (data: ExpenseFormValues) => {
        const otherExpenses = getOtherExpenses();
        if (editingExpense) {
            const updatedExpenses = otherExpenses.map(exp => exp.id === editingExpense.id ? { ...exp, ...data, isEditable: true } : exp);
            updateOtherExpenses(updatedExpenses);
        } else {
            const newExpense: Expense = {
                id: `exp-other-${Date.now()}`,
                ...data,
                isEditable: true,
            };
            updateOtherExpenses([newExpense, ...otherExpenses]);
        }
        closeDialogs();
    };

    const handleDelete = () => {
        if (deletingExpense) {
            const otherExpenses = getOtherExpenses();
            const newExpenses = otherExpenses.filter(exp => exp.id !== deletingExpense.id);
            updateOtherExpenses(newExpenses);
            setDeletingExpense(null);
        }
    };
    
    const openAddDialog = () => {
        setEditingExpense(null);
        setIsDialogOpen(true);
    };

    const openEditDialog = (expense: Expense) => {
        setEditingExpense(expense);
        setIsDialogOpen(true);
    };

    const openDeleteDialog = (expense: Expense) => {
        setDeletingExpense(expense);
    };

    const closeDialogs = () => {
        setIsDialogOpen(false);
        setEditingExpense(null);
    };

    const handleExport = () => {
      exportToCsv(filteredExpenses, 'expenses.csv');
    }

    const monthOptions = eachMonthOfInterval({
        start: subMonths(new Date(), 11),
        end: new Date(),
    }).reverse();

    const filteredExpenses = allExpenses.filter(expense => {
        const matchesSearch = 
            expense.category.toLowerCase().includes(searchTerm.toLowerCase()) ||
            (expense.description && expense.description.toLowerCase().includes(searchTerm.toLowerCase())) ||
            (expense.person && expense.person.toLowerCase().includes(searchTerm.toLowerCase())) ||
            new Date(expense.date).toLocaleDateString().includes(searchTerm);
        
        const matchesMonth =
            !selectedMonth ||
            (new Date(expense.date) >= startOfMonth(selectedMonth) && new Date(expense.date) <= endOfMonth(selectedMonth));

        return matchesSearch && matchesMonth;
    });


  return (
    <div className="flex flex-col gap-4">
      <PageHeader title="Expenses" actionButtonText="Add Expense" onActionButtonClick={openAddDialog}>
        <div className="relative w-full max-w-sm">
            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
            <Input
                type="search"
                placeholder="Search expenses..."
                className="pl-8 w-full"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
            />
        </div>
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="h-8 gap-1">
                <span>{selectedMonth ? format(selectedMonth, 'MMMM yyyy') : 'Filter by month'}</span>
                <ChevronDown className="h-3.5 w-3.5" />
            </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
            <DropdownMenuItem onSelect={() => setSelectedMonth(null)}>All Months</DropdownMenuItem>
            {monthOptions.map((month) => (
                <DropdownMenuItem key={month.toString()} onSelect={() => setSelectedMonth(month)}>
                {format(month, 'MMMM yyyy')}
                </DropdownMenuItem>
            ))}
            </DropdownMenuContent>
        </DropdownMenu>
        <Button size="sm" variant="outline" className="h-8 gap-1" onClick={handleExport}>
          <File className="h-3.5 w-3.5" />
          <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
            Export
          </span>
        </Button>
      </PageHeader>

      <AddExpenseDialog
            isOpen={isDialogOpen}
            onOpenChange={setIsDialogOpen}
            expense={editingExpense}
            onSubmit={handleFormSubmit}
            employees={employees}
        />

        <AlertDialog open={!!deletingExpense} onOpenChange={() => setDeletingExpense(null)}>
            <AlertDialogContent>
                <AlertDialogHeader>
                    <AlertDialogTitle>Are you sure?</AlertDialogTitle>
                    <AlertDialogDescription>
                        This will permanently delete this expense record. This action cannot be undone.
                    </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction onClick={handleDelete}>Delete</AlertDialogAction>
                </AlertDialogFooter>
            </AlertDialogContent>
       </AlertDialog>

      <Card>
        <CardHeader>
          <CardTitle>Expense Transactions</CardTitle>
          <CardDescription>
            A log of all expenses, including salaries, wages, and other operational costs.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Category</TableHead>
                <TableHead className="hidden sm:table-cell">Description/Person</TableHead>
                <TableHead className="hidden md:table-cell">Date</TableHead>
                <TableHead className="text-right">Amount</TableHead>
                 <TableHead>
                    <span className="sr-only">Actions</span>
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredExpenses.map((expense) => (
                <TableRow key={expense.id}>
                  <TableCell>
                    <div className="font-medium">{expense.category}</div>
                    <div className="text-sm text-muted-foreground md:hidden">{new Date(expense.date).toLocaleDateString()}</div>
                  </TableCell>
                  <TableCell className="hidden sm:table-cell">
                    {expense.person ? (
                         <div className="font-medium">{expense.person}</div>
                    ): (
                        expense.description
                    )}
                   
                  </TableCell>
                  <TableCell className="hidden md:table-cell">{new Date(expense.date).toLocaleDateString()}</TableCell>
                  <TableCell className="text-right text-red-600">-৳{expense.amount.toFixed(2)}</TableCell>
                  <TableCell>
                    {expense.isEditable && (
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                            <Button
                                aria-haspopup="true"
                                size="icon"
                                variant="ghost"
                            >
                                <MoreHorizontal className="h-4 w-4" />
                                <span className="sr-only">Toggle menu</span>
                            </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                                <DropdownMenuLabel>Actions</DropdownMenuLabel>
                                <DropdownMenuItem onClick={() => openEditDialog(expense)}>Edit</DropdownMenuItem>
                                <DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(expense)}>Delete</DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
        <CardFooter>
          <div className="text-xs text-muted-foreground">
            Showing <strong>1-{filteredExpenses.length}</strong> of <strong>{allExpenses.length}</strong> transactions
          </div>
        </CardFooter>
      </Card>
    </div>
  )
}
