
'use client';

import { useState } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult, UserRole } 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 { Checkbox } from '@/components/ui/checkbox';
import { Save, UserPlus } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

type Permission = 'viewReports' | 'runPayroll' | 'approveExpenses' | 'manageInvoices' | 'accessAudit';
type RolePermissions = Record<UserRole, Record<Permission, boolean>>;

const initialPermissions: RolePermissions = {
  'finance-manager': { viewReports: true, runPayroll: true, approveExpenses: true, manageInvoices: true, accessAudit: true },
  'finance': { viewReports: true, runPayroll: false, approveExpenses: false, manageInvoices: true, accessAudit: false },
  'support': { viewReports: false, runPayroll: false, approveExpenses: false, manageInvoices: false, accessAudit: false },
  'seller': { viewReports: false, runPayroll: false, approveExpenses: false, manageInvoices: false, accessAudit: false },
  'super-admin': { viewReports: true, runPayroll: true, approveExpenses: true, manageInvoices: true, accessAudit: true },
  'admin': { viewReports: true, runPayroll: true, approveExpenses: true, manageInvoices: true, accessAudit: true },
  'branch-operator': { viewReports: false, runPayroll: false, approveExpenses: false, manageInvoices: false, accessAudit: false },
  'marketing': { viewReports: false, runPayroll: false, approveExpenses: false, manageInvoices: false, accessAudit: false },
  'marketing-manager': { viewReports: false, runPayroll: false, approveExpenses: false, manageInvoices: false, accessAudit: false },
  'rider-manager': { viewReports: false, runPayroll: false, approveExpenses: false, manageInvoices: false, accessAudit: false },
};

const permissionLabels: Record<Permission, string> = {
  viewReports: 'View Reports',
  runPayroll: 'Run Payroll',
  approveExpenses: 'Approve Expenses',
  manageInvoices: 'Manage Invoices',
  accessAudit: 'Access Audit Logs',
};

const rolesToShow: UserRole[] = ['finance-manager', 'finance'];

export default function RoleBasedAccessPage() {
  
  const handleBookingComplete = (result: BookingResult) => {};
  const [permissions, setPermissions] = useState<RolePermissions>(initialPermissions);
  const { toast } = useToast();

  const handlePermissionChange = (role: UserRole, permission: Permission, checked: boolean) => {
    setPermissions(prev => ({
      ...prev,
      [role]: {
        ...prev[role],
        [permission]: checked,
      },
    }));
  };
  
  const handleSaveChanges = () => {
    toast({
        title: 'Permissions Updated',
        description: 'Role-based permissions have been successfully saved.',
    });
  }

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="finance">
        <div className="flex flex-col gap-8">
          <Card>
            <CardHeader className="flex flex-row items-center">
                <div className="flex-1">
                    <CardTitle>Role Based Access Control</CardTitle>
                    <CardDescription>
                    Define permissions for different user roles within the finance module.
                    </CardDescription>
                </div>
                <Button size="sm" className="ml-auto gap-1">
                    <UserPlus className="h-4 w-4" />
                    Create New Role
                </Button>
            </CardHeader>
            <CardContent>
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Role</TableHead>
                            {Object.values(permissionLabels).map(label => (
                                <TableHead key={label} className="text-center">{label}</TableHead>
                            ))}
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {rolesToShow.map(role => (
                            <TableRow key={role}>
                                <TableCell className="font-medium capitalize">{role.replace('-', ' ')}</TableCell>
                                {(Object.keys(permissionLabels) as Permission[]).map(permission => (
                                    <TableCell key={permission} className="text-center">
                                        <Checkbox
                                            checked={permissions[role]?.[permission] || false}
                                            onCheckedChange={(checked) => handlePermissionChange(role, permission, checked as boolean)}
                                        />
                                    </TableCell>
                                ))}
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
            </CardContent>
            <CardFooter className="border-t pt-6 justify-end">
                <Button onClick={handleSaveChanges}>
                    <Save className="mr-2 h-4 w-4" />
                    Save Changes
                </Button>
            </CardFooter>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}
