
'use client';

import { useState } 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 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

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

const incomeAccounts = [
    { code: '4010', name: 'Delivery Charges Income' },
    { code: '4020', name: 'COD Handling Fees' },
    { code: '1020', name: 'Accounts Receivable - Merchants' },
];

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

  const totalAmount = entries.reduce((sum, entry) => sum + entry.credit, 0);

  const handleAddEntry = () => {
    setEntries([...entries, { id: `entry-${Date.now()}`, account: '', description: '', 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 (!receivedFrom || entries.length === 0 || totalAmount === 0) {
        toast({ variant: 'destructive', title: 'Error', description: 'Please fill all required fields and add at least one entry.' });
        return;
    }
    toast({ title: 'Success', description: 'Cash Receipt Voucher saved successfully!' });
  };
  
  const handleReset = () => {
    setDate(new Date());
    setReceivedFrom('');
    setEntries([]);
  }

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="finance">
        <div className="flex flex-col gap-8">
          <Card>
            <CardHeader>
              <CardTitle>Cash Receipt Voucher</CardTitle>
              <CardDescription>
                Create a voucher for payments received in cash.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <Label>Voucher No.</Label>
                        <Input readOnly value="CRV-AUTO-00345" className="bg-muted/50" />
                    </div>
                     <div>
                        <Label>Date</Label>
                        <DatePicker date={date} setDate={setDate} />
                    </div>
                     <div>
                        <Label htmlFor="received-from">Received From</Label>
                        <Input id="received-from" placeholder="Enter source name" value={receivedFrom} onChange={e => setReceivedFrom(e.target.value)} />
                    </div>
                </div>

                <div>
                    <div className="flex items-center justify-between mb-2">
                        <h3 className="text-lg font-semibold">Account Entries (Credit)</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">Credit (PKR)</TableHead>
                                <TableHead className="w-[50px]"></TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {entries.length === 0 ? (
                                <TableRow>
                                    <TableCell colSpan={4} 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>
                                                {incomeAccounts.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.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={totalAmount.toLocaleString()} className="text-right font-bold bg-muted/50" />
                                </TableCell>
                                <TableCell></TableCell>
                            </TableRow>
                        </ShadTableFooter>
                    </Table>
                </div>

                 <div>
                    <Label htmlFor="remarks">Remarks</Label>
                    <Textarea id="remarks" placeholder="Add any additional notes or remarks here..." />
                </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"><Printer className="mr-2 h-4 w-4" /> Save & Print</Button>
                <Button onClick={handleSave}><Save className="mr-2 h-4 w-4" /> Save Voucher</Button>
            </CardFooter>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
