
'use client';

import { useState } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult, Seller } from '@/lib/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { MoreVertical, PlusCircle, ToggleLeft, ToggleRight } from 'lucide-react';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { mockSellers } from '@/lib/data';
import { format } from 'date-fns';

type DeductionRule = {
  id: string;
  name: string;
  type: 'Percentage' | 'Fixed Amount';
  value: string;
  status: 'Active' | 'Inactive';
};

type AppliedDeduction = {
  id: string;
  date: string;
  merchant: Seller;
  shipmentId: string;
  deductionType: string;
  amount: number;
  reason: string;
};

const mockRules: DeductionRule[] = [
  { id: 'rule-1', name: 'Fuel Surcharge', type: 'Percentage', value: '2.5%', status: 'Active' },
  { id: 'rule-2', name: 'Late Delivery Penalty', type: 'Fixed Amount', value: 'PKR 50.00', status: 'Active' },
  { id: 'rule-3', name: 'Weight Discrepancy Fee', type: 'Fixed Amount', value: 'PKR 100.00', status: 'Active' },
  { id: 'rule-4', name: 'Return Processing Fee', type: 'Fixed Amount', value: 'PKR 75.00', status: 'Inactive' },
];

const mockAppliedDeductions: AppliedDeduction[] = [
  { id: 'ad-1', date: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(), merchant: mockSellers[0], shipmentId: 'PCL162822', deductionType: 'Late Delivery Penalty', amount: 50.00, reason: 'Delivery exceeded SLA by 2 days' },
  { id: 'ad-2', date: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(), merchant: mockSellers[1], shipmentId: 'PCL162819', deductionType: 'Fuel Surcharge', amount: 62.50, reason: 'Applied on COD amount of 2500' },
  { id: 'ad-3', date: new Date(Date.now() - 4 * 24 * 60 * 60 * 1000).toISOString(), merchant: mockSellers[0], shipmentId: 'PCL162820', deductionType: 'Weight Discrepancy Fee', amount: 100.00, reason: 'Declared weight 0.5kg, actual 1.2kg' },
];

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

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="finance">
        <div className="flex flex-col gap-8">
          <Card>
            <CardHeader>
              <CardTitle>Deductions Management</CardTitle>
              <CardDescription>
                Configure and track all service charges, penalties, and other deductions applied to merchant settlements.
              </CardDescription>
            </CardHeader>
            <CardContent>
                <Tabs defaultValue="rules">
                    <TabsList>
                        <TabsTrigger value="rules">Deduction Rules</TabsTrigger>
                        <TabsTrigger value="log">Applied Deductions Log</TabsTrigger>
                    </TabsList>
                    <TabsContent value="rules" className="mt-4">
                        <Card>
                            <CardHeader className="flex flex-row items-center">
                                <div className="grid gap-2 flex-1">
                                    <CardTitle className="text-lg">Deduction Rules</CardTitle>
                                    <CardDescription>
                                    Define the rules for automatic deductions.
                                    </CardDescription>
                                </div>
                                <Button size="sm" className="ml-auto gap-1">
                                    <PlusCircle className="h-4 w-4" />
                                    Add New Rule
                                </Button>
                            </CardHeader>
                            <CardContent>
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Rule Name</TableHead>
                                            <TableHead>Type</TableHead>
                                            <TableHead>Value / Rate</TableHead>
                                            <TableHead>Status</TableHead>
                                            <TableHead className="text-right">Actions</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {mockRules.map(rule => (
                                            <TableRow key={rule.id}>
                                                <TableCell className="font-medium">{rule.name}</TableCell>
                                                <TableCell>{rule.type}</TableCell>
                                                <TableCell>{rule.value}</TableCell>
                                                <TableCell>
                                                    <Badge variant={rule.status === 'Active' ? 'default' : 'secondary'} className={rule.status === 'Active' ? 'bg-green-100 text-green-800' : ''}>
                                                        {rule.status}
                                                    </Badge>
                                                </TableCell>
                                                <TableCell className="text-right">
                                                    <DropdownMenu>
                                                        <DropdownMenuTrigger asChild>
                                                            <Button size="icon" variant="ghost">
                                                                <MoreVertical className="h-4 w-4" />
                                                            </Button>
                                                        </DropdownMenuTrigger>
                                                        <DropdownMenuContent>
                                                            <DropdownMenuItem>Edit</DropdownMenuItem>
                                                            <DropdownMenuItem>
                                                                {rule.status === 'Active' ? <ToggleLeft className="mr-2 h-4 w-4"/> : <ToggleRight className="mr-2 h-4 w-4"/>}
                                                                {rule.status === 'Active' ? 'Disable' : 'Enable'}
                                                            </DropdownMenuItem>
                                                        </DropdownMenuContent>
                                                    </DropdownMenu>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </CardContent>
                        </Card>
                    </TabsContent>
                    <TabsContent value="log" className="mt-4">
                         <Card>
                            <CardHeader>
                                <CardTitle className="text-lg">Applied Deductions Log</CardTitle>
                                <CardDescription>
                                A log of all deductions applied to merchant settlements.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Date</TableHead>
                                            <TableHead>Merchant</TableHead>
                                            <TableHead>Shipment ID</TableHead>
                                            <TableHead>Deduction Type</TableHead>
                                            <TableHead>Reason</TableHead>
                                            <TableHead className="text-right">Amount (PKR)</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {mockAppliedDeductions.map(deduction => (
                                            <TableRow key={deduction.id}>
                                                <TableCell>{format(new Date(deduction.date), 'dd MMM, yyyy')}</TableCell>
                                                <TableCell>{deduction.merchant.name}</TableCell>
                                                <TableCell>{deduction.shipmentId}</TableCell>
                                                <TableCell>{deduction.deductionType}</TableCell>
                                                <TableCell>{deduction.reason}</TableCell>
                                                <TableCell className="text-right font-medium text-red-600">-{deduction.amount.toFixed(2)}</TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </CardContent>
                        </Card>
                    </TabsContent>
                </Tabs>
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
