import React, { useState, useMemo } from 'react';
import { useTable, FilterDropdown } from '@refinedev/antd';
import { Table, Button, Space, Tooltip, Input, Typography } from 'antd';
import {
  EditOutlined,
  EyeOutlined,
  SearchOutlined,
  CodeOutlined,
} from '@ant-design/icons';
import {
  getDefaultFilter,
  type HttpError,
  useGetIdentity,
} from '@refinedev/core';
import type { Resource } from './types';
import { EditModal } from './Components/EditModal';
import { CreateModal } from './Components/CreateModal';
import { ResourceDetailDrawer } from './Components/ResourceDetailDrawer';
import { SqlModal, generateResourceSql } from '../../components/SqlModal';

// System resources that cannot be modified (use Set for O(1) lookup performance)
// System resources that cannot be modified
export const PROTECTED_RESOURCES = [
  'pageresource',
  'resource',
  'page',
  'rolepages',
  'role',
  'roleresource',
];

export const ResourceManagementListPage: React.FC = () => {
  const { data: identity } = useGetIdentity<any>();
  const { tableProps, filters, tableQueryResult } = useTable<
    Resource,
    HttpError,
    Partial<Resource>
  >({
    resource: 'resource',
    syncWithLocation: false, // Disable URL sync to keep URL clean
    pagination: {
      pageSize: 20,
    },
    onSearch: (values: Partial<Resource>) => {
      return Object.entries(values)
        .filter(([, value]) => value !== undefined && value !== '')
        .map(([field, value]) => ({
          field,
          operator: 'contains' as const,
          value: value || '',
        }));
    },
    filters: {
      initial: [
        { field: 'code', operator: 'contains', value: '' },
        { field: 'name', operator: 'contains', value: '' },
      ],
      defaultBehavior: 'merge',
    },
    sorters: {},
  });

  const [showModal, setShowModal] = useState<{
    type: 'edit' | 'create' | null;
    id: number | null;
  }>({
    type: null,
    id: null,
  });

  const [drawerResource, setDrawerResource] = useState<Resource | null>(null);

  const [sqlModal, setSqlModal] = useState<{
    open: boolean;
    title: string;
    sql: string;
  }>({ open: false, title: '', sql: '' });

  const handleShowSql = (record: Resource) => {
    const operator = {
      authorId: identity?.userid,
      authorName: identity?.username,
    };
    const sql = generateResourceSql(record, operator);
    setSqlModal({ open: true, title: `SQL — Resource: ${record.code}`, sql });
  };

  // fix for ant design filter dropdown contains operator
  filters.map((filter) => {
    if (filter.operator === 'contains' && Array.isArray(filter.value)) {
      filter.value = filter.value.join(',');
    }
  });

  // Pre-compute protected resources map for better performance
  // This avoids repeated toLowerCase() and includes() calls during rendering
  const protectedResourcesMap = useMemo(() => {
    const dataSource = tableProps.dataSource || [];
    const map = new Map<number, boolean>();
    dataSource.forEach((record: Resource) => {
      map.set(
        record.id,
        PROTECTED_RESOURCES.includes(record.code.toLowerCase()),
      );
    });
    return map;
  }, [tableProps.dataSource]);

  const handleModalClose = () => {
    setShowModal({ type: null, id: null });
  };

  const handleModalSuccess = () => {
    handleModalClose();
    tableQueryResult?.refetch();
  };

  return (
    <div>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 16,
        }}
      >
        <Typography.Title level={4} style={{ margin: 0 }}>
          Resource mgnts
        </Typography.Title>
        <Button
          type="primary"
          onClick={() =>
            setShowModal({
              type: 'create',
              id: null,
            })
          }
        >
          Create Resource
        </Button>
      </div>
      <Table {...tableProps} rowKey="id">
        <Table.Column
          dataIndex="code"
          title="Code"
          sorter={(a: Resource, b: Resource) => a.code.localeCompare(b.code)}
          defaultFilteredValue={getDefaultFilter('code', filters, 'contains')}
          filterDropdown={(props) => (
            <FilterDropdown
              {...props}
              clearFilters={() => {
                props.setSelectedKeys([]);
                props.confirm?.();
              }}
            >
              <Input placeholder="Search Code" />
            </FilterDropdown>
          )}
          filterIcon={<SearchOutlined />}
        />
        <Table.Column
          dataIndex="name"
          title="Name"
          sorter={(a: Resource, b: Resource) => a.name.localeCompare(b.name)}
          defaultFilteredValue={getDefaultFilter('name', filters, 'contains')}
          filterDropdown={(props) => (
            <FilterDropdown
              {...props}
              clearFilters={() => {
                props.setSelectedKeys([]);
                props.confirm?.();
              }}
            >
              <Input placeholder="Search Name" />
            </FilterDropdown>
          )}
          filterIcon={<SearchOutlined />}
        />
        <Table.Column dataIndex="description" title="Description" />
        <Table.Column
          dataIndex="creator"
          title="Creator"
          sorter={(a: Resource, b: Resource) =>
            (a.creator || '').localeCompare(b.creator || '')
          }
        />
        <Table.Column
          title="Actions"
          render={(_, record: Resource) => {
            const isProtected = protectedResourcesMap.get(record.id) || false;
            return (
              <Space>
                <Tooltip title="View details">
                  <Button
                    type="default"
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={() => setDrawerResource(record)}
                  />
                </Tooltip>
                <Tooltip
                  title={
                    isProtected
                      ? 'This is a system resource and cannot be modified'
                      : 'Edit'
                  }
                >
                  <Button
                    type="default"
                    size="small"
                    icon={<EditOutlined />}
                    disabled={isProtected}
                    onClick={() =>
                      setShowModal({ type: 'edit', id: record.id })
                    }
                  />
                </Tooltip>
                <Tooltip title="Generate SQL">
                  <Button
                    type="default"
                    size="small"
                    icon={<CodeOutlined />}
                    onClick={() => handleShowSql(record)}
                  />
                </Tooltip>
              </Space>
            );
          }}
        />
      </Table>
      {showModal.type === 'edit' && showModal.id && (
        <EditModal
          id={showModal.id}
          onClose={handleModalClose}
          onSuccess={handleModalSuccess}
        />
      )}
      {showModal.type === 'create' && (
        <CreateModal
          onClose={handleModalClose}
          onSuccess={handleModalSuccess}
        />
      )}
      {drawerResource && (
        <ResourceDetailDrawer
          resource={drawerResource}
          open={!!drawerResource}
          onClose={() => setDrawerResource(null)}
        />
      )}
      <SqlModal
        open={sqlModal.open}
        onClose={() => setSqlModal({ open: false, title: '', sql: '' })}
        title={sqlModal.title}
        sql={sqlModal.sql}
      />
    </div>
  );
};
