import React, { type PropsWithChildren, useState } from 'react';

import {
  DeleteButton,
  EditButton,
  FilterDropdown,
  List,
  ShowButton,
  useTable,
} from '@refinedev/antd';
import {
  getDefaultFilter,
  type HttpError,
  useGetIdentity,
} from '@refinedev/core';

import { PlusOutlined, CodeOutlined } from '@ant-design/icons';
import { Button, Form, Input, Select, Space, Table, Tag, Tooltip } from 'antd';
import debounce from 'lodash/debounce';

import {
  CustomAvatar,
  PaginationTotal,
  RoleStatusTag,
  Text,
} from '@/components';
import { useRoles } from '@/hooks/useRoles';
import { User } from '@/types';

import { CreateModal } from './components/create-modal';
import { EditModal } from './components/edit-modal';
import { ShowDrawer } from './components/show-drawer';
import { LIST_CONTENT_PROPS } from '@/constants/layout';
import { SqlModal, generateUserSql } from '../../components/SqlModal';

export const UserListPage: React.FC<PropsWithChildren> = ({ children }) => {
  const [form] = Form.useForm();
  const { data: identity } = useGetIdentity<any>();

  // Fetch roles from backend using custom hook
  const { roleOptions, loading: rolesLoading } = useRoles();

  // We want to always parse the query string even when syncWithLocation is
  // deactivated, for hotlinking to work properly.
  // 转换布尔字段过滤器的值（从字符串 "Yes"/"No" 转为 boolean）
  const transformBooleanFilters = (filters: any[]) => {
    return filters.map((filter) => {
      if (
        (filter.field === 'isApiKey' || filter.field === 'isActive') &&
        filter.operator === 'eq'
      ) {
        let boolValue: boolean | undefined;
        if (filter.value === 'Yes' || filter.value === 'Active') {
          boolValue = true;
        } else if (filter.value === 'No' || filter.value === 'Inactive') {
          boolValue = false;
        }
        return { ...filter, value: boolValue };
      }
      return filter;
    });
  };

  const {
    tableProps,
    searchFormProps,
    filters,
    sorters,
    tableQuery: tableQueryResult,
  } = useTable<User, HttpError, Partial<User>>({
    resource: 'user',
    pagination: {
      pageSize: 20,
    },
    onSearch: (values: Partial<User>) => {
      return Object.entries(values)
        .filter(([, value]) => value !== undefined && value !== '')
        .map(([field, value]) => ({
          field,
          operator: 'contains' as const,
          value: value || '',
        }));
    },
    // https://refine.dev/docs/ui-integrations/ant-design/components/filter-dropdown/#example
    filters: {
      initial: [
        { field: 'username', operator: 'contains', value: '' },
        { field: 'roles', operator: 'contains', value: '' },
      ],
      defaultBehavior: 'merge',
    },
    sorters: {
      initial: [],
    },
    meta: {
      transformFn: transformBooleanFilters,
    },
  });

  const onSearch = () => {
    const values = form.getFieldsValue();
    searchFormProps?.onFinish?.({
      ...values,
    });
  };

  const debouncedOnChange = debounce(onSearch, 500);

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

  // 修改modal状态类型
  const [showModal, setShowModal] = useState<{
    type: 'show' | 'edit' | 'create' | null;
    id: number | null;
  }>({
    type: null,
    id: null,
  });

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

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

  // 处理modal关闭
  const handleModalClose = () => {
    setShowModal({ type: null, id: null });
  };

  return (
    <div className="page-container">
      <List
        breadcrumb={false}
        contentProps={LIST_CONTENT_PROPS}
        headerButtons={() => {
          return (
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setShowModal({ type: 'create', id: null })}
            >
              Add User
            </Button>
          );
        }}
      >
        <Table
          {...tableProps}
          pagination={{
            ...tableProps.pagination,
            showTotal: (total) => (
              <PaginationTotal total={total} entityName="user" />
            ),
          }}
          rowKey="id"
        >
          <Table.Column
            dataIndex="userid"
            title="User ID"
            render={(_, record) => {
              return (
                <Space>
                  <CustomAvatar
                    shape="square"
                    name={record.userid || ''}
                    src={`https://rhrc.woa.com/photo/150/${record.userid}.png`}
                  />
                  <Text style={{ whiteSpace: 'nowrap' }}>{record.userid}</Text>
                </Space>
              );
            }}
          />
          <Table.Column
            dataIndex="username"
            title="User Name"
            filterDropdown={(props) => (
              <FilterDropdown
                {...props}
                clearFilters={() => {
                  props.setSelectedKeys([]);
                  props.confirm?.();
                }}
              >
                <Input />
              </FilterDropdown>
            )}
            defaultFilteredValue={getDefaultFilter(
              'username',
              filters,
              'contains',
            )}
            /*filterIcon={<SearchOutlined />}*/
          />
          <Table.Column
            dataIndex="roles"
            title="Roles"
            defaultFilteredValue={getDefaultFilter(
              'roles',
              filters,
              'contains',
            )}
            filterDropdown={(props) => (
              <FilterDropdown
                {...props}
                clearFilters={() => {
                  props.setSelectedKeys([]);
                  props.confirm?.();
                }}
              >
                <Select
                  options={roleOptions}
                  style={{ width: '150px' }}
                  placeholder="Select Role"
                  loading={rolesLoading}
                />
              </FilterDropdown>
            )}
            render={(value) => {
              return JSON.parse(value || '[]').map((role: string) => (
                <RoleStatusTag key={role} role={role} />
              ));
            }}
          />
          <Table.Column
            dataIndex="isApiKey"
            title="API Key"
            defaultFilteredValue={getDefaultFilter('isApiKey', filters, 'eq')}
            filterDropdown={(props) => (
              <FilterDropdown
                {...props}
                mapValue={(selectedKeys) => {
                  if (selectedKeys?.[0] === 'Yes') return true;
                  if (selectedKeys?.[0] === 'No') return false;
                  return selectedKeys;
                }}
                clearFilters={() => {
                  props.setSelectedKeys([]);
                  props.confirm?.();
                }}
              >
                <Select
                  style={{ width: '120px' }}
                  placeholder="Select"
                  allowClear
                  options={[
                    { label: 'Yes', value: 'Yes' },
                    { label: 'No', value: 'No' },
                  ]}
                />
              </FilterDropdown>
            )}
            render={(value) => (
              <Tag color={value ? 'blue' : 'default'}>
                {value ? 'Yes' : 'No'}
              </Tag>
            )}
          />
          <Table.Column
            dataIndex="isActive"
            title="Active"
            defaultFilteredValue={getDefaultFilter('isActive', filters, 'eq')}
            filterDropdown={(props) => (
              <FilterDropdown
                {...props}
                mapValue={(selectedKeys) => {
                  if (selectedKeys?.[0] === 'Active') return true;
                  if (selectedKeys?.[0] === 'Inactive') return false;
                  return selectedKeys;
                }}
                clearFilters={() => {
                  props.setSelectedKeys([]);
                  props.confirm?.();
                }}
              >
                <Select
                  style={{ width: '120px' }}
                  placeholder="Select"
                  allowClear
                  options={[
                    { label: 'Active', value: 'Active' },
                    { label: 'Inactive', value: 'Inactive' },
                  ]}
                />
              </FilterDropdown>
            )}
            render={(value) => (
              <Tag color={value ? 'green' : 'red'}>
                {value ? 'Active' : 'Inactive'}
              </Tag>
            )}
          />
          <Table.Column
            fixed="right"
            title="Actions"
            dataIndex="actions"
            render={(_, record) => {
              return (
                <Space>
                  <ShowButton
                    hideText
                    size="small"
                    style={{ backgroundColor: 'transparent' }}
                    onClick={() =>
                      setShowModal({ type: 'show', id: record.id })
                    }
                  />
                  <EditButton
                    hideText
                    size="small"
                    style={{ backgroundColor: 'transparent' }}
                    onClick={() =>
                      setShowModal({ type: 'edit', id: record.id })
                    }
                  />
                  <Tooltip title="Generate SQL">
                    <Button
                      size="small"
                      icon={<CodeOutlined />}
                      style={{ backgroundColor: 'transparent' }}
                      onClick={() => handleShowSql(record)}
                    />
                  </Tooltip>
                  <DeleteButton
                    hideText
                    size="small"
                    recordItemId={record.id}
                    style={{ backgroundColor: 'transparent' }}
                  />
                </Space>
              );
            }}
          />
        </Table>
      </List>

      {/* Show Drawer */}
      {showModal.type === 'show' && showModal.id && (
        <ShowDrawer id={showModal.id} onClose={handleModalClose} />
      )}

      {/* Edit Modal */}
      {showModal.type === 'edit' && showModal.id && (
        <EditModal id={showModal.id} onClose={handleModalClose} />
      )}

      {/* Create Modal */}
      {showModal.type === 'create' && (
        <CreateModal onClose={handleModalClose} />
      )}

      {/* SQL Modal */}
      <SqlModal
        open={sqlModal.open}
        onClose={() => setSqlModal({ open: false, title: '', sql: '' })}
        title={sqlModal.title}
        sql={sqlModal.sql}
      />

      {children}
    </div>
  );
};
