
'use client';

import { useState, useMemo } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult } from '@/lib/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, TableFooter } from '@/components/ui/table';
import { DatePickerWithRange } from '@/components/ui/date-range-picker';
import { type DateRange } from 'react-day-picker';
import { addDays, format } from 'date-fns';
import { Button } from '@/components/ui/button';
import { Download } from 'lucide-react';

type LedgerEntry = {
    date: string;
    description: string;
    debit: number;
    credit: number;
};

const mockLedgerData: Record<string, LedgerEntry[]> = {
  '1010': [ // Cash and Bank
    { date: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(), description: 'Opening Balance', debit: 500000, credit: 0 },
    { date: new Date(Date.now() - 4 * 24 * 60 * 60 * 1000).toISOString(), description: 'COD Deposit - LHR', debit: 120000, credit: 0 },
    { date: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(), description: 'Salary Payments', debit: 0, credit: 250000 },
    { date: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(), description: 'COD Deposit - KHI', debit: 85000, credit: 0 },
    { date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(), description: 'Vendor Payment - Fuel', debit: 0, credit: 50000 },
  ],
  '4010': [ // Delivery Charges Income
      { date: new Date(Date.now() - 4 * 24 * 60 * 60 * 1000).toISOString(), description: 'Revenue Batch 001', debit: 0, credit: 22000 },
      { date: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(), description: 'Revenue Batch 002', debit: 0, credit: 18500 },
  ]
};

const accounts = [
  { code: '1010', name: 'Cash and Bank' },
  { code: '1020', name: 'Accounts Receivable - Merchants' },
  { code: '4010', name: 'Delivery Charges Income' },
  { code: '5010', name: 'Salaries and Wages' },
];

export default function LedgerPage() {
  const [selectedAccount, setSelectedAccount] = useState('1010');
  const [dateRange, setDateRange] = useState<DateRange | undefined>({
    from: addDays(new Date(), -30),
    to: new Date(),
  });

  const { entries, totalDebit, totalCredit, balance } = useMemo(() => {
    const accountEntries = mockLedgerData[selectedAccount] || [];
    const filtered = accountEntries.filter(e => {
        const entryDate = new Date(e.date);
        return dateRange?.from && dateRange?.to && entryDate >= dateRange.from && entryDate <= dateRange.to;
    });

    let runningBalance = 0;
    const entriesWithBalance = filtered.map(e => {
        runningBalance += e.debit - e.credit;
        return { ...e, balance: runningBalance };
    });

    const totalDebit = filtered.reduce((sum, e) => sum + e.debit, 0);
    const totalCredit = filtered.reduce((sum, e) => sum + e.credit, 0);

    return {
        entries: entriesWithBalance,
        totalDebit,
        totalCredit,
        balance: totalDebit - totalCredit
    };
  }, [selectedAccount, dateRange]);


  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={() => {}} userRole="finance">
        <div className="flex flex-col gap-8">
          <Card>
            <CardHeader>
              <CardTitle>General Ledger</CardTitle>
              <CardDescription>
                View a detailed record of transactions for any financial account.
              </CardDescription>
            </CardHeader>
            <CardContent>
                <div className="p-4 border rounded-lg bg-muted/50 mb-6">
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 items-end">
                        <div>
                            <label className="text-sm font-medium">Select Account</label>
                            <Select value={selectedAccount} onValueChange={setSelectedAccount}>
                                <SelectTrigger><SelectValue /></SelectTrigger>
                                <SelectContent>
                                    {accounts.map(acc => (
                                        <SelectItem key={acc.code} value={acc.code}>{acc.code} - {acc.name}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                        <div>
                            <label className="text-sm font-medium">Date Range</label>
                            <DatePickerWithRange date={dateRange} setDate={setDateRange} />
                        </div>
                         <Button variant="outline"><Download className="mr-2 h-4 w-4" /> Export</Button>
                    </div>
                </div>

                <h3 className="text-lg font-semibold mb-4">
                  Ledger for: <span className="text-primary">{accounts.find(a => a.code === selectedAccount)?.name}</span>
                </h3>

                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead className="w-1/4">Date</TableHead>
                            <TableHead className="w-2/4">Description</TableHead>
                            <TableHead className="w-1/4 text-right">Debit (PKR)</TableHead>
                            <TableHead className="w-1/4 text-right">Credit (PKR)</TableHead>
                            <TableHead className="w-1/4 text-right">Balance (PKR)</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {entries.map((entry, index) => (
                            <TableRow key={index}>
                                <TableCell>{format(new Date(entry.date), 'dd MMM, yyyy')}</TableCell>
                                <TableCell>{entry.description}</TableCell>
                                <TableCell className="text-right font-mono">{entry.debit > 0 ? entry.debit.toLocaleString() : '-'}</TableCell>
                                <TableCell className="text-right font-mono">{entry.credit > 0 ? entry.credit.toLocaleString() : '-'}</TableCell>
                                <TableCell className="text-right font-mono">{entry.balance.toLocaleString()}</TableCell>
                            </TableRow>
                        ))}
                         {entries.length === 0 && (
                            <TableRow>
                                <TableCell colSpan={5} className="text-center h-24">No entries for selected period.</TableCell>
                            </TableRow>
                        )}
                    </TableBody>
                    <TableFooter>
                        <TableRow>
                            <TableCell colSpan={2} className="font-bold">Total</TableCell>
                            <TableCell className="text-right font-bold font-mono">{totalDebit.toLocaleString()}</TableCell>
                            <TableCell className="text-right font-bold font-mono">{totalCredit.toLocaleString()}</TableCell>
                            <TableCell className="text-right font-bold font-mono">{balance.toLocaleString()}</TableCell>
                        </TableRow>
                    </TableFooter>
                </Table>
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
