
'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, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { DatePicker } from '@/components/ui/date-picker';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, TableFooter as ShadTableFooter } from '@/components/ui/table';
import { Textarea } from '@/components/ui/textarea';
import { Save, Printer, RefreshCw, PlusCircle, Trash2, AlertCircle } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

type AccountEntry = {
  id: string;
  account: string;
  description: string;
  debit: number;
  credit: number;
};

const allAccounts = [
    { code: '1010', name: 'Cash and Bank' },
    { code: '1020', name: 'Accounts Receivable' },
    { code: '2010', name: 'Accounts Payable' },
    { code: '4010', name: 'Delivery Income' },
    { code: '5010', name: 'Salaries Expense' },
    { code: '5020', name: 'Fuel Expense' },
];

export default function JournalVoucherPage() {
  
  const handleBookingComplete = (result: BookingResult) => {};
  const [date, setDate] = useState<Date | undefined>(new Date());
  const [remarks, setRemarks] = useState('');
  const [entries, setEntries] = useState<AccountEntry[]>([]);
  const { toast } = useToast();

  const { totalDebit, totalCredit, isBalanced } = useMemo(() => {
    const debit = entries.reduce((sum, entry) => sum + entry.debit, 0);
    const credit = entries.reduce((sum, entry) => sum + entry.credit, 0);
    return {
        totalDebit: debit,
        totalCredit: credit,
        isBalanced: debit === credit && debit > 0,
    }
  }, [entries]);

  const handleAddEntry = () => {
    setEntries([...entries, { id: `entry-${Date.now()}`, account: '', description: '', debit: 0, credit: 0 }]);
  };

  const handleEntryChange = (id: string, field: keyof AccountEntry, value: string | number) => {
    setEntries(entries.map(entry => entry.id === id ? { ...entry, [field]: value } : entry));
  };
  
  const handleRemoveEntry = (id: string) => {
    setEntries(entries.filter(entry => entry.id !== id));
  };

  const handleSave = () => {
    if (!isBalanced) {
        toast({ variant: 'destructive', title: 'Unbalanced Entry', description: 'Total debits must equal total credits and cannot be zero.' });
        return;
    }
    toast({ title: 'Success', description: 'Journal Voucher saved successfully!' });
  };
  
  const handleReset = () => {
    setDate(new Date());
    setRemarks('');
    setEntries([]);
  }

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="finance">
        <div className="flex flex-col gap-8">
          <Card>
            <CardHeader>
              <CardTitle>Journal Voucher</CardTitle>
              <CardDescription>
                Create a voucher for non-cash and non-bank transactions.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <div>
                        <Label>Voucher No.</Label>
                        <Input readOnly value="JV-AUTO-00057" className="bg-muted/50" />
                    </div>
                     <div>
                        <Label>Date</Label>
                        <DatePicker date={date} setDate={setDate} />
                    </div>
                </div>

                <div>
                    <div className="flex items-center justify-between mb-2">
                        <h3 className="text-lg font-semibold">Account Entries</h3>
                        <Button size="sm" variant="outline" onClick={handleAddEntry}>
                            <PlusCircle className="mr-2 h-4 w-4" /> Add Row
                        </Button>
                    </div>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead className="w-2/5">Account</TableHead>
                                <TableHead className="w-2/5">Description</TableHead>
                                <TableHead className="w-1/5 text-right">Debit</TableHead>
                                <TableHead className="w-1/5 text-right">Credit</TableHead>
                                <TableHead className="w-[50px]"></TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {entries.length === 0 ? (
                                <TableRow>
                                    <TableCell colSpan={5} className="text-center h-24">
                                        Click "Add Row" to start.
                                    </TableCell>
                                </TableRow>
                            ) : entries.map(entry => (
                                <TableRow key={entry.id}>
                                    <TableCell>
                                        <Select 
                                            value={entry.account} 
                                            onValueChange={(val) => handleEntryChange(entry.id, 'account', val)}
                                        >
                                            <SelectTrigger><SelectValue placeholder="Select account..." /></SelectTrigger>
                                            <SelectContent>
                                                {allAccounts.map(acc => <SelectItem key={acc.code} value={acc.code}>{acc.code} - {acc.name}</SelectItem>)}
                                            </SelectContent>
                                        </Select>
                                    </TableCell>
                                    <TableCell>
                                        <Input 
                                            placeholder="Enter description..." 
                                            value={entry.description}
                                            onChange={(e) => handleEntryChange(entry.id, 'description', e.target.value)}
                                        />
                                    </TableCell>
                                    <TableCell>
                                        <Input 
                                            type="number"
                                            className="text-right"
                                            value={entry.debit}
                                            onChange={(e) => handleEntryChange(entry.id, 'debit', e.target.valueAsNumber)}
                                        />
                                    </TableCell>
                                    <TableCell>
                                        <Input 
                                            type="number"
                                            className="text-right"
                                            value={entry.credit}
                                            onChange={(e) => handleEntryChange(entry.id, 'credit', e.target.valueAsNumber)}
                                        />
                                    </TableCell>
                                    <TableCell>
                                         <Button variant="ghost" size="icon" onClick={() => handleRemoveEntry(entry.id)}>
                                            <Trash2 className="h-4 w-4 text-red-500" />
                                        </Button>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                        <ShadTableFooter>
                            <TableRow>
                                <TableCell colSpan={2} className="font-bold text-right">Total</TableCell>
                                <TableCell className="text-right font-bold">
                                    <Input readOnly value={totalDebit.toLocaleString()} className="text-right font-bold bg-muted/50" />
                                </TableCell>
                                 <TableCell className="text-right font-bold">
                                    <Input readOnly value={totalCredit.toLocaleString()} className="text-right font-bold bg-muted/50" />
                                </TableCell>
                                <TableCell></TableCell>
                            </TableRow>
                        </ShadTableFooter>
                    </Table>
                    {!isBalanced && entries.length > 0 && (
                        <div className="text-red-600 text-sm mt-2 flex items-center gap-2">
                           <AlertCircle className="h-4 w-4" /> Total debits must equal total credits.
                        </div>
                    )}
                </div>

                 <div>
                    <Label htmlFor="remarks">Narration / Remarks</Label>
                    <Textarea id="remarks" placeholder="e.g., To record depreciation for the month" value={remarks} onChange={(e) => setRemarks(e.target.value)} />
                </div>
            </CardContent>
            <CardFooter className="justify-end gap-2 border-t pt-6">
                <Button variant="outline" onClick={handleReset}><RefreshCw className="mr-2 h-4 w-4" /> Reset</Button>
                <Button variant="secondary" disabled={!isBalanced}><Printer className="mr-2 h-4 w-4" /> Save & Print</Button>
                <Button onClick={handleSave} disabled={!isBalanced}><Save className="mr-2 h-4 w-4" /> Save Voucher</Button>
            </CardFooter>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
