
'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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DatePickerWithRange } from '@/components/ui/date-range-picker';
import { Upload, CheckCircle, AlertTriangle, Loader2 } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import type { DateRange } from 'react-day-picker';
import { addDays, format } from 'date-fns';
import { useToast } from '@/hooks/use-toast';
import { Input } from '@/components/ui/input';

type ReconciliationTransaction = {
    id: string;
    date: string;
    description: string;
    systemAmount: number | null;
    bankAmount: number | null;
    status: 'Matched' | 'Mismatch' | 'System Only' | 'Bank Only';
};

const mockReconciliation: ReconciliationTransaction[] = [
    { id: '1', date: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(), description: 'COD Deposit - Multan Branch', systemAmount: 45500, bankAmount: 45500, status: 'Matched' },
    { id: '2', date: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(), description: 'COD Deposit - Lahore Hub', systemAmount: 88300, bankAmount: 88000, status: 'Mismatch' },
    { id: '3', date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(), description: 'COD Deposit - Karachi Central', systemAmount: 72400, bankAmount: null, status: 'System Only' },
    { id: '4', date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(), description: 'Bank Service Charges', systemAmount: null, bankAmount: -500, status: 'Bank Only' },
];


export default function FinanceBankReconciliationPage() {
  
  const handleBookingComplete = (result: BookingResult) => {};

  const [dateRange, setDateRange] = useState<DateRange | undefined>({
    from: addDays(new Date(), -30),
    to: new Date(),
  });
  const [bankAccount, setBankAccount] = useState('');
  const [statementFile, setStatementFile] = useState<File | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [report, setReport] = useState<ReconciliationTransaction[] | null>(null);
  const { toast } = useToast();
  
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
        setStatementFile(e.target.files[0]);
    }
  };

  const handleRunReconciliation = () => {
    if (!bankAccount || !dateRange?.from || !dateRange?.to || !statementFile) {
        toast({ variant: 'destructive', title: 'Missing Information', description: 'Please select an account, date range, and upload a statement.' });
        return;
    }
    setIsLoading(true);
    setTimeout(() => {
        setReport(mockReconciliation);
        setIsLoading(false);
    }, 1500);
  };
  
  const summary = report ? report.reduce((acc, tx) => {
    if (tx.status === 'Matched') {
        acc.matched += tx.systemAmount!;
    } else {
        acc.unmatched += (tx.systemAmount || 0) - (tx.bankAmount || 0);
    }
    acc.systemTotal += tx.systemAmount || 0;
    acc.bankTotal += tx.bankAmount || 0;
    return acc;
  }, { systemTotal: 0, bankTotal: 0, matched: 0, unmatched: 0 }) : null;

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="finance">
        <div className="flex flex-col gap-8">
          <Card>
            <CardHeader>
              <CardTitle>Bank Reconciliation Report</CardTitle>
              <CardDescription>
                Upload a bank statement to reconcile it against system records for a selected period.
              </CardDescription>
            </CardHeader>
            <CardContent>
               <div className="p-4 border rounded-lg bg-muted/50 space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 items-end">
                        <div>
                            <label className="text-sm font-medium">Bank Account</label>
                            <Select value={bankAccount} onValueChange={setBankAccount}>
                                <SelectTrigger>
                                    <SelectValue placeholder="Select an account" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="hbl-1">HBL - ****1234</SelectItem>
                                    <SelectItem value="mcb-1">MCB - ****5678</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                        <div>
                            <label className="text-sm font-medium">Date Range</label>
                            <DatePickerWithRange date={dateRange} setDate={setDateRange} />
                        </div>
                        <div className="lg:col-span-1">
                            <label className="text-sm font-medium">Bank Statement</label>
                            <Input type="file" onChange={handleFileChange} accept=".csv,.xlsx,.ofx" />
                        </div>
                        <Button onClick={handleRunReconciliation} disabled={isLoading} className="w-full">
                            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            Run Reconciliation
                        </Button>
                    </div>
                </div>
            </CardContent>
          </Card>
           {report && summary && (
                <Card className="animate-in fade-in-50">
                    <CardHeader>
                        <CardTitle>Reconciliation Result</CardTitle>
                        <CardDescription>
                            Comparison between system records and bank statement for {bankAccount} from {format(dateRange?.from!, 'PPP')} to {format(dateRange?.to!, 'PPP')}.
                        </CardDescription>
                    </CardHeader>
                    <CardContent>
                        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                            <Card>
                                <CardHeader className="p-4">
                                <CardDescription>System Deposits</CardDescription>
                                <CardTitle>PKR {summary.systemTotal.toLocaleString()}</CardTitle>
                                </CardHeader>
                            </Card>
                            <Card>
                                <CardHeader className="p-4">
                                <CardDescription>Bank Statement Deposits</CardDescription>
                                <CardTitle>PKR {summary.bankTotal.toLocaleString()}</CardTitle>
                                </CardHeader>
                            </Card>
                            <Card className="border-green-500">
                                <CardHeader className="p-4">
                                <CardDescription>Matched Amount</CardDescription>
                                <CardTitle>PKR {summary.matched.toLocaleString()}</CardTitle>
                                </CardHeader>
                            </Card>
                             <Card className="border-red-500">
                                <CardHeader className="p-4">
                                <CardDescription>Discrepancies</CardDescription>
                                <CardTitle>PKR {summary.unmatched.toLocaleString()}</CardTitle>
                                </CardHeader>
                            </Card>
                        </div>
                        
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Date</TableHead>
                                    <TableHead>Description</TableHead>
                                    <TableHead>System Amount</TableHead>
                                    <TableHead>Bank Amount</TableHead>
                                    <TableHead>Status</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {report.map(tx => (
                                    <TableRow key={tx.id}>
                                        <TableCell>{format(new Date(tx.date), 'dd MMM, yyyy')}</TableCell>
                                        <TableCell>{tx.description}</TableCell>
                                        <TableCell>
                                            {tx.systemAmount !== null ? `PKR ${tx.systemAmount.toLocaleString()}` : '—'}
                                        </TableCell>
                                        <TableCell>
                                            {tx.bankAmount !== null ? `PKR ${tx.bankAmount.toLocaleString()}` : '—'}
                                        </TableCell>
                                        <TableCell>
                                            <Badge variant={
                                                tx.status === 'Matched' ? 'default' :
                                                tx.status === 'Mismatch' ? 'destructive' : 'secondary'
                                            } className={tx.status === 'Matched' ? 'bg-green-100 text-green-800' : ''}>
                                                {tx.status}
                                            </Badge>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </CardContent>
                     <CardFooter>
                        <Button variant="outline">Resolve Discrepancies</Button>
                    </CardFooter>
                </Card>
            )}
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
