import React from 'react';
import { useModalForm } from '@refinedev/antd';
import { type HttpError, useList } from '@refinedev/core';
import { Checkbox, Form, Input, Modal, Select } from 'antd';
import type { Resource } from '../types';
import { ResourceSelect } from '../queries';
import { PROTECTED_RESOURCES } from '../list';

type ResourceFormFields = Partial<Resource>;

type Props = {
  action: 'create' | 'edit';
  id?: number;
  onMutationSuccess?: () => void;
  onCancel?: () => void;
};

// Pattern to detect special characters - only allows letters, numbers, and underscores
const SPECIAL_CHAR_PATTERN = /[^a-zA-Z0-9_]/;

export const ResourceFormModal: React.FC<Props> = ({
  action,
  id,
  onCancel,
  onMutationSuccess,
}) => {
  const { formProps, modalProps, close } = useModalForm<
    Resource,
    HttpError,
    ResourceFormFields
  >({
    resource: 'resource',
    action,
    id,
    defaultVisible: true,
    onMutationSuccess: () => {
      onMutationSuccess?.();
    },
    meta: {
      select: ResourceSelect,
    },
  });

  // Fetch all resources for code duplication check
  const { data: resourcesData } = useList<Resource>({
    resource: 'resource',
    pagination: {
      mode: 'off',
    },
  });

  // Check if current resource is protected (for edit mode)
  const currentResource = resourcesData?.data?.find((r) => r.id === id);
  const isProtectedResource = currentResource
    ? PROTECTED_RESOURCES.includes(currentResource.code.toLowerCase())
    : false;

  return (
    <Modal
      {...modalProps}
      width={560}
      onCancel={() => {
        if (onCancel) {
          onCancel();
          return;
        }
        close();
      }}
      title={action === 'create' ? 'Create Resource' : 'Edit Resource'}
    >
      <Form {...formProps} layout="vertical">
        {isProtectedResource && (
          <div
            style={{
              padding: '12px',
              marginBottom: '16px',
              backgroundColor: '#fff7e6',
              border: '1px solid #ffd591',
              borderRadius: '4px',
              color: '#d46b08',
            }}
          >
            ⚠️ This is a system resource and cannot be modified.
          </div>
        )}
        <Form.Item
          rules={[
            { required: true, message: 'Resource Code is required' },
            {
              pattern: /^[a-zA-Z0-9_]+$/,
              message:
                'Resource Code can only contain letters, numbers and underscores',
            },
            {
              validator: async (_, value) => {
                if (!value) {
                  return Promise.resolve();
                }

                const existingResources = resourcesData?.data || [];
                const trimmedValue = value.trim();

                // In edit mode, if value hasn't changed, skip validation
                if (
                  action === 'edit' &&
                  currentResource &&
                  trimmedValue === currentResource.code
                ) {
                  return Promise.resolve();
                }

                // Check if trying to use a protected resource code
                if (PROTECTED_RESOURCES.includes(trimmedValue.toLowerCase())) {
                  return Promise.reject(
                    new Error(
                      'This resource code is reserved for system use and cannot be used.',
                    ),
                  );
                }

                // Check if resource code already exists (case-insensitive)
                const isDuplicate = existingResources.some((resource) => {
                  // Skip current resource when editing
                  if (action === 'edit' && resource.id === id) {
                    return false;
                  }
                  return (
                    resource.code.toLowerCase() === trimmedValue.toLowerCase()
                  );
                });

                if (isDuplicate) {
                  return Promise.reject(
                    new Error(
                      'Resource code already exists. Please use a different code.',
                    ),
                  );
                }

                return Promise.resolve();
              },
            },
          ]}
          name="code"
          label="Resource Code"
        >
          <Input
            placeholder="Enter resource code (e.g., networkincidents, pageresources)"
            disabled={isProtectedResource || action === 'edit'}
          />
        </Form.Item>

        <Form.Item
          rules={[
            { required: true, message: 'Resource name is required' },
            {
              validator: (_, value) => {
                if (!value || !SPECIAL_CHAR_PATTERN.test(value)) {
                  return Promise.resolve();
                }
                return Promise.reject(
                  new Error(
                    'Special characters are not allowed in resource name.',
                  ),
                );
              },
            },
            {
              validator: async (_, value) => {
                if (!value) {
                  return Promise.resolve();
                }

                const existingResources = resourcesData?.data || [];
                const trimmedValue = value.trim();

                // In edit mode, if value hasn't changed, skip validation
                if (
                  action === 'edit' &&
                  currentResource &&
                  trimmedValue === currentResource.name
                ) {
                  return Promise.resolve();
                }

                // Check if resource name already exists (case-insensitive) - warning only
                const isDuplicate = existingResources.some((resource) => {
                  // Skip current resource when editing
                  if (action === 'edit' && resource.id === id) {
                    return false;
                  }
                  return (
                    resource.name.toLowerCase() === trimmedValue.toLowerCase()
                  );
                });

                if (isDuplicate) {
                  return Promise.reject(
                    new Error(
                      "⚠️ Warning: Resource name already exists. It's recommended to use a different name.",
                    ),
                  );
                }

                return Promise.resolve();
              },
            },
          ]}
          name="name"
          label="Resource Name"
        >
          <Input
            placeholder="Enter resource name (e.g., User Read Permission)"
            disabled={isProtectedResource}
          />
        </Form.Item>
        <Form.Item name="isCommonResource" valuePropName="checked">
          <Checkbox>Is Common Resource</Checkbox>
        </Form.Item>
        <Form.Item name="description" label="Description">
          <Input.TextArea
            rows={4}
            placeholder="Enter resource description"
            disabled={isProtectedResource}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};
