'use client';

import {useState} from 'react';
import {proportional} from '@astryxdesign/core/Table';
import {ResponsiveTable} from '@/shared/components/patterns/ResponsiveTable';
import type {TableColumn} from '@astryxdesign/core/Table';
import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';
import {Badge} from '@astryxdesign/core/Badge';
import {Button} from '@astryxdesign/core/Button';
import {useToast} from '@astryxdesign/core/Toast';
import {StaticPanel} from '@/shared/components/patterns/PanelCard';

export interface PermissionRow extends Record<string, unknown> {
  module: string;
  description: string;
  Owner: boolean;
  Manager: boolean;
  Cashier: boolean;
  Marketing: boolean;
  Support: boolean;
}

const INITIAL_MATRIX: PermissionRow[] = [
  {
    module: 'Dashboard & Analytics',
    description: 'View sales timeseries, footfall, conversion trends and KPIs',
    Owner: true,
    Manager: true,
    Cashier: false,
    Marketing: true,
    Support: false,
  },
  {
    module: 'Store Management',
    description: 'Add, edit, disable stores and change operating hours',
    Owner: true,
    Manager: true,
    Cashier: false,
    Marketing: false,
    Support: false,
  },
  {
    module: 'Staff Directory',
    description: 'Manage staff rosters, assign stores, reset passwords',
    Owner: true,
    Manager: true,
    Cashier: false,
    Marketing: false,
    Support: true,
  },
  {
    module: 'Rewards & LYTs',
    description: 'Create rewards, issue LYTs, adjust redemption rules',
    Owner: true,
    Manager: true,
    Cashier: true,
    Marketing: true,
    Support: false,
  },
  {
    module: 'Billing & Settlement',
    description: 'View invoices, change payment methods, set bank account',
    Owner: true,
    Manager: false,
    Cashier: false,
    Marketing: false,
    Support: false,
  },
  {
    module: 'API Keys & Webhooks',
    description: 'Generate developer keys and manage webhook event triggers',
    Owner: true,
    Manager: false,
    Cashier: false,
    Marketing: false,
    Support: false,
  },
  {
    module: 'Security & Audit Logs',
    description: 'Revoke active sessions, 2FA settings and login history',
    Owner: true,
    Manager: true,
    Cashier: false,
    Marketing: false,
    Support: false,
  },
];

export function RoleMatrix() {
  const toast = useToast();
  const [matrix, setMatrix] = useState<PermissionRow[]>(INITIAL_MATRIX);
  const [isSaving, setIsSaving] = useState(false);

  const togglePermission = (
    moduleName: string,
    role: 'Owner' | 'Manager' | 'Cashier' | 'Marketing' | 'Support',
  ) => {
    if (role === 'Owner') return; // Owner permissions locked
    setMatrix((prev) =>
      prev.map((item) =>
        item.module === moduleName ? {...item, [role]: !item[role]} : item,
      ),
    );
  };

  const handleSave = () => {
    setIsSaving(true);
    setTimeout(() => {
      setIsSaving(false);
      toast({body: 'Role permission matrix updated successfully'});
    }, 400);
  };

  const renderCheck = (
    row: PermissionRow,
    role: 'Owner' | 'Manager' | 'Cashier' | 'Marketing' | 'Support',
  ) => {
    const isGranted = row[role];
    return (
      <HStack hAlign="center" width="full">
        <div className="w-[108px] flex justify-center">
          <Button
            size="sm"
            variant={isGranted ? 'primary' : 'secondary'}
            isDisabled={role === 'Owner'}
            label={isGranted ? 'Granted' : 'No Access'}
            onClick={() => togglePermission(row.module, role)}
            className="w-full flex justify-center text-center"
          />
        </div>
      </HStack>
    );
  };

  const columns: TableColumn<PermissionRow>[] = [
    {
      key: 'module',
      header: 'Module / Feature Area',
      width: proportional(3),
      renderCell: (row) => (
        <VStack gap={0}>
          <Text size="sm" weight="medium">
            {row.module}
          </Text>
          <Text size="sm" color="secondary">
            {row.description}
          </Text>
        </VStack>
      ),
    },
    {
      key: 'Owner',
      header: 'Owner',
      align: 'center',
      width: proportional(1),
      renderCell: (row) => renderCheck(row, 'Owner'),
    },
    {
      key: 'Manager',
      header: 'Manager',
      align: 'center',
      width: proportional(1),
      renderCell: (row) => renderCheck(row, 'Manager'),
    },
    {
      key: 'Cashier',
      header: 'Cashier',
      align: 'center',
      width: proportional(1),
      renderCell: (row) => renderCheck(row, 'Cashier'),
    },
    {
      key: 'Marketing',
      header: 'Marketing',
      align: 'center',
      width: proportional(1),
      renderCell: (row) => renderCheck(row, 'Marketing'),
    },
    {
      key: 'Support',
      header: 'Support',
      align: 'center',
      width: proportional(1),
      renderCell: (row) => renderCheck(row, 'Support'),
    },
  ];

  return (
    <VStack gap={5}>
      <StaticPanel
        title="Role Access Control Matrix"
        subtitle="Configure granular module access levels for Owner, Manager, Cashier, Marketing and Support roles."
        actions={
          <Button
            variant="primary"
            size="sm"
            label="Save Permissions"
            isLoading={isSaving}
            onClick={handleSave}
          />
        }
      >
        <VStack gap={4}>
          <HStack gap={2} wrap="wrap">
            <Badge variant="info" label="Owner (Full Root Access)" />
            <Badge variant="neutral" label="Manager (Operational Controls)" />
            <Badge variant="neutral" label="Cashier (POS & Rewards)" />
            <Badge variant="neutral" label="Marketing (Campaigns & Analytics)" />
            <Badge variant="neutral" label="Support (Staff Roster View)" />
          </HStack>
          <ResponsiveTable
            columns={columns}
            data={matrix}
            primaryKey="module"
          />
        </VStack>
      </StaticPanel>
    </VStack>
  );
}
