import TreeGroup from '@/components/shared/TreeGroup';
import { PADDING_BLOCK, PADDING_IN_LINE } from '@/constants';
import { apiSearchThings } from '@/services/master/ThingController';
import ProCard from '@ant-design/pro-card';
import type { ProFormInstance } from '@ant-design/pro-form';
import { ModalForm } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { useIntl } from '@umijs/max';
import { Input } from 'antd';
import { useEffect, useRef, useState } from 'react';

type Group = {
  id: string;
  metadata?: Record<string, unknown> & {
    code?: string;
    province_code?: string;
  };
};

export default ({
  visible,
  onVisibleChange,
  onSubmit,
  groups,
}: {
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  onSubmit: (
    values: { things: SgwModel.SgwThing[] } & Record<string, unknown>,
  ) => Promise<void>;
  groups: Group[];
}) => {
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance<Record<string, unknown>>>();
  const [selectedRowsState, setSelectedRows] = useState<SgwModel.SgwThing[]>(
    [],
  );
  const [searchValue, setSearchValue] = useState<string>('');
  const [groupCheckedKeys, setGroupCheckedKeys] = useState<string[]>([]);
  const [responsive] = useState(false);

  // Lấy danh sách group IDs từ groups truyền vào
  const accountManagedGroups = Array.isArray(groups)
    ? groups.map((g: Group) => g.id)
    : [];

  useEffect(() => {
    return () => {
      setSearchValue('');
      setSelectedRows([]);
    };
  }, []);

  const columns: ProColumns<SgwModel.SgwThing>[] = [
    {
      title: intl.formatMessage({
        id: 'pages.things.name',
        defaultMessage: 'Name',
      }),
      dataIndex: 'name',
      render: (dom: React.ReactNode, record: SgwModel.SgwThing) => {
        const text = record?.name;
        const isDisabled = !!record?.metadata?.ship_id;
        return (
          <span style={{ color: isDisabled ? '#aaa' : 'inherit' }}>{text}</span>
        );
      },
    },
  ];

  return (
    <ModalForm
      formRef={formRef}
      initialValues={{ things: [] }}
      title={intl.formatMessage({
        id: 'pages.users.share.title',
        defaultMessage: 'Share thing',
      })}
      width="720px"
      visible={visible}
      onVisibleChange={onVisibleChange}
      onFinish={async (values) => {
        // Validate things selected
        if (!selectedRowsState || selectedRowsState.length === 0) {
          formRef.current?.setFields([
            {
              name: 'things',
              errors: [
                intl.formatMessage({
                  id: 'pages.users.things.required',
                  defaultMessage: 'Please select things',
                }),
              ],
            },
          ]);
          return false;
        }

        // Add selected things to values
        const submitValues = {
          ...values,
          things: selectedRowsState,
        };

        await onSubmit(submitValues);
      }}
    >
      {/* Danh sách thiết bị */}
      <div>
        <label style={{ marginBottom: 8, display: 'block', fontWeight: 500 }}>
          {intl.formatMessage({
            id: 'pages.users.things.list',
            defaultMessage: 'List things',
          })}
          <span style={{ color: '#ff4d4f', marginLeft: 4 }}>*</span>
        </label>
        <ProCard split="vertical" bordered>
          <ProCard
            colSpan="240px"
            bodyStyle={
              responsive
                ? {
                    paddingInline: PADDING_IN_LINE,
                    paddingBlock: PADDING_BLOCK,
                  }
                : undefined
            }
          >
            <TreeGroup
              multiple={true}
              groupIds={groupCheckedKeys}
              allowedGroupIds={accountManagedGroups}
              onSelected={(value) => {
                setGroupCheckedKeys(
                  value ? (Array.isArray(value) ? value : [value]) : [],
                );
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }}
            />
          </ProCard>
          <ProCard
            bodyStyle={
              responsive
                ? {
                    paddingInline: PADDING_IN_LINE,
                    paddingBlock: PADDING_BLOCK,
                  }
                : undefined
            }
          >
            <div
              style={{
                display: 'flex',
                justifyContent: 'flex-end',
                marginBottom: 8,
              }}
            >
              <Input.Search
                allowClear
                placeholder={intl.formatMessage({
                  id: 'pages.things.name',
                  defaultMessage: 'Search by name',
                })}
                style={{ width: 240 }}
                onSearch={(value) => {
                  setSearchValue(value);
                  actionRef.current?.reload();
                }}
                onChange={(e) => {
                  if (!e.target.value) {
                    setSearchValue('');
                    actionRef.current?.reload();
                  }
                }}
              />
            </div>
            <ProTable
              actionRef={actionRef}
              columns={columns}
              tableLayout="auto"
              rowKey="id"
              dateFormatter="string"
              pagination={{
                showQuickJumper: false,
                showSizeChanger: false,
                pageSize: 5,
              }}
              request={async (
                params: { current?: number; pageSize?: number } = {},
              ) => {
                const { current = 1, pageSize } = params;
                const size = pageSize || 5;
                const offset = current === 1 ? 0 : (current - 1) * size;

                // Build search body
                const searchBody: MasterModel.SearchThingPaginationBody = {
                  offset: offset,
                  limit: size,
                  order: 'name',
                  dir: 'asc',
                };

                // Add group filter if selected
                if (groupCheckedKeys.length > 0 && groupCheckedKeys[0]) {
                  searchBody.metadata = {
                    group_id: groupCheckedKeys[0], // Use first selected group
                  };
                }

                // Add name filter if search value exists
                if (searchValue) {
                  searchBody.name = searchValue;
                }

                // Call API
                const response = await apiSearchThings(searchBody, 'sgw');

                return {
                  data: response.things || [],
                  success: true,
                  total: response.total || 0,
                };
              }}
              search={false}
              rowSelection={{
                type: 'radio',
                selectedRowKeys: selectedRowsState
                  .map((row) => row.id)
                  .filter(Boolean) as React.Key[],
                onChange: (_: unknown, selectedRows: SgwModel.SgwThing[]) => {
                  const first = selectedRows?.[0] ? [selectedRows[0]] : [];
                  setSelectedRows(first as SgwModel.SgwThing[]);
                  formRef.current?.setFieldsValue({ things: first });
                },
                getCheckboxProps: (record: SgwModel.SgwThing) => ({
                  // Disable if already linked to a ship (ship_id present)
                  disabled: !!record?.metadata?.ship_id,
                }),
              }}
            />
          </ProCard>
        </ProCard>
      </div>
    </ModalForm>
  );
};
